2023-07-27 07:23:49 +00:00
|
|
|
---
|
2023-07-27 08:37:01 +00:00
|
|
|
- name: Check and Add Authorized Key
|
2023-07-27 08:44:01 +00:00
|
|
|
hosts: "{{ host }}"
|
2023-07-27 07:23:49 +00:00
|
|
|
gather_facts: yes
|
|
|
|
|
|
|
|
tasks:
|
|
|
|
- name: Read authorized_keys file
|
2023-07-27 08:50:58 +00:00
|
|
|
shell: cat ~/.ssh/authorized_keys | grep "{{ key_to_add }}"
|
2023-07-27 08:27:35 +00:00
|
|
|
register: authorized_key_output
|
2023-07-27 07:23:49 +00:00
|
|
|
ignore_errors: yes
|
|
|
|
|
|
|
|
- name: Check if authorized key exists
|
|
|
|
set_fact:
|
2023-07-27 08:27:35 +00:00
|
|
|
authorized_key_exists: "{{ authorized_key_output.stdout | length > 0 }}"
|
|
|
|
when: authorized_key_output.rc == 0
|
2023-07-27 07:23:49 +00:00
|
|
|
|
|
|
|
- name: Display result
|
|
|
|
debug:
|
2023-07-27 09:05:59 +00:00
|
|
|
msg: "Authorized key exists: {{ authorized_key_exists | default(false) }}"
|
2023-07-27 08:37:01 +00:00
|
|
|
|
|
|
|
- name: Add authorized key
|
|
|
|
authorized_key:
|
|
|
|
user: root # Replace with the remote user's name
|
|
|
|
state: present
|
2023-07-27 08:48:31 +00:00
|
|
|
key: "{{ key_to_add }}"
|
2023-07-27 09:05:59 +00:00
|
|
|
when: authorized_key_exists | default(false) | not
|