Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If condition is true run some include yml files

Tags:

ansible

I have some playbook for ubuntu and centos and I want to use main.yml to check when: ansible_os_family == 'RedHat' or ansible_distribution == 'Centos', run playbooks ( as some ans many :-) ).

When I run just:

-include: centos-xxx.yml
-include: centos-xaa.yml
-include: centos-xsss.yml

It will run all of them

Basically I want that the playbook will run if meet condition.

I didn't find any doc that say how to run include: more then one i am trying to not make task per include if possible.

like image 408
Noam Greenberg Avatar asked Mar 23 '15 15:03

Noam Greenberg


People also ask

Can we use if condition in YAML file?

You cannot use if statements everywhere within your YAML. You'll want to use them only prior to Stages, Jobs, Tasks, and Variables. Using an if statement within the parameters of a job will not work.

Does YAML support conditional statements?

yml file can contain conditions expressions that must be satisfied for the step to execute.

What is condition in Ansible?

Ansible supports conditional evaluations before executing a specific task on the target hosts. If the set condition is true, Ansible will go ahead and perform the task. If the condition is not true (unmet), Ansible will skip the specified task. To implement conditions in Ansible, we use the when keyword.


1 Answers

You can use the when conditional to include files. This is somewhat common, in fact.

- include: centos-xxx.yml
  when: ansible_os_family == 'RedHat' or ansible_distribution == 'Centos'
- include: debian-xxx.yml
  when: ansible_distribution == 'Debian'

Per your comment- if you want to run them in order, you have two options. Here's the straightforward:

- include: centos-a.yml
  when: ansible_os_family == 'RedHat' or ansible_distribution == 'Centos'
- include: centos-b.yml
  when: ansible_os_family == 'RedHat' or ansible_distribution == 'Centos'
- include: centos-c.yml
  when: ansible_os_family == 'RedHat' or ansible_distribution == 'Centos'
- include: centos-d.yml
  when: ansible_os_family == 'RedHat' or ansible_distribution == 'Centos'

Or, you can do this:

- include: centos.yml
  when: ansible_os_family == 'RedHat' or ansible_distribution == 'Centos'

and inside centos.yml:

- include: centos-a.yml
- include: centos-b.yml
- include: centos-c.yml
- include: centos-d.yml
like image 103
tedder42 Avatar answered Oct 27 '22 03:10

tedder42