4

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"

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

#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

这可能吗 ?谢谢!

4

2 回答 2

4

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

config.vm.provision "shell", privileged: false blablabla

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

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

于 2016-02-25T13:33:01.330 回答
3

如果您想让脚本与其他脚本内联,您可以使用如下命令序列。

sudo -u devops /bin/sh <<\DEVOPS_BLOCK
# Become devops user here
id
whoami
# Back to the root user here
DEVOPS_BLOCK
于 2016-02-25T13:40:51.303 回答