繁体   English   中英

如何在 cloud-init 配置期间为非 root 用户运行 shell 命令?

[英]How can I run shell commands for non-root user during cloud-init configuration?

在使用cloud-init安装云 VM 期间,例如在安装 Rust 工具链时

#cloud-config
package_upgrade: true
packages:
- apt-transport-https
- build-essential
- cmake
runcmd:
- export RUSTUP_HOME=/opt/rust
- export CARGO_HOME=/opt/rust
- curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | bash -s -- -y --no-modify-path --default-toolchain stable --profile default

我还想在用户空间执行工具链配置rustup default stable以便在用户首次登录时可以使用。

一个关键要素是确定当前安装在 VM 上的(目标/管理员)用户export USER=$(awk -v uid=1000 -F":" '{ if($3==uid){print $1} }' /etc/passwd) ,以便环境变量$USERcloud-init 配置过程中保存用户名。 然后使用sudo -H -u $USER在目标用户的上下文中运行 shell 。 还导入是为了增强用户的环境以包括已安装的工具链 - 永久地扩展.profile或类似的,以及在执行此 shell 操作时临时。

#cloud-config
package_upgrade: true
packages:
- apt-transport-https
- build-essential
- cmake
runcmd:
- export USER=$(awk -v uid=1000 -F":" '{ if($3==uid){print $1} }' /etc/passwd)
- export RUSTUP_HOME=/opt/rust
- export CARGO_HOME=/opt/rust
- curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | bash -s -- -y --no-modify-path --default-toolchain stable --profile default
- echo '\n\n# added by cloud init\nsource /opt/rust/env' >> /home/$USER/.profile
- sudo -H -u $USER bash -c 'source /opt/rust/env && rustup default stable'

查看带有背景信息的完整帖子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM