refactor(k3s): manage token securely and install guest agent

Signed-off-by: Tuan-Dat Tran <tuan-dat.tran@tudattr.dev>
This commit is contained in:
Tuan-Dat Tran
2025-07-13 02:15:01 +02:00
parent 97a5d6c41d
commit 9cce71f73b
7 changed files with 48 additions and 36 deletions

View File

@@ -33,17 +33,44 @@
delay: 5
become: true
- name: Check if k3s token vault file already exists
ansible.builtin.stat:
path: "{{ playbook_dir }}/{{ k3s_server_token_vault_file }}"
register: k3s_vault_file_stat
delegate_to: localhost
run_once: true
- name: Get K3s token from the first server
when: ansible_default_ipv4.address == k3s_primary_server_ip
when:
- ansible_default_ipv4.address == k3s_primary_server_ip
- not k3s_vault_file_stat.stat.exists
ansible.builtin.slurp:
src: /var/lib/rancher/k3s/server/node-token
register: k3s_token
become: true
- name: Set fact on k3s_primary_server_ip
when: ansible_default_ipv4.address == k3s_primary_server_ip
ansible.builtin.set_fact:
k3s_token: "{{ k3s_token['content'] | b64decode | trim }}"
when:
- not k3s_vault_file_stat.stat.exists
- name: Write K3s token to local file for encryption
ansible.builtin.copy:
content: |
k3s_token: "{{ k3s_token }}"
dest: "{{ playbook_dir }}/{{ k3s_server_token_vault_file }}"
mode: "0600"
delegate_to: localhost
run_once: true
when:
- not k3s_vault_file_stat.stat.exists
- name: Encrypt k3s token
ansible.builtin.shell: cd ../; ansible-vault encrypt "{{ playbook_dir }}/{{k3s_server_token_vault_file}}"
delegate_to: localhost
when:
- not k3s_vault_file_stat.stat.exists
- name: Install K3s on the secondary servers
when: (ansible_default_ipv4.address != k3s_primary_server_ip and (not k3s_status.stat.exists))
@@ -52,5 +79,5 @@
--node-taint CriticalAddonsOnly=true:NoExecute \
--tls-san {{ k3s.loadbalancer.ip }}
environment:
K3S_TOKEN: "{{ hostvars[(hostvars | dict2items | map(attribute='value') | map('dict2items') | map('selectattr', 'key', 'match', 'host') | map('selectattr', 'value.ip', 'match', k3s_primary_server_ip ) | select() | first | items2dict).host.hostname].k3s_token }}"
K3S_TOKEN: "{{ k3s_token }}"
become: true