user11708158
user11708158

Reputation:

Modules to create file only if it does not exist and write some data

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?

Upvotes: 6

Views: 8449

Answers (2)

Zeitounator
Zeitounator

Reputation: 44595

The following will:

  • Create the file if it does not exist and report changed
  • Add the block at the end of file if it does not exists and report changed, i.e.
    # BEGIN ANSIBLE MANAGED BLOCK
    mydata=something
    mydata2=somethingelse
    # END ANSIBLE MANAGED BLOCK
    
  • Update the block wherever it is in the file if the content changed and report 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).
  • Do nothing if the block is up-to-date anywhere in the file and report 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

Upvotes: 9

Pradeep Kumar H C
Pradeep Kumar H C

Reputation: 686

Here is the possible way to achieve your requirements.

- hosts: localhost
  tasks:
  - name: Create file
    copy:
      content: ""
      dest: "{{item}}"
      force: no
    with_items:
      - /etc/x.conf
      - /etc/y.conf

  - name: add content
    blockinfile:
      path: "{{ item.file_name }}"
      insertafter: EOF
      block: |
        "{{ item.content }}"
    loop:
      - { file_name: '/etc/x.conf', content: 'mydata=something' }
      - { file_name: '/etc/y.conf', content: 'mydata=hey something' }

Upvotes: -1

Related Questions