Ansible - include_vars

Often, variables are created in a playbook, like this.

---
- hosts: all
  vars:
    foo: hello
    bar: world

 

Instead of creating variables in a playbook, variables can be created in a file, such as vars.yml or vars.json. Let's say vars.yml contains the following.

foo: Hello

 

include_vars can then be used to load the variables in the file. In this example, the vars.yml file could be in the same directory as the playbook, or in the vars directory (vars/vars.yml).

---
- hosts: all
  tasks:
    - name: include vars.yml
      include_vars: vars.yml

 

Or like this.

---
- hosts: all
  tasks:
    - name: include vars.yml
      include_vars:
        file: vars.yml

 

AVOID TROUBLE

The -e or --extra-vars command line optionExtra Variables in Tower and set_fact module will take precedence over include_vars.

 

If the file is successfully loaded, something like this should be returned.

TASK [include vars.yml]
ok: [server1.example.com]

TASK [debug]
ok: [server1.example.com] => {
    "foo": "Hello"
}

 

On the other hand, let's say vars.yml does not exist. In this scenario, something like this should be returned.

TASK [include vars.yml]
fatal: [server1.example.com]: FAILED! => {"ansible_facts": {}, "ansible_included_var_files": [], "changed": false, "message": "Could not find or access 'vars.yml'\nSearched in:\n\t/usr/local/ansible/vars/vars.yml\n\t/usr/local/ansible/vars.yml\n\t/usr/local/ansible/vars/vars.yml\n\t/usr/local/ansible/vars.yml on the Ansible Controller.\nIf you are using a module and expect the file to exist on the remote, see the remote_src option"}

 

The when parameter can be used to only include variables when a certain condition is met.

---
- hosts: all
  tasks:
    - include_vars: vars.yml
      when: foo is not defined

 

The name parameter can be used to store the variables in vars.yml in a variable, such as my_included_vars.

---
- hosts: all
  tasks:
    - name: include_vars vars.yml
      include_vars:
        file: vars.yml
        name: my_included_vars

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter e34de in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |