【问题标题】:Ansible with Vagrant: read inventory from Vagrantfile "extra_vars"Ansible with Vagrant: 从 Vagrantfile "extra_vars" 读取库存
【发布时间】:2014-05-25 08:38:00
【问题描述】:

我们的本地开发盒正在运行 Virtualbox/Vagrant,并由 ansible 提供。现在我们为盒子设置了一个固定的 IP 地址,我们需要在三个不同的地方使用它。我们的 Vagrantfile 看起来像这样:

# Set the Vagrantbox IP address
VAGRANT_NETWORK_IP = "10.0.0.10"

# Set the Ansible configuration environment variable
ENV['ANSIBLE_CONFIG'] = "./ansible/.ansible.cfg"

Vagrant.configure("2") do |config|
  config.vm.box     = "ubuntu-precise-64"
  config.vm.box_url = "http://cloud-images.ubuntu.com/vagrant/precise/current/precise-server-cloudimg-amd64-vagrant-disk1.box"
  config.vm.network "forwarded_port", guest: 80, host: 8080
  config.vm.network :private_network, ip: VAGRANT_NETWORK_IP
  config.vm.synced_folder ".", "/var/www"

  config.vm.provision "ansible" do |ansible|
    ansible.playbook       = "ansible/playbook.yml"
    ansible.limit          = "all"
    ansible.inventory_path = "ansible/hosts/vagrant"
    ansible.extra_vars     = {target: VAGRANT_NETWORK_IP}
  end

end

还有我们的 ansible 剧本:

---
- hosts: "{{ target }}"
  sudo: yes
  roles:
    # ...

还有我们的库存文件:

10.0.0.10 ansible_ssh_user=vagrant ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key

我们通过使用变量 VAGRANT_NETWORK_IP 重用了 Vagrantfile 中的 IP 地址。但是,我们仍然需要在清单中设置此 IP 地址。 是否可以在清单文件中使用 ansible 变量作为主机?简单地在库存中使用{{target}} 是行不通的。

或者,或者,有没有办法让这更容易?如果可能的话,我们想在一个文件中配置盒子的 IP 地址。

【问题讨论】:

    标签: vagrant provisioning ansible


    【解决方案1】:

    Vagrantfile 只是一个普通的 ruby​​ 文件,因此您可以从中生成库存文件:

    File.open('ansible/hosts/vagrant' ,'w') do |f|
      f.write "[default]\n"
      f.write "#{VAGRANT_NETWORK_IP} ansible_ssh_user=vagrant ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key\n"
    end
    

    默认情况下,vagrant 框以名称“default”开头,因此我通常将 ansible 托管主机限制为 vagrant 的主机(您可以设置 ansible.limit = “default”)。

    如果您想在一个库存中拥有多个 vagrant 盒子,您可以在一个 Vagrantfile 中定义这些盒子并为其生成库存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-22
      • 2023-04-05
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 2015-09-13
      相关资源
      最近更新 更多