/
/
/
1- name: Ensure .ssh directory exists
2 file:
3 path: "{{ my_user_key_dir }}"
4 state: directory
5 mode: "0700"
6 owner: "{{ my_user_username }}"
7 group: "{{ my_user_primary_group }}"
8 become: true
9
10# Authorized keys precedence:
11# 1) explicit my_user_ssh_public_key
12# 2) if not provided, fetch from GitHub username (if set)
13# 3) otherwise skip authorized_key
14
15- name: Install explicit authorized key (if provided)
16 authorized_key:
17 user: "{{ my_user_username }}"
18 key: "{{ my_user_ssh_public_key }}"
19 state: "{{ my_user_authorized_keys_state }}"
20 manage_dir: false
21 when: my_user_ssh_public_key | length > 0
22 become: true
23
24- name: Install authorized keys from GitHub (if username provided and no explicit key)
25 authorized_key:
26 user: "{{ my_user_username }}"
27 key: "{{ lookup('url', 'https://github.com/' + my_user_github_username + '.keys', split_lines=False) }}"
28 state: "{{ my_user_authorized_keys_state }}"
29 manage_dir: false
30 when:
31 - my_user_ssh_public_key | length == 0
32 - my_user_github_username | length > 0
33 become: true
34
35# Keypair generation for non-edge devices:
36# If edge_device == false AND no id_ed25519 exists, generate.
37# Uses community.crypto.openssh_keypair for idempotence.
38
39- name: Stat existing private key
40 stat:
41 path: "{{ my_user_key_dir }}/{{ my_user_key_name }}"
42 register: _priv
43
44- name: Stat existing public key
45 stat:
46 path: "{{ my_user_key_dir }}/{{ my_user_key_name }}.pub"
47 register: _pub
48
49- name: Generate SSH keypair if needed (non-edge devices)
50 community.crypto.openssh_keypair:
51 path: "{{ my_user_key_dir }}/{{ my_user_key_name }}"
52 type: "{{ my_user_key_type }}"
53 owner: "{{ my_user_username }}"
54 group: "{{ my_user_primary_group }}"
55 mode: "0600"
56 comment: "{{ my_user_key_comment }}"
57 when:
58 - not edge_device
59 - not _priv.stat.exists or not _pub.stat.exists
60 become: true
61
62# NOTE: we do NOT auto-add the user's *own* public key to their authorized_keys,
63# since that's usually not desired for remote admin access.
64# If you want that behavior, uncomment the task below.
65
66# - name: (Optional) Add user's own public key to authorized_keys
67# authorized_key:
68# user: "{{ my_user_username }}"
69# state: present
70# key: "{{ lookup('file', my_user_key_dir ~ '/' ~ my_user_key_name ~ '.pub') }}"
71# manage_dir: false
72# when:
73# - not edge_device
74# - (_pub.stat.exists | default(false))
75# become: true
76
77