簡體   English   中英

在 cloud-init 腳本中以 root 身份為其他用戶安裝 oh-my-zsh

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

我正在嘗試使用為 ubuntu 用戶安裝的 oh-my-zsh 來引導我的 AWS EC2 ubuntu 服務器。 我有一個以 root 用戶身份(使用 sudo)運行的 cloud-init 腳本(更多信息在這里)。 因此,在我的腳本中,我以 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 .zshrc 時評估一次?

我解決了這個感謝jgshawkey的答案在這里 我使用 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看起來像這樣:

在此處輸入圖片說明

由於我正在創建一個新的用戶/服務器,所以我是這樣做的:

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'

對我來說效果很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM