Ansible - Get variables from a file using vars_files

Following are the differet ways that variables can be set in Ansible. This list is in the order of precedence, where the option higher in the list takes precedence over options lower in the list.

Often, variables are created using the vars plugin like this.

---
- hosts: localhost
  vars:
    foo: hello
    bar: world
  tasks:
  - debug:
      var: foo
  - debug:
      var: bar
...

 

Instead of creating variables in a playbook, vars_files can be used. 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
  vars_files:
    - vars/vars.yml
  tasks:
    - debug:
        var: foo
...

 

AVOID TROUBLE

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

 

Let's say vars.yml contains the following.

foo: Hello

 

Something like this should be returned.

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

 


Vars File does not exist

Let's say vars.yml does not exist and vars_files is referencing vars.yml.

---
- hosts: all
  vars_files:
  - vars.yml
  tasks:
  - debug:
      var: foo
...

 

This will cause the playbook to fail, returning something like this.

ERROR! vars file vars.yml was not found
Could not find file on the Ansible Controller.
If you are using a module and expect the file to exist on the remote, see the remote_src option

 

If you don't want your playbook to fail if the vars file does not exist, or if you want to print some improved output, you could use stat to determine if the vars file exists and then use include_vars and when to do something based on whether the vars file does or does not exist.

---
- hosts: all
  pre_tasks:
  - stat:
      path: vars.yml
    register: out

  - name: include vars.yml
    include_vars: vars.yml
    when: out.stat.exists == true 

  tasks:
  - debug:
      var: foo
...

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

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 2ec3b in the box below so that we can be sure you are a human.