/
/
/
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 become: true
44
45- name: Stat existing public key
46 stat:
47 path: "{{ my_user_key_dir }}/{{ my_user_key_name }}.pub"
48 register: _pub
49 become: true
50
51- name: Generate SSH keypair if needed (non-edge devices)
52 community.crypto.openssh_keypair:
53 path: "{{ my_user_key_dir }}/{{ my_user_key_name }}"
54 type: "{{ my_user_key_type }}"
55 owner: "{{ my_user_username }}"
56 group: "{{ my_user_primary_group }}"
57 mode: "0600"
58 comment: "{{ my_user_key_comment }}"
59 when:
60 - not edge_device
61 - not _priv.stat.exists or not _pub.stat.exists
62 become: true
63
64# NOTE: we do NOT auto-add the user's *own* public key to their authorized_keys,
65# since that's usually not desired for remote admin access.
66# If you want that behavior, uncomment the task below.
67
68# - name: (Optional) Add user's own public key to authorized_keys
69# authorized_key:
70# user: "{{ my_user_username }}"
71# state: present
72# key: "{{ lookup('file', my_user_key_dir ~ '/' ~ my_user_key_name ~ '.pub') }}"
73# manage_dir: false
74# when:
75# - not edge_device
76# - (_pub.stat.exists | default(false))
77# become: true
78
79