繁体   English   中英

Packer 无法以 sudo 身份执行 shell 配置程序

[英]Packer can't execute shell provisioner as sudo

我在 packer 中有一个shell provisioner器连接到一个带有用户vagrant的盒子

{
  "environment_vars": [
    "HOME_DIR=/home/vagrant"
  ],
  "expect_disconnect": true,
  "scripts": [
    "scripts/foo.sh"
  ],
  "type": "shell"
}

脚本的内容是:

whoami
sudo su
whoami

并且输出奇怪地仍然存在:

==> virtualbox-ovf: Provisioning with shell script: scripts/configureProxies.sh
    virtualbox-ovf: vagrant
    virtualbox-ovf: vagrant

为什么我不能切换到root用户? 如何以 root 身份执行语句? 注意,我不想引用像sudo "statement |foo"这样的所有语句,而是像用sudo su演示的那样全局切换用户

您应该覆盖execute_command 例子:

  "provisioners": [
    {
      "execute_command": "echo 'vagrant' | {{.Vars}} sudo -S -E sh -eux '{{.Path}}'",
      "scripts": [
        "scripts/foo.sh"
      ],
      "type": "shell"
    }
  ],

一个可能的答案似乎是: https : //unix.stackexchange.com/questions/70859/why-doesnt-sudo-su-in-a-shell-script-run-the-rest-of-the-script-as -根

sudo su <<HERE
ls /root
whoami
HERE

也许有更好的答案?

假设您使用的 shell 配置程序是一个 bash 脚本,您可以将我的技术添加到您的脚本中。

function if_not_root_rerun_as_root(){
    install_self
    if [[ "$(id -u)" -ne 0 ]]; then
        run_as_root_keeping_exports "$0" "$@"
        exit $?
    fi
}

function run_as_root_keeping_exports(){
    eval sudo $(for x in $_EXPORTS; do printf '%s=%q ' "$x" "${!x}"; done;) "$@"
}

export EXPORTS="PACKER_BUILDER_TYPE PACKER_BUILD_NAME"
if_not_root_rerun_as_root "$@"

在 StackOverflow 上"$@"有一个很好的解释。

还有另一种解决方案,可以更简单地将 2 个配置器一起使用。

Packer 的 shell 配置器可以使用sudo权限运行bash 首先,您需要使用file配置器将脚本文件从本地机器复制到远程,然后使用shell配置器运行它。

packer.json

{
    "vars": [...],
    "builders": [
        {
            # ...
            "ssh_username": "<some_user_other_than_root_with_passwordless_sudo>",
        }
    ],
    "provisioners": [
        {
            "type": "file",
            "source": "scripts/foo.sh",
            "destination": "~/shell.tmp.sh"
        },
        {
            "type": "shell",
            "inline": ["sudo bash ~/shell.tmp.sh"]
        }
    ]
}

foo.sh

# ...
whoami
sudo su root
whoami
# ...

output

<some_user_other_than_root_with_passwordless_sudo>
root

供应商完成其任务后,您可以使用外壳供应商删除该文件。

packer.json更新

        {
            "type": "shell",
            "inline": ["sudo bash ~/shell.tmp.sh", "rm ~/shell.tmp.sh"]
        }

暂无
暂无

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

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