Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 3, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions examples/templates/gcp-linux/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ resource "google_compute_disk" "root" {
name = "coder-${lower(data.coder_workspace.me.owner)}-${lower(data.coder_workspace.me.name)}-root"
type = "pd-ssd"
zone = var.zone
image = "debian-cloud/debian-9"
image = "debian-cloud/debian-10"
lifecycle {
ignore_changes = [image]
}
Expand Down Expand Up @@ -70,21 +70,24 @@ resource "google_compute_instance" "dev" {
email = data.google_compute_default_service_account.default.email
scopes = ["cloud-platform"]
}
# The startup script runs as root with no $HOME environment set up, which can break workspace applications, so
# instead of directly running the agent init script, setup the home directory, write the init script, and then execute
# it.
# The startup script runs as root with no $HOME environment set up, so instead of directly
# running the agent init script, create a user (with a homedir, default shell and sudo
# permissions) and execute the init script as that user.
metadata_startup_script = <<EOMETA
#!/usr/bin/env sh
set -eux

mkdir /root || true
cat <<'EOCODER' > /root/coder_agent.sh
${coder_agent.main.init_script}
EOCODER
chmod +x /root/coder_agent.sh

export HOME=/root
/root/coder_agent.sh
# If user does not exist, create it and set up passwordless sudo
if ! id -u "${local.linux_user}" >/dev/null 2>&1; then
useradd -m -s /bin/bash "${local.linux_user}"
echo "${local.linux_user} ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/coder-user
fi

exec sudo -u "${local.linux_user}" sh -c '${coder_agent.main.init_script}'
EOMETA
}

locals {
# Ensure Coder username is a valid Linux username
linux_user = lower(substr(data.coder_workspace.me.owner, 0, 32))
}