【问题标题】:Vagrant: how to have shell scripts run prior to ansible provisioning?Vagrant:如何在 ansible 配置之前运行 shell 脚本?
【发布时间】:2022-07-01 15:48:07
【问题描述】:

我们目前遇到了 Vagrant 的问题,需要在配置 Ansible 之前运行某些 CLI 命令:

以下 SSH 命令以非零退出状态响应。 Vagrant 假设这意味着命令失败!

卷曲https://bootstrap.pypa.io/get-pip.py |须藤蟒蛇

来自命令的标准输出:

错误:此脚本不适用于 Python 2.7 支持的最低版本 Python版本是3.7。请用 https://bootstrap.pypa.io/pip/2.7/get-pip.py 代替。

在我们的 Vagrantfile 中,我们添加了以下内容,但是当我们进行配置时,shell 块似乎没有在 Ansible 块之前被调用,因此我们最终不得不将 vagrant ssh 放入容器中,然后手动运行它们:

  config.vm.provision "shell" do |s|
    s.inline = "update-alternatives --install /usr/bin/python python /usr/bin/python2 1"
    s.inline = "update-alternatives --install /usr/bin/python python /usr/bin/python3 2"
    s.inline = "apt install -y python3-setuptools"
  end

  config.vm.provision "ansible_local" do |ansible|
    ansible.compatibility_mode = "2.0"
    ansible.install = true
    ansible.install_mode = "pip_args_only"
    ansible.pip_args = "ansible==#{ANSIBLE_VERSION}"
    ansible.playbook = "deploy-local.yml"
    ansible.galaxy_role_file = "roles.yml"
    ansible.galaxy_roles_path = "/tmp/galaxy_roles"
  end

谁能建议如何强制配置块的顺序?

【问题讨论】:

  • Vagrantfile 是强制执行的,因此很可能是其他原因。您可能需要指定安装 Ansible 时使用与版本 3 而不是版本 2 的 Python 相关联的 pip(目前您已为 Vagrant 设置了此设置以使用自动/默认逻辑),或者指定 python 解释器设置Ansible 在版本 3 中使用 Python。

标签: ansible vagrant vagrant-provision


【解决方案1】:

默认情况下,一些类似 debian 的发行版,例如 Ubuntu 20.04,有一个指向 python2python 链接。虽然版本python3 也存在。如果没有,您需要更改此行为并添加 pip3 版本。例如配置块将如下所示:

   # Change link to python3 and install pip3 
   config.vm.provision "shell",
     inline: "sudo ln -f /usr/bin/python3 /usr/bin/python && sudo apt install python3-pip"
    
   # Run Ansible from the Vagrant Host
   config.vm.provision "ansible_local" do |ansible|
     ansible.playbook = "playbook.yml"
     ansible.install_mode = "pip"
   end

【讨论】: