简体   繁体   English

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

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

During installation of a cloud VM with cloud-init eg when installing Rust toolchain在使用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

I also want to execute the toolchain configuration rustup default stable in user space so that it is ready to use when user first signs in.我还想在用户空间执行工具链配置rustup default stable以便在用户首次登录时可以使用。

One key element is to determine the (target/adminsitration) user, that is currently installed on the VM with export USER=$(awk -v uid=1000 -F":" '{ if($3==uid){print $1} }' /etc/passwd) , so that environment variable $USER holds the username during the cloud-init configuration process.一个关键要素是确定当前安装在 VM 上的(目标/管理员)用户export USER=$(awk -v uid=1000 -F":" '{ if($3==uid){print $1} }' /etc/passwd) ,以便环境变量$USERcloud-init 配置过程中保存用户名。 Then to use sudo -H -u $USER to run a shell in target user's context.然后使用sudo -H -u $USER在目标用户的上下文中运行 shell 。 Also import is to enhance the user's environment to include the installed toolchain - permanently with extending .profile or alike as well as temporarily while executing this shell operation.还导入是为了增强用户的环境以包括已安装的工具链 - 永久地扩展.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'

check out complete post with background information查看带有背景信息的完整帖子

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

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