Search code examples
bashubuntuzshoh-my-zshcloud-init

installing oh-my-zsh for a different user as root in cloud-init script


I'm attempting to bootstrap my AWS EC2 ubuntu server with oh-my-zsh installed for the ubuntu user. I have a cloud-init script (more info here) that runs as the root user (with sudo). So, in my script I run the oh-my-zsh installation as the ubuntu user.

#cloud-config
runcmd:
# omitted other commands specific to my server, install zsh at the end
  - apt-get install -y zsh
  - su ubuntu -c 'sh -c "$(curl -fsSL https://raw.githubusercontent.com/coreycole/oh-my-zsh/master/tools/install.sh)"' 
  - chsh -s $(which zsh) ubuntu
# change the prompt to include the server hostname
  - su ubuntu -c echo "echo export PROMPT=\''%{$fg[green]%}%n@%{$fg[green]%}%m%{$reset_color%} ${ret_status} %{$fg[cyan]%}%c%{$reset_color%} $(git_prompt_info)'\'" >> /home/ubuntu/.zshrc
# get environment variables defined above
  - echo "source ~/.profile" >> /home/ubuntu/.zshrc

When the cloud-init finishes and I ssh into the colors are not working in the $PROMPT, I see [green] and [cyan]:

[green]ubuntu@[green]ip-172-31-27-24  [cyan]~

If I run the same PROMPT command as the ubuntu user after ssh'ing in, the colors work correctly:

enter image description here

The problem seems to be how the colors are evaulated when the cloud-init script runs the echo command vs how the colors are evaulated when the ubuntu user runs the echo command. Does anyone know how I might change the PROMPT so the colors are only evaulated once ~/.zshrc is evaulated by the ubuntu user?


Solution

  • I solved this thanks to jgshawkey's answer here. I used bash variables to escape the color codes & commands to postpone their evaluation:

      - apt-get install -y zsh
      - runuser -l ubuntu -c 'sh -c "$(curl -fsSL https://raw.githubusercontent.com/coreycole/oh-my-zsh/master/tools/install.sh)"' 
      - chsh -s $(which zsh) ubuntu
      - fgGreen='%{$fg[green]%}'
      - fgCyan='%{$fg[cyan]%}'
      - fgReset='%{$reset_color%}'
      - retStatus='${ret_status}'
      - gitInfo='$(git_prompt_info)'
      - runuser -l ubuntu -c "echo export PROMPT=\''${fgGreen}%n@%m${fgReset} ${retStatus} ${fgCyan}%c${fgReset} ${gitInfo}'\'" >> /home/ubuntu/.zshrc
      - echo "source ~/.profile" >> /home/ubuntu/.zshrc
    

    It ended up looking like this in my ~/.zshrc:

    enter image description here