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 11:25:18 +00:00
|
|
|
hosts: "{{ hosts_servers }}"
|
2023-07-27 07:23:49 +00:00
|
|
|
gather_facts: yes
|
|
|
|
|
|
|
|
tasks:
|
|
|
|
- name: Read authorized_keys file
|
2023-07-27 09:21:37 +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 09:17:54 +00:00
|
|
|
authorized_key_exists: "{{ authorized_key_output.stdout_lines | length > 0 }}"
|
2023-07-27 07:23:49 +00:00
|
|
|
|
|
|
|
- name: Display result
|
|
|
|
debug:
|
2023-07-27 09:25:41 +00:00
|
|
|
msg: "Authorized key exists: {{ authorized_key_exists }}"
|
2023-07-27 08:37:01 +00:00
|
|
|
|
2023-07-27 09:17:54 +00:00
|
|
|
- name: Add authorized key
|
|
|
|
authorized_key:
|
|
|
|
user: root # Replace with the remote user's name
|
|
|
|
state: present
|
2023-07-27 09:21:37 +00:00
|
|
|
key: "{{ key_to_add }}"
|
2023-07-27 09:13:19 +00:00
|
|
|
when: not authorized_key_exists | default(false)
|