Make gcp-linux example template use a non-root user (#2480)

* make gcp-linux example template use a non-root user

* don't try to create user account if it already exists

* upgrade to debian-10 image since debian-9 is no longer available
This commit is contained in:
David Wahler
2022-08-03 18:07:10 -05:00
committed by GitHub
parent fd4e2cc331
commit 9f54fa8e52

View File

@ -39,7 +39,7 @@ resource "google_compute_disk" "root" {
name = "coder-${lower(data.coder_workspace.me.owner)}-${lower(data.coder_workspace.me.name)}-root" name = "coder-${lower(data.coder_workspace.me.owner)}-${lower(data.coder_workspace.me.name)}-root"
type = "pd-ssd" type = "pd-ssd"
zone = var.zone zone = var.zone
image = "debian-cloud/debian-9" image = "debian-cloud/debian-10"
lifecycle { lifecycle {
ignore_changes = [image] ignore_changes = [image]
} }
@ -70,21 +70,24 @@ resource "google_compute_instance" "dev" {
email = data.google_compute_default_service_account.default.email email = data.google_compute_default_service_account.default.email
scopes = ["cloud-platform"] scopes = ["cloud-platform"]
} }
# The startup script runs as root with no $HOME environment set up, which can break workspace applications, so # The startup script runs as root with no $HOME environment set up, so instead of directly
# instead of directly running the agent init script, setup the home directory, write the init script, and then execute # running the agent init script, create a user (with a homedir, default shell and sudo
# it. # permissions) and execute the init script as that user.
metadata_startup_script = <<EOMETA metadata_startup_script = <<EOMETA
#!/usr/bin/env sh #!/usr/bin/env sh
set -eux set -eux
mkdir /root || true # If user does not exist, create it and set up passwordless sudo
cat <<'EOCODER' > /root/coder_agent.sh if ! id -u "${local.linux_user}" >/dev/null 2>&1; then
${coder_agent.main.init_script} useradd -m -s /bin/bash "${local.linux_user}"
EOCODER echo "${local.linux_user} ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/coder-user
chmod +x /root/coder_agent.sh fi
export HOME=/root
/root/coder_agent.sh
exec sudo -u "${local.linux_user}" sh -c '${coder_agent.main.init_script}'
EOMETA EOMETA
} }
locals {
# Ensure Coder username is a valid Linux username
linux_user = lower(substr(data.coder_workspace.me.owner, 0, 32))
}