Running ansible [core 2.16.6]
I need to remove a specific key from the authorized_keys file while leaving all other keys intact. I’ve been able to add a key but it seems that removing a specific key isn’t an option. As I understand things I can add a key to be exclusive but that isn’t a solution as some systems have different keys that need to be there.
Added:
I looked at the state parameter and now see that I can use absent. As long as I don’t have the exclusive parameter set to true will this do what I need?
ptn
(Pierre TOURON)
May 23, 2024, 4:23pm
2
Hi,
Here is a simplified and condensed example of how you could do it:
- hosts: localhost
connection: local
gather_facts: false
vars:
my_pubkeys:
- {user: ptn, pubkeys: ['ssh-rsa myKey1','ssh-rsa myKey2']}
tasks:
- name: Add authorizedkeys
ansible.posix.authorized_key:
user: "{{ item.0.user }}"
key: "{{ item.1 }}"
path: "/tmp/{{ item.0.user }}.authorized_keys"
manage_dir: no
state: present
loop: "{{ my_pubkeys|d([]) | subelements('pubkeys') }}"
register: _addauthorizedkeys_debug
- name: "[DEBUG] Print added public keys"
ansible.builtin.debug:
msg:
- "Pubkeys : {{ item.key }}"
- "Added to file: {{ item.keyfile }}"
- "For user : {{ item.user }}"
with_items: "{{ _addauthorizedkeys_debug | json_query('results[*].invocation.module_args') }}"
- name: Remove specific authorizedkey
ansible.posix.authorized_key:
user: "{{ item.0.user }}"
key: 'ssh-rsa myKey2'
path: "/tmp/{{ item.0.user }}.authorized_keys"
manage_dir: no
state: absent
loop: "{{ my_pubkeys|d([]) | subelements('pubkeys') }}"
register: _removeauthorizedkeys_debug
- name: "[DEBUG] Print removed public keys"
ansible.builtin.debug:
msg:
- "Pubkeys : {{ item.key }}"
- "Removed from file: {{ item.keyfile }}"
- "For user : {{ item.user }}"
with_items: "{{ _removeauthorizedkeys_debug | json_query('results[*].invocation.module_args') }}"
$ cat /tmp/ptn.authorized_keys
ssh-rsa myKey1
To adjust to your needs.
1 Like