【问题标题】:installing oh-my-zsh for a different user as root in cloud-init script在 cloud-init 脚本中以 root 身份为不同的用户安装 oh-my-zsh
【发布时间】:2018-09-20 00:35:25
【问题描述】:

我正在尝试使用为 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 完成并且我 ssh 进入颜色在 $PROMPT 中不起作用时,我看到 [green][cyan]

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

如果我在 ssh 后运行与 ubuntu 用户相同的 PROMPT 命令,颜色将正常工作:

问题似乎是当 cloud-init 脚本运行 echo 命令时如何评估颜色与 ubuntu 用户运行 echo 命令时如何评估颜色。有谁知道我可以如何更改 PROMPT 以便仅在 ubuntu 用户评估 ~/.zshrc 时评估颜色?

【问题讨论】:

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


    【解决方案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 中最终看起来像这样:

    【讨论】:

    • 注意你正在运行的脚本不是来自官方的ohmyzsh github脚本。
    【解决方案2】:

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

    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'
    

    对我来说工作得很好。

    【讨论】:

      猜你喜欢
      • 2015-12-23
      • 2021-09-27
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 2015-08-23
      相关资源
      最近更新 更多