Viswesn
Viswesn

Reputation: 4880

How to pass vars in nested Ansible playbook?

I have a nested ansible playbook (master) file and I want to call included playbook (slave) with their own JSON vars.

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 should make use of "vars/slave_first_vars.json" file and slave_second.yaml should make use of "vars/slave_second_vars.json" file.

Upvotes: 1

Views: 2016

Answers (2)

Arbab Nazar
Arbab Nazar

Reputation: 23811

In your scenario, I'll use like this, 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"

While slave_first.yml and slave_second.yml are like this, in my case both are same but you get an idea that how you can use them: slave_first.yml:

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

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

slave_second.yml:

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

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

Now come to the different variable part: slave_first_vars.yml: in your case it will be json

---
DOMAIN_NAME: "first.com"

slave_second_vars.yml:

---
DOMAIN_NAME: "second.com"

Then you can run and verify that if work as expected:

➤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

Hope that might help you!

Upvotes: 0

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68329

When including playbooks you can only override variables with vars statement, like:

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

There are no other options for PlaybookInclude.

If you need to load variables from files, you have to use vars_files or include_vars inside your slave playbooks.

Upvotes: 3

Related Questions