Create and then edit file in Ansible problems (authorized_keys)

182 Views Asked by At

I'm doing two easy tasks with ansible.

First i create a new file with content (i exect how role):

- name: Add keys to authorized_keys
  blockinfile:
        owner: user
        group: user
        mode: '0600'
        create: yes
        path: /home/user/.ssh/authorized_keys
        block: |
                line if text
                other line
                more lines

Second task (i exect how second role):

- name: Add more keys to authorized_keys root
  blockinfile:
        path: /home/user/.ssh/test_keys
        block: |
                other and more keys

The problem is that when executing the second task, the existing lines in the file are deleted and only those of the second task remain. What should I do to add the new lines and not delete the existing ones?

1

There are 1 best solutions below

0
On BEST ANSWER

Q: "Existing lines in the file are deleted and only those of the second task remain. What should I do to add the new lines and not delete the existing ones?"

A: Set unique marker_begin and marker_end of the blocks. For example

- name: Add keys to authorized_keys
  blockinfile:
    marker_begin: "BEGIN BLOCK1"
    marker_end: "END BLOCK1"
    owner: user
    group: user
    mode: '0600'
    create: yes
    path: /home/user/.ssh/authorized_keys
    block: |
      line if text
      other line
      more lines

- name: Add more keys to authorized_keys root
  blockinfile:
    marker_begin: "BEGIN BLOCK2"
    marker_end: "END BLOCK2"
    path: /home/user/.ssh/authorized_keys
    block: |
      other and more keys