Can I use Ansible authorized_key exclusive with multiple keys?

I am new to using Ansible and read google here and haven't found an answer yet.

My scenario is that I have 1 user on the server, but 2-3 different pub keys that need to insert an authorized_keys file.

I can successfully delete all keys or add all keys using this script:

---
  - hosts: all

 tasks:
  - name: update SSH keys
    authorized_key:
     user: <user>
     key: "{{ lookup('file', item) }}"
     state: present
     #exclusive: yes
    with_fileglob:
      - ../files/pub_keys/*.pub

With the flag, presenthe reads and adds all the keys. With a flag, absentit deletes all the keys listed.

The problem is that I have an old key that is only on the server, and I want to delete / rewrite it, and for future deployments, overwrite any unauthorized keys that may be on the server, and not in my book.

exclusive . , . Ansible , .

pub exclusive ?

+4
3

pub ?

. docs:

: authorized_keys. , . , , with_, , , , , , .

, .
- :

- name: update SSH keys
  authorized_key:
    user: <user>
    key: "{{ lookup('pipe','cat ../files/pub_keys/*.pub') }}"
    state: present
    exclusive: yes

!

+7

, :

---

- hosts: all
  vars_files:
    - roles/users/vars/main.yml
  tasks:
    - name: Allow other users to login to the account
      authorized_key:
        user: user_name
        exclusive: yes
        key: "{{ developers|map(attribute='publish_ssh_key')|join('\n') }}"

roles/users/vars/main.yml :

---

developers:
  - name: user1
    publish_ssh_key: ssh-rsa AAAA...
  - name: user2
    publish_ssh_key: ssh-rsa AAAA...
+2

If you want to avoid the search pipe(for example, since the path does not belong to the role), you can also use a combination of search fileand fileglob:

- name: update SSH keys
  authorized_key:
    user: <user>
    key:  "{% for key in lookup('fileglob', 'pub_keys/*.pub').split(',') %}{{ lookup('file', key) ~ '\n'}}{% endfor %}"
    state: present
    exclusive: yes
+1
source

Source: https://habr.com/ru/post/1650822/


All Articles