sdot257
sdot257

Reputation: 10366

Ansible: How can I Include variable file with conditional statement

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"

Upvotes: 3

Views: 5970

Answers (1)

conorsch
conorsch

Reputation: 1496

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.

Upvotes: 2

Related Questions