diff --git a/dotfiles/main.tf b/dotfiles/main.tf index 67a9985..a260309 100644 --- a/dotfiles/main.tf +++ b/dotfiles/main.tf @@ -21,6 +21,13 @@ variable "dotfiles_uri" { default = null } +variable "user" { + type = string + description = "The name of the user to apply the dotfiles to. (optional, applies to the current user by default)" + + default = null +} + data "coder_parameter" "dotfiles_uri" { count = var.dotfiles_uri == null ? 1 : 0 @@ -35,12 +42,14 @@ data "coder_parameter" "dotfiles_uri" { locals { dotfiles_uri = var.dotfiles_uri != null ? var.dotfiles_uri : data.coder_parameter.dotfiles_uri[0].value + user = var.user != null ? var.user : "" } resource "coder_script" "personalize" { agent_id = var.agent_id script = templatefile("${path.module}/run.sh", { DOTFILES_URI : local.dotfiles_uri, + DOTFILES_USER : local.user }) display_name = "Dotfiles" icon = "/icon/dotfiles.svg" diff --git a/dotfiles/run.sh b/dotfiles/run.sh index bc4931b..abd52dc 100644 --- a/dotfiles/run.sh +++ b/dotfiles/run.sh @@ -1,6 +1,21 @@ +#!/usr/bin/env bash DOTFILES_URI="${DOTFILES_URI}" +DOTFILES_USER="${DOTFILES_USER}" if [ -n "$${DOTFILES_URI// }" ]; then - echo "✨ Applying dotfiles for user $USER" - coder dotfiles "$DOTFILES_URI" -y 2>&1 | tee -a ~/.dotfiles.log + if [ -z "$DOTFILES_USER" ]; then + DOTFILES_USER="$USER" + fi + + echo "✨ Applying dotfiles for user $DOTFILES_USER" + + if [ "$DOTFILES_USER" = "$USER" ]; then + coder dotfiles "$DOTFILES_URI" -y 2>&1 | tee -a ~/.dotfiles.log + else + # The "eval echo ~$USER" part is used to dynamically get the home directory of the user, see https://superuser.com/a/484280 + # sudo -u coder sh -c 'eval echo ~$USER' -> "/home/coder" ~/projects/coder-modules + # sudo sh -c 'eval echo ~$USER' -> "/root" + + sudo -u "$DOTFILES_USER" sh -c "$(which coder) dotfiles \"$DOTFILES_URI\" -y 2>&1 | tee -a $(eval echo ~$USER)/.dotfiles.log" + fi fi