Ansible子组变量不会覆盖父组变量

时间:2019-07-14 09:19:48

标签: ansible vagrant

根据有关Assigning a variable to many machines: group variables的Ansible文档,子组变量应该覆盖父组变量。在下面的结构中,未设置在子组上定义的变量。

main.yml

- name: apply common configuration to server
  hosts: all
  user: deployer
  roles:
    - common

group_vars / all.yml

deploy_ssl: false
app_dir: /home/{{ deploy_user }}/{{ app_name }}
venv_dir: "/home/{{ deploy_user }}/venvs/{{ app_name }}"
venv_python: "{{ venv_dir }}/bin/python"

hosts.yml

all:
  children:
    vagrant:
      hosts:
        local:
          ansible_host: 192.168.33.10
          ansible_user: vagrant
          ansible_ssh_private_key_file: ~/workspace/myuser/.vagrant/machines/default/virtualbox/private_key
      vars:
        deploy_ssl: false
        app_dir: /vagrant
        venv_dir: /vagrant/venv
        venv_python: /vagrant/venv/bin/python

ansible-playbook的命令是:

ansible-playbook main.yml -i hosts.yml --limit vagrant --tags wsgi

在VM上检查结果,在hosts.yml文件中使用vars关键字为无业游民定义的变量不会覆盖group_vars/all.yml文件中的值。

我可以为vagrant组专门创建一个文件,因为group_vars/vagrant.yml', and that indeed works as expected. What I don't understand is why the vars keyword inside the hosts.yml`文件无效。

1 个答案:

答案 0 :(得分:1)

Q:“ strsplit('caabacb','(?!b)',perl=TRUE) [[1]] [1] "c" "a" "a" "b" "a" "c" "b"

A:因为与“ The variables defined in the hosts.yml file for vagrant using the vars keyword are not overriding the values from the group_vars/all.yml file”相比,“ inventory group_vars/all”具有更高的优先级。参见Ansible variable precedence

Q:“ inventory file or script group vars

A:在剧本中设置无用主机模式

What would be the command to run ansible only for the vagrant hosts without using --limit?

并运行剧本

- name: apply common configuration to server
  hosts: vagrant

您是对的。和跑步一样

ansible-playbook deploy.yml -i hosts.yml --tags wsgi

使用

ansible-playbook deploy.yml -i hosts.yml --tags wsgi --limit vagrant

要覆盖group_vars / all.yml中的变量,必须将变量放入文件group_vars / vagrant.yml

- name: apply common configuration to server
  hosts: all