Ansible变量未定义

时间:2016-10-30 08:20:48

标签: configuration vagrant ansible jinja2 ansible-playbook

为什么我无法从playbook.yml访问我在库存文件中定义为变量var的变量?

以下是playbook.yml的内容:

---
- name: test ansible local provisioning
  hosts: all
  vars:
    playbook_var: "playbook_var"
  tasks:
    - name: Test ansible is working
      debug: msg="Ansible seems to be working, this variable is from plabook {{ playbook_var }} and this variable is from hosts file {{ hosts_file_var }}"

这是hosts

[all:vars]
hosts_file_var="hosts_file_var"

Ansible抛出以下错误:

TASK [Test ansible is working] *************************************************  
fatal: [ansible_host]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'hosts_file_var' is undefined

The error appears to have been in '/vagrant/provisioning/ansible_host/playbook.yml': line 7, column 7, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:
  tasks:
    - name: Test ansible is working
      ^ here
"}

是否有一些方面我不明白Ansible如何处理变量?

这里也是ansible.cfg。我愿意使用Ansible进行流氓配置:

[defaults]
inventory = hosts
remote_user = vagrant

1 个答案:

答案 0 :(得分:2)

问题是使用了库存文件错误,因此未定义的变量。以下是为什么发生这种情况的长期解释。

问题是vagrant如何执行ansible-playbook命令。在guest虚拟机中执行命令的缺省工作目录不是ansible.playbook配置的路径,而是/vagrant(默认情况下相对于Vagrantfile同步)。这可以通过检查以下配置给出的输出来确认:

ansible.verbose = true

解决方案是提供以下配置(请注意ansible.playbook与guest虚拟机中的此目录相关,并且不必在主机位置执行任何操作。

ansible.provisioning_path = "/vagrant/provisioning/ansible_host"

如果没有给出额外的配置,Vagrant还会生成自己的库存文件并执行以下命令。

Running ansible-playbook...
cd /vagrant/provisioning/ansible_host && PYTHONUNBUFFERED=1 ANSIBLE_FORCE_COLOR=true ansible-playbook --limit="ansible-host" --inventory-file=/tmp/vagrant-ansible/inventory -v playbook.yml
Using /vagrant/provisioning/ansible_host/ansible.cfg as config file

这是让事情顺利进行的所有必要配置

ansible_host.vm.provision "ansible_local" do |ansible|
  ansible.playbook = "playbook.yml"
  ansible.provisioning_path = "/vagrant/provisioning/ansible_host"
  ansible.inventory_path = "hosts"
  ansible.limit = "all"
  ansible.verbose = true
end

请注意,为localhost条目声明ansible_connection=local host / group var也是必要的