replace string in file created by root on remote server

Hi!

What I’m trying to do is very “complicated” task:

  1. create a file on the remote server as root (in /root)
  2. replace a string in the file

I just can’t seem to achieve this without resorting to executing shell commands directly. (Any more than I already am, that is.)

Version a)

  • name: create the file as root
    shell: ‘echo “Test_string” > /root/test.txt’
    remote_user: root

  • name: replace ‘’ with ‘-’ in the file
    replace:
    path: “/root/test.txt”
    regexp: '

    replace: ‘-’
    backup: no

==> it fails, because the replace task doesn’t accept either remote_user or sudo_user as a parameter, so it can only be run as the user running the playbook, and that user can’t modify a file created by root

Version b)

  • name: create release information file for all awwphp applications
    shell: ‘echo “Test_string” > /tmp/test.txt’

no remote_user!

  • name: replace ‘’ with ‘-’ in the file
    replace:
    path: “/tmp/test.txt”
    regexp: '

    replace: ‘-’
    backup: no

  • name: copy test.txt into /root
    copy:
    src: “/tmp/test.txt”
    dest: “/root/test.txt”
    remote_src: yes

==> this fails here, because this task doesn’t accept remote_user/sudo_user either, and the regular user running the playbook doesn’t have rights to write into /root

How do you do that with Ansible?

remote_user and become_user(sudo_user is depricated) is a directive for the task, not the module so you indentation is probably wrong.
They must be on the same level as replace.

Hi Kai,

indeed, that seemed to be the problem!

Thank you very much!