如何在 Ansible 中传递变量?

How to pass variable in Ansbile?

无法找出为什么在 Ansible 2.3.1.0 中没有获取变量。

文件结构:

.
├── ansible.cfg
├── group_vars
│   └── test1.yml
├── hosts
├── host_vars
│   └── test1
├── roles
│   └── install
│       └── tasks
│           └── main.yml
├── testing.retry
└── testing.yml

group_vars/test1.yml:

---
test_var: "This is from host_vars file"

content of host_vars/test1:

---
test_var: "This is from host_vars file"

roles/install/tasks/main.yml的内容:

---

- name: Debug
  debug: var=test_var

结果是:

 ansible-playbook -i hosts testing.yml 

PLAY [This is testing] *****************************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [localhost]

TASK [install : Debug] *****************************************************************************************************************************************************
ok: [localhost] => {
    "test_var": "VARIABLE IS NOT DEFINED!"
}

PLAY RECAP *****************************************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0   

预期输出:

test_var = This is from host_vars file
  1. Ansible 未读取 group_vars/test1.yml 因为您没有名为 test1.

    的组

    如果您不想为任何组定义 group_vars,则应将其命名为 all,因此文件应为 group_vars/all.yml.

  2. Ansible 未读取 host_vars/test1 因为您没有名为 test1.

    的主机

    如果您不想为本地主机定义 host_vars,则应将其命名为 localhost,因此文件应为 host_vars/localhost.yml.