【问题标题】:How execute commands as another user during provisioning on Vagrant?在 Vagrant 上配置期间如何以其他用户身份执行命令?
【发布时间】:2016-02-25 13:28:08
【问题描述】:

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

这可能吗?谢谢!

【问题讨论】:

    标签: linux vagrant root sudo vagrant-provision


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 没有看到privileged: false 设置,谢谢。
    【解决方案2】:

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

    sudo -u devops /bin/sh <<\DEVOPS_BLOCK
    # Become devops user here
    id
    whoami
    # Back to the root user here
    DEVOPS_BLOCK
    

    【讨论】:

      猜你喜欢
      • 2014-04-28
      • 2019-11-09
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 2015-12-04
      相关资源
      最近更新 更多