I need to use Ansible modules to check if a the file exist, and if it doesn't, then create it and write some data in to it.
If the file exists then check the content, which I am trying to write, is present in that file.
If the content is not present, write the content into it.
If the content is present then do nothing.
My playbook below is not working.
Any suggestions on this?
- hosts: all
tasks:
- name: check for file
stat:
path: "{{item}}"
register: File_status
with_items:
- /etc/x.conf
- /etc/y.conf
- name: Create file
file:
path: "{{item}}"
state: touch
with_items:
- /etc/x.conf
- /etc/y.conf
when: not File_status.stat.exists
- name: add content
blockinfile:
path: /etc/x.conf
insertafter:EOF
block: |
mydata=something
Can you help me with the modules and conditions which can achieve my desired output?
The following will:
changed
changed
, i.e.
# BEGIN ANSIBLE MANAGED BLOCK
mydata=something
mydata2=somethingelse
# END ANSIBLE MANAGED BLOCK
changed
(see the marker
option if you have several blocks to manage in the same file, and dont forget {mark}
in there if you change it).ok
.Please read the module documentation for more info
---
- name: blockinfile example
hosts: localhost
gather_facts: false
tasks:
- name: Update/create block if needed. Create file if not exists
blockinfile:
path: /tmp/testfile.conf
block: |
mydata=something
mydata2=somethingelse
create: true