homelab/roles/common/tasks/main.yaml
2025-01-10 10:26:38 -03:00

76 lines
2.5 KiB
YAML

# yaml-language-server: $schema=https://raw.githubusercontent.com/ansible/ansible-lint/refs/heads/main/src/ansiblelint/schemas/tasks.json
- name: Setup users
loop: "{{ users | dict2items }}"
ansible.builtin.user:
state: present
name: "{{ item.key }}"
system: "{{ item.value.system }}"
shell: "{{ item.value.shell }}"
create_home: true
password: "{{ (item.value.password != '!' or item.value.password != '*') | ternary(item.value.password | password_hash('sha512'), item.value.password) }}"
groups: "{{ item.value.groups + (extra_groups | default([])) }}"
append: true
- name: Add SSH public key to users
loop: "{{ users | dict2items }}"
ansible.posix.authorized_key:
user: "{{ item.key }}"
state: present
exclusive: false
key: "{{ lookup('file', item.value.ssh_keys.pub) }}"
key_options: "{{ 'command=\"' + robo_allowed_commands | join('; ') + '\"' if robo_allowed_commands is defined and item.key == 'robo' else omit }}"
- name: Configure SSH login for current user if present
vars:
user_name: "{{ lookup('env', 'USER') }}"
user_dir: "{{ lookup('env', 'HOME') }}"
current_user: "{{ users[user_name] | default(None) }}"
when: current_user
block:
- name: Creates directory
run_once: True
local_action:
module: file
path: "{{ user_dir }}/.ssh/credentials"
state: directory
owner: "{{ user_name }}"
group: "{{ user_name }}"
- name: Save SSH Key in localhost
run_once: True
local_action:
module: copy
src: "{{ current_user.ssh_keys.priv }}"
dest: "{{ user_dir }}/.ssh/credentials/homelab"
owner: "{{ user_name }}"
group: "{{ user_name }}"
mode: '0600'
- name: Configure SSH host
local_action:
module: community.general.ssh_config
user: "{{ user_name }}"
host: "{{ inventory_hostname }}"
hostname: "{{ ansible_default_ipv4.address }}"
identity_file: "{{ user_dir }}/.ssh/credentials/homelab"
port: "{{ ansible_port | default(22) }}"
state: present
- name: Disable password authentication for SSH
become: true
notify: Restart sshd
ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?PasswordAuthentication'
line: 'PasswordAuthentication no'
state: present
- name: Allow authentication via ssh keys
become: true
notify: Restart sshd
ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?PubkeyAuthentication'
line: 'PubkeyAuthentication yes'
state: present