以root用户身份在cloud-init脚本中为其他用户安装oh-my-zsh

时间:2018-09-20 00:35:25

标签: bash ubuntu zsh oh-my-zsh cloud-init

我试图使用为ubuntu用户安装了oh-my-zsh引导我的AWS EC2 ubuntu服务器。我有一个以root用户(带有sudo)运行的cloud-init脚本(更多信息here)。因此,在我的脚本中,我以ubuntu用户身份运行oh-my-zsh安装。

#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

当cloud-init结束并且我在$PROMPT中使用ssh进行颜色转换时,我看到[green][cyan]

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

如果在ssh进入后与ubuntu用户运行相同的PROMPT命令,则颜色可以正常工作:

enter image description here

问题似乎是cloud-init脚本运行echo命令时如何评估颜色,而ubuntu用户运行echo命令时如何评估颜色。有人知道我将如何更改PROMPT,以便仅在ubuntu用户撤消~/.zshrc后才撤消颜色吗?

2 个答案:

答案 0 :(得分:1)

我感谢jgshawkey的回答here解决了这个问题。我使用bash变量来转义颜色代码和命令以推迟其评估:

  - 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

最终在我的~/.zshrc中看起来像这样:

enter image description here

答案 1 :(得分:1)

由于我正在创建新的用户/服务器,所以我这样做:

user=you user here
pass=you password here

apt install -y zsh curl wget # considering you currently are root

#creates a new user with password and zsh as default shell
useradd "$user" -m -p $(openssl passwd -1 "$pass") -s $(which zsh)
usermod -aG sudo "$user" # append to sudo and user group (optional)

# mind the command above, with the parameter --unattended which means "no questions" and "no set default to zsh"
runuser -l $user -c 'sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended'

对我来说很好。