replace string in file created by root on remote server

8 views
Skip to first unread message

Agoston Bejo

unread,
Apr 14, 2018, 4:01:38 AM4/14/18
to Ansible Project
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?



Kai Stian Olstad

unread,
Apr 14, 2018, 4:42:35 AM4/14/18
to ansible...@googlegroups.com
On Saturday, 14 April 2018 10.01.38 CEST Agoston Bejo wrote:
> 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

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.


--
Kai Stian Olstad

Agoston Bejo

unread,
Apr 15, 2018, 3:32:28 AM4/15/18
to Ansible Project

Hi Kai,

indeed, that seemed to be the problem!


Thank you very much!
Reply all
Reply to author
Forward
0 new messages