Home > Software engineering >  replace word with content of another file with absolute paths on a remote machine?
replace word with content of another file with absolute paths on a remote machine?

Time:09-07

I have a kickstart file on a remote machine to which I would like to add the ssh key of the user of the remote machine without having that pub file locally. My plan is to add a shell section to the ansible playbook to perform this task. So far my testing was havin 2 files and replacing the required section using sed. I have the following:

file1:

aaa
bbb
text "REPLACE"
ccc

file2:

1233456

using sed -i "s@REPLACE@$(cat file2)@g" file1 it replaces the text.

However when I add the absolute path sed -i "s@REPLACE@$(cat /home/me/test/file2)@g" /home/me/test/file1 the command fails.

What could solve this problem?

edit: to clarify the ansible is provisioning the remote machine for various tasks amongst which is PXE boot server. the solution using ansible replace works very nice in this case.

CodePudding user response:

Given the files

shell> cat /tmp/file1
aaa
bbb
text "REPLACE"
ccc
shell> cat /tmp/file2
1233456

Use the module replace to update the file. For example, the playbook

- hosts: localhost

  tasks:

    - name: Read file2
      command: cat /tmp/file2
      register: file2

    - name: Update file1
      replace:
        path: /tmp/file1
        regexp: '^(.*)REPLACE(.*)$'
        replace: '\g<1>{{ file2.stdout }}\g<2>'

updates the file

shell> cat /tmp/file1
aaa
bbb
text "1233456"
ccc

Running the playbook with --diff mode gives

shell> ansible-playbook pb.yml -D

PLAY [localhost] *****************************************************************************

TASK [Read file2] ****************************************************************************
changed: [localhost]

TASK [Update file1] **************************************************************************
--- before: /tmp/file1
    after: /tmp/file1
@@ -1,4  1,4 @@
 aaa
 bbb
-text "REPLACE"
 text "1233456"
 ccc

changed: [localhost]

PLAY RECAP ***********************************************************************************
localhost: ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
  • Related