1

I am using Ansible to automate some tasks when installing some applications.

In some point, I want to check if in a file, some lines are present. In the file are several lines always in the same order with the same content. And I want to check that no extra lines appear inserted between the previous lines.

I think that the correct command is blockinfile, mixed with state: present to assure that the lines are there. Also I use check_mode to not change the file. Then the task is:

- name: Check content of file
  delegate_to: localhost
  blockinfile:
    dest: "{{ file.path }}"
    block: 
      line 1 text....
      line 2 text....
      line 3 text....
    state: present
  check_mode: yes

But, the task does not fail neither if the block is present or not. And Ansible continues without stopping. As suggested in this answer. I can add failed_when as:

- name: Check content of file
  delegate_to: localhost
  blockinfile:
    dest: "{{ file.path }}"
    block: 
      line 1 text....
      line 2 text....
      line 3 text....
    state: present
  check_mode: yes
  register: block_exists
  failed_when: (block_exists | changed)

Always block_exists is marked as changed.

Is blockinfilethe correct command for this? How can I check if a set of lines exists in a file or not?

techraf
  • 64,883
  • 27
  • 193
  • 198
King Midas
  • 1,442
  • 4
  • 29
  • 50

1 Answers1

2

Block of the blockinfile module is a multiline text marked by starting and ending mark (by default added in a form of a comment).

For your use case using replace module in check mode is appropriate:

- name: Check content of file
  delegate_to: localhost
  replace:
    path: "{{ file.path }}"
    regexp: |
      line 1 text....
      line 2 text....
      line 3 text....
  check_mode: yes
  register: block_exists
  failed_when: block_exists is changed
techraf
  • 64,883
  • 27
  • 193
  • 198
  • I have tried this option, and the task never fails. Does not matter if one line text in the `regexp` is contained in the file or it isn't. – King Midas Apr 04 '18 at 13:52
  • So you are doing something wrong, because it **does** fail if the multiline text is present with the error: `FAILED! => {"changed": true, "failed_when_result": true, "msg": "1 replacements made"}`. – techraf Apr 04 '18 at 19:44
  • Partii karły remember that `regexp` value is a regular expression. You might need to escape certain characters to get a match. – techraf Apr 04 '18 at 23:32
  • Ok, I have escaped the characters, but I am going to check the complete test to find some possible missing ones. – King Midas Apr 05 '18 at 13:59
  • 1
    Ok, it was a missing escaped character. Thanks! – King Midas Apr 05 '18 at 14:07