【问题标题】:Set host name for Vagrant VM in Ansible在 Ansible 中设置 Vagrant VM 的主机名
【发布时间】:2015-12-05 16:45:30
【问题描述】:

为了测试 Ansible,我设置了一个 Vagrant VM,可以使用 vagrant provision 进行配置

config.vm.provision "ansible" do |ansible|
  ansible.playbook = "site.yml"
end

Vagrantfile。这在我将hosts 设置为all 时有效,

- hosts: all
  sudo: true
  roles:
    - common
    - ssl
    - webserver

或者,文件

.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory

Vagrant 自己生成的说

default ansible_ssh_host=127.0.0.1 ansible_ssh_port=2222

表示 Vagrant VM 的名称是 default。因此,

- hosts: default

也做我想做的事。不过,我想为 VM 指定一个更具体的名称(例如,vagrant)。

有没有办法将该名称更改为其他名称?

【问题讨论】:

    标签: vagrant ansible vagrantfile


    【解决方案1】:

    诀窍是定义虚拟机(这里有 2 个虚拟机 productionstaging):

    config.vm.define "production" do |production|
      production.vm.hostname = "production.example.com"
    end
    
    config.vm.define "staging" do |staging|
      staging.vm.hostname = "staging.example.com"
    end
    

    然后 vagrant 生成以下清单:

    production ansible_ssh_host=127.0.0.1 ansible_ssh_port=2222
    staging ansible_ssh_host=127.0.0.1 ansible_ssh_port=2200
    

    另见this answer

    【讨论】:

      【解决方案2】:

      仅更改 .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory 中的清单主机名,请使用:

      config.vm.define "myvm"
      

      这将生成以下内容:

      # Generated by Vagrant
      myvm ansible_ssh_host=127.0.0.1 ansible_ssh_port=2222
      

      因此,ansible inventory_hostname 将变为 myvm

      如果您想更改机器的主机名,请使用:

      config.vm.define "myvm" do |myvm|
        myvm.vm.hostname = "myvm.example.com"
      end
      

      【讨论】:

        【解决方案3】:

        您可以从 vagrant 文档中读取 The inventory file

        如果你想更改虚拟机的名称,你可以有类似的东西

        Vagrant.configure("2") do |config|
          config.vm.define "host1"
          config.vm.provision "ansible" do |ansible|
            ansible.playbook = "site.yml"
        

        这将产生库存文件

        # Generated by Vagrant
        
        host1 ansible_ssh_host=...
        

        请注意,vagrant 还提出了一个static inventory 选项,它允许您编写自己的库存文件并使用inventory_path 选项进行引用

        【讨论】:

        • 这只会更改 VM 中的 hostname,而不是 .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory 的内容,因此也不是 Ansible 所指的名称。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-22
        • 1970-01-01
        • 2013-08-08
        • 2014-06-11
        • 1970-01-01
        相关资源
        最近更新 更多