Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: How can I Include variable file with conditional statement

Tags:

ansible

I have three sets of servers. Depending on the hostname, I want the client to grab the correct file. I tested the playbook on a server with the word "batch" but it picks up both files group_vars/perl and group_vars/batch

pre_tasks:
  - include_vars: group_vars/web
    when: "'web' in ansible_hostname"
  - include_vars: group_vars/batch
    when: "'web' not in ansible_hostname"
  - include_vars: group_vars/perl
    when: "'web' not in ansible_hostname" or "'batch' not in ansible_hostname"
like image 478
sdot257 Avatar asked Jan 25 '26 13:01

sdot257


1 Answers

Ansible will handle group_vars for you. For any hosts in the group web, the vars at group_vars/web (or group_vars/web.yml) will be automatically included. See Splitting Out Host and Group Specific Data in the Ansible docs.

To answer your question about conditional variable includes, the examples you gave are the correct syntax. Here's another example, not using group_vars:

- include_vars: vars/{{ ansible_distribution}}_packages.yml
  when: install_extra_packages is defined and
        install_extra_packages != ''

Note that include_vars accepts expressions, so you can use variables to determine the vars files to pull in dynamically.

like image 135
conorsch Avatar answered Jan 27 '26 02:01

conorsch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!