在 Vagrant 上配置期间如何以另一个用户身份执行命令?

Val*_*lva 4 linux sudo root vagrant vagrant-provision

Vagrant在提供期间执行我的脚本root。但我想在配置期间以另一个用户的身份执行一些命令。这就是我现在正在做的事情:

  su - devops -c "git clone git://github.com/sstephenson/rbenv.git .rbenv"
  su - devops -c "echo 'export PATH=\"$HOME/.rbenv/bin:$PATH\"' >> ~/.bash_profile"
  su - devops -c "echo 'eval "$(rbenv init -)"' >> ~/.bash_profile"
  su - devops -c "git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build"
  su - devops -c "echo 'export PATH=\"$HOME/.rbenv/plugins/ruby-build/bin:$PATH\"' >> ~/.bash_profile"
  su - devops -c "source ~/.bash_profile"
Run Code Online (Sandbox Code Playgroud)

但我想让它变得更好,像这样:

#become devops user here

git clone git://github.com/sstephenson/rbenv.git .rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
echo 'eval "$(rbenv init -)"' >> ~/.bash_profile

git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile

# back to the root user here
Run Code Online (Sandbox Code Playgroud)

这可能吗 ?谢谢你!

Fré*_*nri 5

运行配置时,vagrant 默认情况下将以 root 身份运行,您可以通过将配置设置为来更改此行为

config.vm.provision "shell", privileged: false blablabla
Run Code Online (Sandbox Code Playgroud)

然后 vagrant 将使用定义为的用户config.ssh.username,如果未设置,则默认为 vagrant 用户

如果您的系统上有多个用户并且仍然想使用另一个用户,我要做的就是编写一个脚本并执行该脚本su -l newuser -c "path to shell script"