Skip to content

Commit 5b071f4

Browse files
authored
feat(examples/templates): add GCP VM devcontainer template (coder#11246)
1 parent 52b87a2 commit 5b071f4

File tree

8 files changed

+315
-4
lines changed

8 files changed

+315
-4
lines changed

cli/testdata/coder_templates_init_--help.golden

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ USAGE:
66
Get started with a templated template.
77

88
OPTIONS:
9-
--id aws-linux|aws-windows|azure-linux|do-linux|docker|gcp-linux|gcp-vm-container|gcp-windows|kubernetes|nomad-docker
9+
--id aws-devcontainer|aws-linux|aws-windows|azure-linux|do-linux|docker|gcp-devcontainer|gcp-linux|gcp-vm-container|gcp-windows|kubernetes|nomad-docker
1010
Specify a given example template by ID.
1111

1212
———

docs/cli/templates_init.md

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/examples.gen.json

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,20 @@
11
// Code generated by examplegen. DO NOT EDIT.
22
[
3+
{
4+
"id": "aws-devcontainer",
5+
"url": "",
6+
"name": "AWS EC2 (Devcontainer)",
7+
"description": "Provision AWS EC2 VMs with a devcontainer as Coder workspaces",
8+
"icon": "/icon/aws.png",
9+
"tags": [
10+
"vm",
11+
"linux",
12+
"aws",
13+
"persistent",
14+
"devcontainer"
15+
],
16+
"markdown": "\n# Remote Development on AWS EC2 VMs using a Devcontainer\n\nProvision AWS EC2 VMs as [Coder workspaces](https://coder.com/docs/v2/latest) with this example template.\n![Architecture Diagram](./architecture.svg)\n\n\u003c!-- TODO: Add screenshot --\u003e\n\n## Prerequisites\n\n### Authentication\n\nBy default, this template authenticates to AWS using the provider's default [authentication methods](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#authentication-and-configuration).\n\nThe simplest way (without making changes to the template) is via environment variables (e.g. `AWS_ACCESS_KEY_ID`) or a [credentials file](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-format). If you are running Coder on a VM, this file must be in `/home/coder/aws/credentials`.\n\nTo use another [authentication method](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#authentication), edit the template.\n\n## Required permissions / policy\n\nThe following sample policy allows Coder to create EC2 instances and modify\ninstances provisioned by Coder:\n\n```json\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"VisualEditor0\",\n \"Effect\": \"Allow\",\n \"Action\": [\n \"ec2:GetDefaultCreditSpecification\",\n \"ec2:DescribeIamInstanceProfileAssociations\",\n \"ec2:DescribeTags\",\n \"ec2:DescribeInstances\",\n \"ec2:DescribeInstanceTypes\",\n \"ec2:CreateTags\",\n \"ec2:RunInstances\",\n \"ec2:DescribeInstanceCreditSpecifications\",\n \"ec2:DescribeImages\",\n \"ec2:ModifyDefaultCreditSpecification\",\n \"ec2:DescribeVolumes\"\n ],\n \"Resource\": \"*\"\n },\n {\n \"Sid\": \"CoderResources\",\n \"Effect\": \"Allow\",\n \"Action\": [\n \"ec2:DescribeInstanceAttribute\",\n \"ec2:UnmonitorInstances\",\n \"ec2:TerminateInstances\",\n \"ec2:StartInstances\",\n \"ec2:StopInstances\",\n \"ec2:DeleteTags\",\n \"ec2:MonitorInstances\",\n \"ec2:CreateTags\",\n \"ec2:RunInstances\",\n \"ec2:ModifyInstanceAttribute\",\n \"ec2:ModifyInstanceCreditSpecification\"\n ],\n \"Resource\": \"arn:aws:ec2:*:*:instance/*\",\n \"Condition\": {\n \"StringEquals\": {\n \"aws:ResourceTag/Coder_Provisioned\": \"true\"\n }\n }\n }\n ]\n}\n```\n\n## Architecture\n\nThis template provisions the following resources:\n\n- AWS Instance\n\nCoder uses `aws_ec2_instance_state` to start and stop the VM. This example template is fully persistent, meaning the full filesystem is preserved when the workspace restarts. See this [community example](https://github.com/bpmct/coder-templates/tree/main/aws-linux-ephemeral) of an ephemeral AWS instance.\n\n\u003e **Note**\n\u003e This template is designed to be a starting point! Edit the Terraform to extend the template to support your use case.\n\n## code-server\n\n`code-server` is installed via the [`code-server`](https://registry.coder.com/modules/code-server) registry module. For a list of all modules and templates pplease check [Coder Registry](https://registry.coder.com).\n"
17+
},
318
{
419
"id": "aws-linux",
520
"url": "",
@@ -65,6 +80,20 @@
6580
],
6681
"markdown": "\n# Remote Development on Docker Containers\n\nProvision Docker containers as [Coder workspaces](https://coder.com/docs/coder-v2/latest) with this example template.\n\n\u003c!-- TODO: Add screenshot --\u003e\n\n## Prerequisites\n\n### Infrastructure\n\nThe VM you run Coder on must have a running Docker socket and the `coder` user must be added to the Docker group:\n\n```sh\n# Add coder user to Docker group\nsudo adduser coder docker\n\n# Restart Coder server\nsudo systemctl restart coder\n\n# Test Docker\nsudo -u coder docker ps\n```\n\n## Architecture\n\nThis template provisions the following resources:\n\n- Docker image (built by Docker socket and kept locally)\n- Docker container pod (ephemeral)\n- Docker volume (persistent on `/home/coder`)\n\nThis means, when the workspace restarts, any tools or files outside of the home directory are not persisted. To pre-bake tools into the workspace (e.g. `python3`), modify the container image. Alternatively, individual developers can [personalize](https://coder.com/docs/v2/latest/dotfiles) their workspaces with dotfiles.\n\n\u003e **Note**\n\u003e This template is designed to be a starting point! Edit the Terraform to extend the template to support your use case.\n\n### Editing the image\n\nEdit the `Dockerfile` and run `coder templates push` to update workspaces.\n"
6782
},
83+
{
84+
"id": "gcp-devcontainer",
85+
"url": "",
86+
"name": "Google Compute Engine (Devcontainer)",
87+
"description": "Provision a Devcontainer on Google Compute Engine instances as Coder workspaces",
88+
"icon": "/icon/gcp.png",
89+
"tags": [
90+
"vm",
91+
"linux",
92+
"gcp",
93+
"devcontainer"
94+
],
95+
"markdown": "\n# Remote Development in a Devcontainer on Google Compute Engine\n\n![Architecture Diagram](./architecture.svg)\n\n## Prerequisites\n\n### Authentication\n\nThis template assumes that coderd is run in an environment that is authenticated\nwith Google Cloud. For example, run `gcloud auth application-default login` to\nimport credentials on the system and user running coderd. For other ways to\nauthenticate [consult the Terraform\ndocs](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/getting_started#adding-credentials).\n\nCoder requires a Google Cloud Service Account to provision workspaces. To create\na service account:\n\n1. Navigate to the [CGP\n console](https://console.cloud.google.com/projectselector/iam-admin/serviceaccounts/create),\n and select your Cloud project (if you have more than one project associated\n with your account)\n\n1. Provide a service account name (this name is used to generate the service\n account ID)\n\n1. Click **Create and continue**, and choose the following IAM roles to grant to\n the service account:\n\n - Compute Admin\n - Service Account User\n\n Click **Continue**.\n\n1. Click on the created key, and navigate to the **Keys** tab.\n\n1. Click **Add key** \u003e **Create new key**.\n\n1. Generate a **JSON private key**, which will be what you provide to Coder\n during the setup process.\n\n## Architecture\n\nThis template provisions the following resources:\n\n- GCP VM (persistent)\n- GCP Disk (persistent, mounted to root)\n\nCoder persists the root volume. The full filesystem is preserved when the workspace restarts.\n\n\u003e **Note**\n\u003e This template is designed to be a starting point! Edit the Terraform to extend the template to support your use case.\n\n## code-server\n\n`code-server` is installed via the [`code-server`](https://registry.coder.com/modules/code-server) registry module. Please check [Coder Registry](https://registry.coder.com) for a list of all modules and templates.\n"
96+
},
6897
{
6998
"id": "gcp-linux",
7099
"url": "",

examples/examples.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,13 @@ var (
2323
// Only some templates are embedded that we want to display inside the UI.
2424
// The metadata in examples.gen.json is generated via scripts/examplegen.
2525
//go:embed examples.gen.json
26+
//go:embed templates/aws-devcontainer
2627
//go:embed templates/aws-linux
2728
//go:embed templates/aws-windows
2829
//go:embed templates/azure-linux
2930
//go:embed templates/do-linux
3031
//go:embed templates/docker
32+
//go:embed templates/gcp-devcontainer
3133
//go:embed templates/gcp-linux
3234
//go:embed templates/gcp-vm-container
3335
//go:embed templates/gcp-windows

examples/templates/aws-devcontainer/main.tf

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ locals {
145145
146146
# Start envbuilder
147147
docker run --rm \
148+
-h ${lower(data.coder_workspace.me.name)} \
148149
-v /home/${local.linux_user}/envbuilder:/workspaces \
149150
-e CODER_AGENT_TOKEN="${try(coder_agent.dev[0].token, "")}" \
150151
-e CODER_AGENT_URL="${data.coder_workspace.me.access_url}" \
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
display_name: Google Compute Engine (Devcontainer)
3+
description: Provision a Devcontainer on Google Compute Engine instances as Coder workspaces
4+
icon: ../../../site/static/icon/gcp.png
5+
maintainer_github: coder
6+
verified: true
7+
tags: [vm, linux, gcp, devcontainer]
8+
---
9+
10+
# Remote Development in a Devcontainer on Google Compute Engine
11+
12+
![Architecture Diagram](./architecture.svg)
13+
14+
## Prerequisites
15+
16+
### Authentication
17+
18+
This template assumes that coderd is run in an environment that is authenticated
19+
with Google Cloud. For example, run `gcloud auth application-default login` to
20+
import credentials on the system and user running coderd. For other ways to
21+
authenticate [consult the Terraform
22+
docs](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/getting_started#adding-credentials).
23+
24+
Coder requires a Google Cloud Service Account to provision workspaces. To create
25+
a service account:
26+
27+
1. Navigate to the [CGP
28+
console](https://console.cloud.google.com/projectselector/iam-admin/serviceaccounts/create),
29+
and select your Cloud project (if you have more than one project associated
30+
with your account)
31+
32+
1. Provide a service account name (this name is used to generate the service
33+
account ID)
34+
35+
1. Click **Create and continue**, and choose the following IAM roles to grant to
36+
the service account:
37+
38+
- Compute Admin
39+
- Service Account User
40+
41+
Click **Continue**.
42+
43+
1. Click on the created key, and navigate to the **Keys** tab.
44+
45+
1. Click **Add key** > **Create new key**.
46+
47+
1. Generate a **JSON private key**, which will be what you provide to Coder
48+
during the setup process.
49+
50+
## Architecture
51+
52+
This template provisions the following resources:
53+
54+
- GCP VM (persistent)
55+
- GCP Disk (persistent, mounted to root)
56+
57+
Coder persists the root volume. The full filesystem is preserved when the workspace restarts.
58+
59+
> **Note**
60+
> This template is designed to be a starting point! Edit the Terraform to extend the template to support your use case.
61+
62+
## code-server
63+
64+
`code-server` is installed via the [`code-server`](https://registry.coder.com/modules/code-server) registry module. Please check [Coder Registry](https://registry.coder.com) for a list of all modules and templates.

examples/templates/gcp-devcontainer/architecture.svg

Lines changed: 8 additions & 0 deletions
Loading
Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
terraform {
2+
required_providers {
3+
coder = {
4+
source = "coder/coder"
5+
}
6+
google = {
7+
source = "hashicorp/google"
8+
}
9+
}
10+
}
11+
12+
provider "coder" {
13+
}
14+
15+
variable "project_id" {
16+
description = "Which Google Compute Project should your workspace live in?"
17+
}
18+
19+
data "coder_parameter" "zone" {
20+
name = "zone"
21+
display_name = "Zone"
22+
description = "Which zone should your workspace live in?"
23+
type = "string"
24+
icon = "/emojis/1f30e.png"
25+
default = "us-central1-a"
26+
mutable = false
27+
option {
28+
name = "North America (Northeast)"
29+
value = "northamerica-northeast1-a"
30+
icon = "/emojis/1f1fa-1f1f8.png"
31+
}
32+
option {
33+
name = "North America (Central)"
34+
value = "us-central1-a"
35+
icon = "/emojis/1f1fa-1f1f8.png"
36+
}
37+
option {
38+
name = "North America (West)"
39+
value = "us-west2-c"
40+
icon = "/emojis/1f1fa-1f1f8.png"
41+
}
42+
option {
43+
name = "Europe (West)"
44+
value = "europe-west4-b"
45+
icon = "/emojis/1f1ea-1f1fa.png"
46+
}
47+
option {
48+
name = "South America (East)"
49+
value = "southamerica-east1-a"
50+
icon = "/emojis/1f1e7-1f1f7.png"
51+
}
52+
}
53+
54+
provider "google" {
55+
zone = data.coder_parameter.zone.value
56+
project = var.project_id
57+
}
58+
59+
data "google_compute_default_service_account" "default" {
60+
}
61+
62+
data "coder_workspace" "me" {
63+
}
64+
65+
resource "google_compute_disk" "root" {
66+
name = "coder-${data.coder_workspace.me.id}-root"
67+
type = "pd-ssd"
68+
image = "debian-cloud/debian-12"
69+
lifecycle {
70+
ignore_changes = [name, image]
71+
}
72+
}
73+
74+
data "coder_parameter" "repo_url" {
75+
name = "repo_url"
76+
display_name = "Repository URL"
77+
default = "https://github.com/coder/envbuilder-starter-devcontainer"
78+
description = "Repository URL"
79+
mutable = true
80+
}
81+
82+
resource "coder_agent" "dev" {
83+
count = data.coder_workspace.me.start_count
84+
arch = "amd64"
85+
auth = "token"
86+
os = "linux"
87+
dir = "/workspaces/${trimsuffix(basename(data.coder_parameter.repo_url.value), ".git")}"
88+
connection_timeout = 0
89+
90+
metadata {
91+
key = "cpu"
92+
display_name = "CPU Usage"
93+
interval = 5
94+
timeout = 5
95+
script = "coder stat cpu"
96+
}
97+
metadata {
98+
key = "memory"
99+
display_name = "Memory Usage"
100+
interval = 5
101+
timeout = 5
102+
script = "coder stat mem"
103+
}
104+
metadata {
105+
key = "disk"
106+
display_name = "Disk Usage"
107+
interval = 5
108+
timeout = 5
109+
script = "coder stat disk"
110+
}
111+
}
112+
113+
module "code-server" {
114+
count = data.coder_workspace.me.start_count
115+
source = "https://registry.coder.com/modules/code-server"
116+
agent_id = coder_agent.dev[0].id
117+
}
118+
119+
resource "google_compute_instance" "vm" {
120+
name = "coder-${lower(data.coder_workspace.me.owner)}-${lower(data.coder_workspace.me.name)}-root"
121+
machine_type = "e2-medium"
122+
# data.coder_workspace.me.owner == "default" is a workaround to suppress error in the terraform plan phase while creating a new workspace.
123+
desired_status = (data.coder_workspace.me.owner == "default" || data.coder_workspace.me.start_count == 1) ? "RUNNING" : "TERMINATED"
124+
125+
network_interface {
126+
network = "default"
127+
access_config {
128+
// Ephemeral public IP
129+
}
130+
}
131+
132+
boot_disk {
133+
auto_delete = false
134+
source = google_compute_disk.root.name
135+
}
136+
137+
service_account {
138+
email = data.google_compute_default_service_account.default.email
139+
scopes = ["cloud-platform"]
140+
}
141+
142+
metadata = {
143+
# The startup script runs as root with no $HOME environment set up, so instead of directly
144+
# running the agent init script, create a user (with a homedir, default shell and sudo
145+
# permissions) and execute the init script as that user.
146+
startup-script = <<-META
147+
#!/usr/bin/env sh
148+
set -eux
149+
150+
# If user does not exist, create it and set up passwordless sudo
151+
if ! id -u "${local.linux_user}" >/dev/null 2>&1; then
152+
useradd -m -s /bin/bash "${local.linux_user}"
153+
echo "${local.linux_user} ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/coder-user
154+
fi
155+
156+
# Check for Docker, install if not present
157+
if ! command -v docker &> /dev/null
158+
then
159+
echo "Docker not found, installing..."
160+
curl -fsSL https://get.docker.com -o get-docker.sh && sudo sh get-docker.sh 2>&1 >/dev/null
161+
sudo usermod -aG docker ${local.linux_user}
162+
newgrp docker
163+
else
164+
echo "Docker is already installed."
165+
fi
166+
# Start envbuilder
167+
docker run --rm \
168+
-h ${lower(data.coder_workspace.me.name)} \
169+
-v /home/${local.linux_user}/envbuilder:/workspaces \
170+
-e CODER_AGENT_TOKEN="${try(coder_agent.dev[0].token, "")}" \
171+
-e CODER_AGENT_URL="${data.coder_workspace.me.access_url}" \
172+
-e GIT_URL="${data.coder_parameter.repo_url.value}" \
173+
-e INIT_SCRIPT="echo ${base64encode(try(coder_agent.dev[0].init_script, ""))} | base64 -d | sh" \
174+
-e FALLBACK_IMAGE="codercom/enterprise-base:ubuntu" \
175+
ghcr.io/coder/envbuilder
176+
META
177+
}
178+
}
179+
180+
locals {
181+
# Ensure Coder username is a valid Linux username
182+
linux_user = lower(substr(data.coder_workspace.me.owner, 0, 32))
183+
}
184+
185+
resource "coder_metadata" "workspace_info" {
186+
count = data.coder_workspace.me.start_count
187+
resource_id = google_compute_instance.vm.id
188+
189+
item {
190+
key = "type"
191+
value = google_compute_instance.vm.machine_type
192+
}
193+
194+
item {
195+
key = "zone"
196+
value = data.coder_parameter.zone.value
197+
}
198+
}
199+
200+
resource "coder_metadata" "home_info" {
201+
resource_id = google_compute_disk.root.id
202+
203+
item {
204+
key = "size"
205+
value = "${google_compute_disk.root.size} GiB"
206+
}
207+
}

0 commit comments

Comments
 (0)