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
|
|
|
|
|
2023-07-27 09:17:54 +00:00
|
|
|
vars:
|
|
|
|
public_key_to_add: "{ key_to_add}" # Replace with the public key you want to add
|
|
|
|
|
2023-07-27 07:23:49 +00:00
|
|
|
tasks:
|
|
|
|
- name: Read authorized_keys file
|
2023-07-27 09:17:54 +00:00
|
|
|
shell: cat ~/.ssh/authorized_keys | grep "{{ public_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:05:59 +00:00
|
|
|
msg: "Authorized key exists: {{ authorized_key_exists | default(false) }}"
|
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
|
|
|
|
key: "{{ public_key_to_add }}"
|
2023-07-27 09:13:19 +00:00
|
|
|
when: not authorized_key_exists | default(false)
|