In ansible how to read file content src and added it to a dest file only if the content is not present in dest?

Viewed 27

In ansible how to read file content source file and added it to a destination file only if the content is not present in the destination file?

Looking to do the below in a more ansible way!

shell: cat /root/.ssh/authorized_keys >> /home/foo/.ssh/authorized_keys
2 Answers

Given the authorized_keys for alice and bob at test_11

root@test_11:/ # cat /home/alice/.ssh/authorized_keys 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbX user@host1
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbY user@host2
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbZ user@host3
root@test_11:/ # cat /home/bob/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbZ user@host3
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbU user@host4

(The module ansible.posix.authorized_key does not test the consistency of the keys.)

Read alice's authorized_keys

    - command: cat /home/alice/.ssh/authorized_keys
      register: out

gives

out.stdout: |-
  ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbX user@host1
  ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbY user@host2
  ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbZ user@host3

Add the keys to bob's authorized_keys

    - authorized_key:
        user: bob
        key: "{{ out.stdout }}"

Run the play in --diff mode. The output shows the module works as expected

TASK [authorized_key] **********************************************
--- before: /home/bob/.ssh/authorized_keys
+++ after: /home/bob/.ssh/authorized_keys
@@ -1,3 +1,5 @@
 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbZ user@host3
 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbU user@host4
+ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbX user@host1
+ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbY user@host2

gives

root@test_11:/ # cat /home/bob/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbZ user@host3
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbU user@host4
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbX user@host1
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzFbY user@host2

Example of a complete playbook for testing

- hosts: test_11
  tasks:
    - command: cat /home/alice/.ssh/authorized_keys
      register: out
    - debug:
        var: out.stdout
    - authorized_key:
        user: bob
        key: "{{ out.stdout }}"

According to the authorized_keys module:

You need to do something like in the example:

- name: Set authorized key in alternate location
  ansible.posix.authorized_key:
    user: username
    state: present
    key: "{{ lookup('file', '/home/username/.ssh/id_rsa.pub') }}"

You need to change user to the proper user and the key for the file where you've the key.

Related