Dynamic vars_files inclusion

In certain scenarios, it may be desirable to parameterize the variable files to be loaded. It is possible to do this by using a variable as part of the filename; however, the variable must have a value defined at the time the playbook is parsed, just like when using variables in task names. Let's update our example play to load a variable file based on the data provided at execution time:

--- 
- name: vars 
  hosts: localhost 
  gather_facts: false 
 
  vars_files:
- "{{ varfile }}"

tasks:
- name: a task
debug:
msg: "I am a {{ varname }}"

Now when we execute the playbook, we'll provide the value for varfile with the -e argument:

In addition to the variable value needing to be defined at execution time, the file to be loaded must also exist at execution time. This rule applies even if the file is generated by the Ansible playbook itself. Let's suppose that an Ansible playbook consists of four plays. The first play generates a YAML variable file. Then, further down, the fourth play references this file in a vars_file directive. Although it might initially appear as though this would work, the file does not exist at the point of execution (that is, when ansible-playbook is first run), and hence an error will be reported.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.151