如何在嵌套的Ansible playbook中传递vars?

时间:2017-05-11 06:58:14

标签: ansible

我有一个嵌套的ansible playbook(master)文件,我想用自己的JSON vars调用包含的playbook(slave)。

Master.yaml

- name: this is a play at the top level of a file
  hosts: local
  connection: local
  tasks:
    - debug: msg=hello

- include: slave_first.yaml
- include: slave_second.yaml 

slave_first.yaml应该使用“vars / slave_first_vars.json”文件,slave_second.yaml应该使用“vars / slave_second_vars.json”文件。

2 个答案:

答案 0 :(得分:3)

包含playbooks时,您只能使用vars语句覆盖变量,例如:

- include: slave_first.yaml
  vars:
    myvar: foo
- include: slave_second.yaml
  vars:
    myvar: foo

PlaybookInclude没有其他选项。

如果您需要从文件加载变量,则必须在奴隶剧本中使用vars_filesinclude_vars

答案 1 :(得分:0)

在您的方案中,我会像这样使用master.yml

- hosts: localhost
  connection: local
  tasks:
    - include: slave_first.yml
      vars:
        VAR_FILE: "slave_first_vars"
    - include: slave_second.yml
      vars:
        VAR_FILE: "slave_second_vars"

虽然slave_first.ymlslave_second.yml是这样的,但在我的情况下两者都是相同的但你知道如何使用它们: slave_first.yml:

---
- include_vars: "{{ VAR_FILE }}.yml"

- debug:
   msg: "{{ DOMAIN_NAME }}"

slave_second.yml:

---
- include_vars: "{{ VAR_FILE }}.yml"

- debug:
   msg: "{{ DOMAIN_NAME }}"

现在来到不同的变量部分: 在您的情况下,slave_first_vars.yml:将是json

---
DOMAIN_NAME: "first.com"

slave_second_vars.yml:

---
DOMAIN_NAME: "second.com"

然后,您可以运行并验证是否按预期工作:

➤ansible-playbook -i localhost, master.yml

PLAY [localhost] **********************************************************************************

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

TASK [include_vars] **********************************************************************************
ok: [localhost]

TASK [debug] **********************************************************************************
ok: [localhost] => {
    "changed": false,
    "msg": "first.com"
}

TASK [include_vars] **********************************************************************************
ok: [localhost]

TASK [debug] **********************************************************************************
ok: [localhost] => {
    "changed": false,
    "msg": "second.com"
}

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

希望这对你有所帮助!