playbooks/roles/harden_ssh_root_key_only/tasks/main.yml
2026-04-05 16:54:48 +08:00

83 lines
2.2 KiB
YAML

---
- name: Read local SSH public key
ansible.builtin.set_fact:
local_ssh_public_key: "{{ lookup('ansible.builtin.file', local_public_key_path) | trim }}"
- name: Assert local SSH public key exists
ansible.builtin.assert:
that:
- local_ssh_public_key | length > 0
fail_msg: "local_public_key_path must point to a readable SSH public key."
- name: Ensure root SSH directory exists
ansible.builtin.file:
path: /root/.ssh
state: directory
mode: "0700"
owner: root
group: root
- name: Install local public key for root
ansible.posix.authorized_key:
user: root
key: "{{ local_ssh_public_key }}"
state: present
manage_dir: false
- name: Ensure sshd drop-in directory exists
ansible.builtin.file:
path: "{{ sshd_dropin_dir }}"
state: directory
mode: "0755"
owner: root
group: root
- name: Write sshd hardening drop-in
ansible.builtin.copy:
dest: "{{ sshd_dropin_dir }}/99-codex-root-key-only.conf"
mode: "0644"
owner: root
group: root
content: |
PermitRootLogin yes
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
ChallengeResponseAuthentication no
UsePAM yes
- name: Validate sshd configuration syntax
ansible.builtin.command: sshd -t
changed_when: false
when: not ansible_check_mode
- name: Collect service facts
ansible.builtin.service_facts:
changed_when: false
- name: Select SSH service name
ansible.builtin.set_fact:
ssh_service_name: >-
{{
ssh_service_name_override
if ssh_service_name_override | length > 0
else ('ssh' if 'ssh.service' in ansible_facts.services else 'sshd')
}}
- name: Reload SSH service
ansible.builtin.service:
name: "{{ ssh_service_name }}"
state: reloaded
- name: Read root authorized_keys
ansible.builtin.slurp:
src: "{{ root_authorized_keys_path }}"
register: root_authorized_keys
changed_when: false
- name: Assert public key was installed
ansible.builtin.assert:
that:
- local_ssh_public_key in (root_authorized_keys.content | b64decode)
fail_msg: "Local public key was not installed into /root/.ssh/authorized_keys"