File size: 6,118 Bytes
287a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import boto3
import json
import subprocess
import os
import re


def b64text(txt):
    """Generate Base 64 encoded CF json for a multiline string, subbing in values where appropriate"""
    lines = []
    for line in txt.splitlines(True):
        if "${" in line:
            lines.append({"Fn::Sub": line})
        else:
            lines.append(line)
    return {"Fn::Base64": {"Fn::Join": ["", lines]}}


path = os.path.dirname(os.path.realpath(__file__))
version = subprocess.check_output(f"{path}/version").decode("ascii").strip()

with open(f"{path}/templates/docker-compose.yml") as f:
    docker_compose_file = str(f.read())


cloud_config_script = """
#cloud-config
cloud_final_modules:
- [scripts-user, always]
"""

cloud_init_script = f"""
#!/bin/bash
amazon-linux-extras install docker
usermod -a -G docker ec2-user
curl -L https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
systemctl enable docker
systemctl start docker

cat << EOF > /home/ec2-user/docker-compose.yml
{docker_compose_file}
EOF

mkdir /home/ec2-user/config

docker-compose -f /home/ec2-user/docker-compose.yml up -d
"""

userdata = f"""Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0

--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"

{cloud_config_script}

--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

{cloud_init_script}
--//--
"""

cf = {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Create a stack that runs Chroma hosted on a single instance",
    "Parameters": {
        "KeyName": {
            "Description": "Name of an existing EC2 KeyPair to enable SSH access to the instance",
            "Type": "String",
            "ConstraintDescription": "If present, must be the name of an existing EC2 KeyPair.",
            "Default": "",
        },
        "InstanceType": {
            "Description": "EC2 instance type",
            "Type": "String",
            "Default": "t3.small",
        },
        "ChromaVersion": {
            "Description": "Chroma version to install",
            "Type": "String",
            "Default": version,
        },
    },
    "Conditions": {
        "HasKeyName": {"Fn::Not": [{"Fn::Equals": [{"Ref": "KeyName"}, ""]}]},
    },
    "Resources": {
        "ChromaInstance": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
                "ImageId": {
                    "Fn::FindInMap": ["Region2AMI", {"Ref": "AWS::Region"}, "AMI"]
                },
                "InstanceType": {"Ref": "InstanceType"},
                "UserData": b64text(userdata),
                "SecurityGroupIds": [{"Ref": "ChromaInstanceSecurityGroup"}],
                "KeyName": {
                    "Fn::If": [
                        "HasKeyName",
                        {"Ref": "KeyName"},
                        {"Ref": "AWS::NoValue"},
                    ]
                },
                "BlockDeviceMappings": [
                    {
                        "DeviceName": {
                            "Fn::FindInMap": [
                                "Region2AMI",
                                {"Ref": "AWS::Region"},
                                "RootDeviceName",
                            ]
                        },
                        "Ebs": {"VolumeSize": 24},
                    }
                ],
            },
        },
        "ChromaInstanceSecurityGroup": {
            "Type": "AWS::EC2::SecurityGroup",
            "Properties": {
                "GroupDescription": "Chroma Instance Security Group",
                "SecurityGroupIngress": [
                    {
                        "IpProtocol": "tcp",
                        "FromPort": "22",
                        "ToPort": "22",
                        "CidrIp": "0.0.0.0/0",
                    },
                    {
                        "IpProtocol": "tcp",
                        "FromPort": "8000",
                        "ToPort": "8000",
                        "CidrIp": "0.0.0.0/0",
                    },
                ],
            },
        },
    },
    "Outputs": {
        "ServerIp": {
            "Description": "IP address of the Chroma server",
            "Value": {"Fn::GetAtt": ["ChromaInstance", "PublicIp"]},
        }
    },
    "Mappings": {"Region2AMI": {}},
}

# Populate the Region2AMI mappings
regions = boto3.client("ec2", region_name="us-east-1").describe_regions()["Regions"]
for region in regions:
    region_name = region["RegionName"]
    ami_result = boto3.client("ec2", region_name=region_name).describe_images(
        Owners=["137112412989"],
        Filters=[
            {"Name": "name", "Values": ["amzn2-ami-kernel-5.10-hvm-*-x86_64-gp2"]},
            {"Name": "root-device-type", "Values": ["ebs"]},
            {"Name": "virtualization-type", "Values": ["hvm"]},
        ],
    )
    img = ami_result["Images"][0]
    ami_id = img["ImageId"]
    root_device_name = img["BlockDeviceMappings"][0]["DeviceName"]
    cf["Mappings"]["Region2AMI"][region_name] = {
        "AMI": ami_id,
        "RootDeviceName": root_device_name,
    }


# Write the CF json to a file
json.dump(cf, open("/tmp/chroma.cf.json", "w"), indent=4)

# upload to S3
s3 = boto3.client("s3", region_name="us-east-1")
s3.upload_file(
    "/tmp/chroma.cf.json",
    "public.trychroma.com",
    f"cloudformation/{version}/chroma.cf.json",
)

# Upload to s3 under /latest version only if this is a release
pattern = re.compile(r"^\d+\.\d+\.\d+$")
if pattern.match(version):
    s3.upload_file(
        "/tmp/chroma.cf.json",
        "public.trychroma.com",
        "cloudformation/latest/chroma.cf.json",
    )
else:
    print(f"Version {version} is not a 3-part semver, not uploading to /latest")