How can I execute task only when file not contain a string?

Hi,

is there a solution more user friendly that http://stackoverflow.com/questions/30786263/only-check-whether-a-line-present-in-a-file-ansible to test if file contain a string?

I don’t like that:

  • name: Check if bash-completion in enable for root user
    command: grep -q “/etc/bash_completion” /root/.bashrc
    register: check_bashcompletion_enabled
    ignore_errors: True

  • name: Enable bach-completion for root user
    command: cp /etc/skel/.bashrc /root/.bashrc
    when: check_bashcompletion_enabled.rc == 1

Do you know a better solution?

Best regards,
Stéphane

What I would do is put the correct .bashrc in Ansible and just use the copy module to copy it to the host(s).

I would like copy only if bash_completion isn’t already present in .bashrc

Then you don't have much choice but go for the solution you posted.

But to make the output nicer I would replace "ignore_errors: True"
with

   failed_when: False

or

   failed_when: check_bashcompletion_enabled.rc > 1
   changed_when: check_bashcompletion_enabled.rc == 1

What is it about your solution you don't like?

Yes, thank it’s better.

My preference in how to achieve this in a more ansible way, is using slurp, and then checking the returned contents:

  • name: Get /root/.bashrc
    slurp:
    src: /root/.bashrc
    register: root_bashrc

  • name: Enable bash-completion for root user
    copy:
    src: /etc/skel/.bashrc
    dest: /root/.bashrc

remote_src: true
when: “‘/etc/bash_completion’ not in root_bashrc.content|b64decode”

I also replaced your command to copy the file, with the copy module, using remote_src=true

it might be easier with the find module

- find: paths=... contains='whatever'
register: found

- command: run if found
  when: found.matched > 0