TemplatesModules
Back to Templates
AWS EC2 (Devcontainer) Icon

AWS EC2 (Devcontainer)

By:
Provision AWS EC2 VMs with a devcontainer as Coder workspaces
Source
README
Resources (3)
Variables (3)

Copy and paste the following into main.tf and run coder template push:

1terraform {
2  required_providers {
3    coder = {
4      source = "coder/coder"
5    }
6    aws = {
7      source = "hashicorp/aws"
8    }
9    envbuilder = {
10      source = "coder/envbuilder"
11    }
12  }
13}
14
15module "aws_region" {
16  source  = "https://registry.coder.com/modules/aws-region"
17  default = "us-east-1"
18}
19
20provider "aws" {
21  region = module.aws_region.value
22}
23
24variable "cache_repo" {
25  default     = ""
26  description = "(Optional) Use a container registry as a cache to speed up builds. Example: host.tld/path/to/repo."
27  type        = string
28}
29
30variable "cache_repo_docker_config_path" {
31  default     = ""
32  description = "(Optional) Path to a docker config.json containing credentials to the provided cache repo, if required. This will depend on your Coder setup. Example: `/home/coder/.docker/config.json`."
33  sensitive   = true
34  type        = string
35}
36
37variable "iam_instance_profile" {
38  default     = ""
39  description = "(Optional) Name of an IAM instance profile to assign to the instance."
40  type        = string
41}
42
43data "coder_workspace" "me" {}
44data "coder_workspace_owner" "me" {}
45
46data "aws_ami" "ubuntu" {
47  most_recent = true
48  filter {
49    name   = "name"
50    values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]
51  }
52  filter {
53    name   = "virtualization-type"
54    values = ["hvm"]
55  }
56  owners = ["099720109477"] # Canonical
57}
58
59data "coder_parameter" "instance_type" {
60  name         = "instance_type"
61  display_name = "Instance type"
62  description  = "What instance type should your workspace use?"
63  default      = "t3.micro"
64  mutable      = false
65  option {
66    name  = "2 vCPU, 1 GiB RAM"
67    value = "t3.micro"
68  }
69  option {
70    name  = "2 vCPU, 2 GiB RAM"
71    value = "t3.small"
72  }
73  option {
74    name  = "2 vCPU, 4 GiB RAM"
75    value = "t3.medium"
76  }
77  option {
78    name  = "2 vCPU, 8 GiB RAM"
79    value = "t3.large"
80  }
81  option {
82    name  = "4 vCPU, 16 GiB RAM"
83    value = "t3.xlarge"
84  }
85  option {
86    name  = "8 vCPU, 32 GiB RAM"
87    value = "t3.2xlarge"
88  }
89}
90
91data "coder_parameter" "root_volume_size_gb" {
92  name         = "root_volume_size_gb"
93  display_name = "Root Volume Size (GB)"
94  description  = "How large should the root volume for the instance be?"
95  default      = 30
96  type         = "number"
97  mutable      = true
98  validation {
99    min       = 1
100    monotonic = "increasing"
101  }
102}
103
104data "coder_parameter" "fallback_image" {
105  default      = "codercom/enterprise-base:ubuntu"
106  description  = "This image runs if the devcontainer fails to build."
107  display_name = "Fallback Image"
108  mutable      = true
109  name         = "fallback_image"
110  order        = 3
111}
112
113data "coder_parameter" "devcontainer_builder" {
114  description  = <<-EOF
115Image that will build the devcontainer.
116Find the latest version of Envbuilder here: https://ghcr.io/coder/envbuilder
117Be aware that using the `:latest` tag may expose you to breaking changes.
118EOF
119  display_name = "Devcontainer Builder"
120  mutable      = true
121  name         = "devcontainer_builder"
122  default      = "ghcr.io/coder/envbuilder:latest"
123  order        = 4
124}
125
126data "coder_parameter" "repo_url" {
127  name         = "repo_url"
128  display_name = "Repository URL"
129  default      = "https://github.com/coder/envbuilder-starter-devcontainer"
130  description  = "Repository URL"
131  mutable      = true
132}
133
134data "coder_parameter" "ssh_pubkey" {
135  name         = "ssh_pubkey"
136  display_name = "SSH Public Key"
137  default      = ""
138  description  = "(Optional) Add an SSH public key to the `coder` user's authorized_keys. Useful for troubleshooting. You may need to add a security group to the instance."
139  mutable      = false
140}
141
142data "local_sensitive_file" "cache_repo_dockerconfigjson" {
143  count    = var.cache_repo_docker_config_path == "" ? 0 : 1
144  filename = var.cache_repo_docker_config_path
145}
146
147data "aws_iam_instance_profile" "vm_instance_profile" {
148  count = var.iam_instance_profile == "" ? 0 : 1
149  name  = var.iam_instance_profile
150}
151
152# Be careful when modifying the below locals!
153locals {
154  # TODO: provide a way to pick the availability zone.
155  aws_availability_zone = "${module.aws_region.value}a"
156  linux_user            = "coder"
157  # Name the container after the workspace and owner.
158  container_name = "coder-${data.coder_workspace_owner.me.name}-${lower(data.coder_workspace.me.name)}"
159  # The devcontainer builder image is the image that will build the devcontainer.
160  devcontainer_builder_image = data.coder_parameter.devcontainer_builder.value
161  # We may need to authenticate with a registry. If so, the user will provide a path to a docker config.json.
162  docker_config_json_base64 = try(data.local_sensitive_file.cache_repo_dockerconfigjson[0].content_base64, "")
163  # The envbuilder provider requires a key-value map of environment variables. Build this here.
164  envbuilder_env = {
165    # ENVBUILDER_GIT_URL and ENVBUILDER_CACHE_REPO will be overridden by the provider
166    # if the cache repo is enabled.
167    "ENVBUILDER_GIT_URL" : data.coder_parameter.repo_url.value,
168    # The agent token is required for the agent to connect to the Coder platform.
169    "CODER_AGENT_TOKEN" : try(coder_agent.dev.0.token, ""),
170    # The agent URL is required for the agent to connect to the Coder platform.
171    "CODER_AGENT_URL" : data.coder_workspace.me.access_url,
172    # The agent init script is required for the agent to start up. We base64 encode it here
173    # to avoid quoting issues.
174    "ENVBUILDER_INIT_SCRIPT" : "echo ${base64encode(try(coder_agent.dev[0].init_script, ""))} | base64 -d | sh",
175    "ENVBUILDER_DOCKER_CONFIG_BASE64" : try(data.local_sensitive_file.cache_repo_dockerconfigjson[0].content_base64, ""),
176    # The fallback image is the image that will run if the devcontainer fails to build.
177    "ENVBUILDER_FALLBACK_IMAGE" : data.coder_parameter.fallback_image.value,
178    # The following are used to push the image to the cache repo, if defined.
179    "ENVBUILDER_CACHE_REPO" : var.cache_repo,
180    "ENVBUILDER_PUSH_IMAGE" : var.cache_repo == "" ? "" : "true",
181    # You can add other required environment variables here.
182    # See: https://github.com/coder/envbuilder/?tab=readme-ov-file#environment-variables
183  }
184  # If we have a cached image, use the cached image's environment variables. Otherwise, just use
185  # the environment variables we've defined above.
186  docker_env_input = try(envbuilder_cached_image.cached.0.env_map, local.envbuilder_env)
187  # Convert the above to the list of arguments for the Docker run command.
188  # The startup script will write this to a file, which the Docker run command will reference.
189  docker_env_list_base64 = base64encode(join("\n", [for k, v in local.docker_env_input : "${k}=${v}"]))
190  # Builder image will either be the builder image parameter, or the cached image, if cache is provided.
191  builder_image = try(envbuilder_cached_image.cached[0].image, data.coder_parameter.devcontainer_builder.value)
192  # User data to start the workspace.
193  user_data = <<-EOT
194  Content-Type: multipart/mixed; boundary="//"
195  MIME-Version: 1.0
196
197  --//
198  Content-Type: text/cloud-config; charset="us-ascii"
199  MIME-Version: 1.0
200  Content-Transfer-Encoding: 7bit
201  Content-Disposition: attachment; filename="cloud-config.txt"
202
203  #cloud-config
204  cloud_final_modules:
205  - [scripts-user, always]
206  hostname: ${lower(data.coder_workspace.me.name)}
207  users:
208  - name: ${local.linux_user}
209    sudo: ALL=(ALL) NOPASSWD:ALL
210    shell: /bin/bash
211    ssh_authorized_keys:
212    - "${data.coder_parameter.ssh_pubkey.value}"
213  # Automatically grow the partition
214  growpart:
215    mode: auto
216    devices: ['/']
217    ignore_growroot_disabled: false
218
219  --//
220  Content-Type: text/x-shellscript; charset="us-ascii"
221  MIME-Version: 1.0
222  Content-Transfer-Encoding: 7bit
223  Content-Disposition: attachment; filename="userdata.txt"
224
225  #!/bin/bash
226  # Install Docker
227  if ! command -v docker &> /dev/null
228  then
229    echo "Docker not found, installing..."
230    curl -fsSL https://get.docker.com -o get-docker.sh && sh get-docker.sh 2>&1 >/dev/null
231    usermod -aG docker ${local.linux_user}
232    newgrp docker
233  else
234    echo "Docker is already installed."
235  fi
236
237  # Set up Docker credentials
238  mkdir -p "/home/${local.linux_user}/.docker"
239  if [ -n "${local.docker_config_json_base64}" ]; then
240     # Write the Docker config JSON to disk if it is provided.
241     printf "%s" "${local.docker_config_json_base64}" | base64 -d | tee "/home/${local.linux_user}/.docker/config.json"
242  else
243    # Assume that we're going to use the instance IAM role to pull from the cache repo if we need to.
244    # Set up the ecr credential helper.
245    apt-get update -y && apt-get install -y amazon-ecr-credential-helper
246    mkdir -p .docker
247    printf '{"credsStore": "ecr-login"}' | tee "/home/${local.linux_user}/.docker/config.json"
248  fi
249  chown -R ${local.linux_user}:${local.linux_user} "/home/${local.linux_user}/.docker"
250
251  # Write the container env to disk.
252  printf "%s" "${local.docker_env_list_base64}" | base64 -d | tee "/home/${local.linux_user}/env.txt"
253
254  # Start envbuilder
255  sudo -u coder docker run \
256    --rm \
257    --net=host \
258    -h ${lower(data.coder_workspace.me.name)} \
259    -v /home/${local.linux_user}/envbuilder:/workspaces \
260    -v /var/run/docker.sock:/var/run/docker.sock \
261    --env-file /home/${local.linux_user}/env.txt \
262    ${local.builder_image}
263  --//--
264  EOT
265}
266
267# Check for the presence of a prebuilt image in the cache repo
268# that we can use instead.
269resource "envbuilder_cached_image" "cached" {
270  count         = var.cache_repo == "" ? 0 : data.coder_workspace.me.start_count
271  builder_image = local.devcontainer_builder_image
272  git_url       = data.coder_parameter.repo_url.value
273  cache_repo    = var.cache_repo
274  extra_env     = local.envbuilder_env
275}
276
277# This is useful for debugging the startup script. Left here for reference.
278# resource local_file "startup_script" {
279#   content  = local.user_data
280#   filename = "${path.module}/user_data.txt"
281# }
282
283resource "aws_instance" "vm" {
284  ami                  = data.aws_ami.ubuntu.id
285  availability_zone    = local.aws_availability_zone
286  instance_type        = data.coder_parameter.instance_type.value
287  iam_instance_profile = try(data.aws_iam_instance_profile.vm_instance_profile[0].name, null)
288  root_block_device {
289    volume_size = data.coder_parameter.root_volume_size_gb.value
290  }
291
292  user_data = local.user_data
293  tags = {
294    Name = "coder-${data.coder_workspace_owner.me.name}-${data.coder_workspace.me.name}"
295    # Required if you are using our example policy, see template README
296    Coder_Provisioned = "true"
297  }
298  lifecycle {
299    ignore_changes = [ami]
300  }
301}
302
303resource "aws_ec2_instance_state" "vm" {
304  instance_id = aws_instance.vm.id
305  state       = data.coder_workspace.me.transition == "start" ? "running" : "stopped"
306}
307
308resource "coder_agent" "dev" {
309  count              = data.coder_workspace.me.start_count
310  arch               = "amd64"
311  auth               = "token"
312  os                 = "linux"
313  dir                = "/workspaces/${trimsuffix(basename(data.coder_parameter.repo_url.value), ".git")}"
314  connection_timeout = 0
315
316  metadata {
317    key          = "cpu"
318    display_name = "CPU Usage"
319    interval     = 5
320    timeout      = 5
321    script       = "coder stat cpu"
322  }
323  metadata {
324    key          = "memory"
325    display_name = "Memory Usage"
326    interval     = 5
327    timeout      = 5
328    script       = "coder stat mem"
329  }
330}
331
332resource "coder_metadata" "info" {
333  count       = data.coder_workspace.me.start_count
334  resource_id = coder_agent.dev[0].id
335  item {
336    key   = "ami"
337    value = aws_instance.vm.ami
338  }
339  item {
340    key   = "availability_zone"
341    value = local.aws_availability_zone
342  }
343  item {
344    key   = "instance_type"
345    value = data.coder_parameter.instance_type.value
346  }
347  item {
348    key   = "ssh_pubkey"
349    value = data.coder_parameter.ssh_pubkey.value
350  }
351  item {
352    key   = "repo_url"
353    value = data.coder_parameter.repo_url.value
354  }
355  item {
356    key   = "devcontainer_builder"
357    value = data.coder_parameter.devcontainer_builder.value
358  }
359}
360
361module "code-server" {
362  count    = data.coder_workspace.me.start_count
363  source   = "registry.coder.com/modules/code-server/coder"
364  version  = "1.0.18"
365  agent_id = coder_agent.dev[0].id
366}
367