Ansible Conditionals When File or Directory Exist | How to Use Condition in Ansible
tags : conditional in ansible, ansible when, when statement, ansible tutorial, ansible playbook, ansible, jobs, ansible roles, ansible facts, ansible debug, when:, conditional statement, ansible create directory,
conditional is used to change a ansible play behavior based on there facts/variable. we can control which tasks/roles will be run or skipped on there targeted hosts/nodes with the help of when statement
conditional is used to change a ansible play behavior based on there facts/variable. we can control which tasks/roles will be run or skipped on there targeted hosts/nodes with the help of when statement
We create a condition_file.yml playbook. You can choose choose any suitable name
To Create condition playbook,
cd /etc/ansible
vi condition_file.yml
---
- hosts: all
gather_facts: false
tasks:
- name: Check File exists or not
stat: path=/tmp/check.txt
register: status
- debug: var=status
Ansible Conditional - File exist |
We used stat module with define the path where we want to check file.
To run playbook
ansible-playbook condition_file.yml
check.txt file not available so it display exists = false, we will use this value, we will create a file if the file does not exist, following example :
- name: Create file if does not exist
file:
state: touch
path: /tmp/check.txt
owner: lokesh
group: lokesh
mode: 0755
when: status.stat.exists == false
Ansible Create Directory - Condition |
ansible-playbook -l 127.0.0.1 condition_file.yml
Our playbook executed now we will check file,
ls -l /tmp/check.txt
Same playbook will work with directory,
---
- hosts: all
gather_facts: false
tasks:
- name: Check directory exists or not
stat: path=/var/lib/linuxtopic
register: status
- name: Create directory if does not exist
file: state=directory path=/var/lib/linuxtopic owner=nobody group=lokesh mode=0775
when: status.stat.exists == false
- name: Update Permission
file: state=directory path=/var/lib/linuxtopic owner=nobody group=lokesh mode=0775
when: status.stat.exists == true
Thanks
End of this ansible conditional tutorial, we need your support so i request you to please comment if something missed by me, share and like this post.
www.linuxtopic.com
Leave a Comment