Files
k3s-ansible/roles/k3s_server/tasks/main.yml
T
Kris b1f5388471 feat: roll the servers one at a time and wait for each to serve again (#562)
* feat: allow the server and agent plays to roll one node at a time

The server and agent roles restart their k3s service on every run, and
the plays run against the whole group at once. On a cluster with three
or more servers that restarts every etcd member together, which costs
the cluster its quorum and its API server.

k3s_server_serial and k3s_agent_serial set the serial of the two plays.
Both default to 100%, the whole group in one batch, so a run that does
not set them behaves as before. The HA integration test now rolls the
servers with the variable instead of --forks=1, which serialises the
role rather than the individual tasks.

Signed-off-by: Kristofer <kristofer@atlascloud.is>

* feat: hold each node until it serves again during a rolling run

Setting k3s_server_serial to 1 rolls the servers one at a time, but the role
returns as soon as the service manager reports k3s started, which is before the
node serves again. On an embedded etcd cluster the next restart can then land
while the previous member is still a learner, and a learner does not count
towards the quorum.

k3s_wait_ready holds each node at the end of its role until the API server
reports it Ready. k3s_server_wait_etcd_voters holds each server until every
server the run has already started carries EtcdIsVoter=True. Both default to
false, are independent of each other, are skipped in check mode, and the upgrade
role honors them as well.

The new voter gate and the existing join barrier both wait only for the servers
the run has reached, taken from the play's host list up to the end of the current
batch: a whole-group count never completes on a fresh HA install rolled one node
at a time. They match nodes by name rather than by count, so a re-run against a
cluster that already holds more nodes also completes, and the comparison ignores
case.

k3s_node_name carries the name K3s registers the node under. It defaults to the
lower-cased hostname and has to be set when a node is installed with --node-name.

The HA integration job installs through tests/serial.yml, which imports site.yml
with the serial variables in its vars, and the external job gives its server a
node name that differs from its host name.

Signed-off-by: Kristofer <kristofer@atlascloud.is>

* docs: say why the node name is recorded as a fact

A role default is not reachable through hostvars, so the barriers read a fact
that each host sets for itself.

Signed-off-by: Kristofer <kristofer@atlascloud.is>

* docs: describe what upgrade.yml does rather than that it is unchanged

Signed-off-by: Kristofer <kristofer@atlascloud.is>

* Tolerate a host that left the play when listing started servers

Extracting a key from hostvars raises when the key is missing. A host that
went unreachable earlier in the play never recorded its node name, so the
list comprehension that both barriers read failed the whole batch rather
than the one host that dropped out. Select the hosts that carry the fact
instead.

Signed-off-by: Kristofer <kristofer@atlascloud.is>

* Count the servers started so far in the server join barrier

The barrier that confirms the servers joined matched the node names the
run had recorded against the names the API server returned. Counting is
enough for what the barrier is for, and it keeps the check independent of
the node name: at the default serial it waits for the whole server group,
which is what it waited for before, and under a serialised run it waits
for the servers the run has started. Name matching stays in the two
opt-in gates, which need it.

Signed-off-by: Kristofer <kristofer@atlascloud.is>

* Take the node name default from the OS nodename

The kubelet registers a node under the name the operating system reports,
which on a host with a search domain is the fully qualified name, not the
short host name the default used. The server and agent plays gather no
facts of their own, so the default also falls back to the inventory host
name rather than requiring a gathered fact.

Signed-off-by: Kristofer <kristofer@atlascloud.is>

* Show the node name as a per-host setting in the sample inventory

k3s_node_name names one node, so the sample carries it under a host entry
rather than in the group vars every node reads. The sample also says where
the serial variables are set, since a reader who meets them in the group
vars block would reasonably try to set them there.

Signed-off-by: Kristofer <kristofer@atlascloud.is>

* State what the etcd voter gate checks and how to read a gate timeout

The voter gate was described as the thing that keeps a rolling run from
taking the quorum down, which overstates it: it checks one condition on
the servers the run has started, and a quorum lost some other way is
outside what it sees. Say that, say which check counts nodes and which
match by name, and give the reader the two failure modes worth knowing
before a gate times out on them.

Signed-off-by: Kristofer <kristofer@atlascloud.is>

* Install the HA test cluster at the default serial and give it an agent

The HA job installed through tests/serial.yml, which left no coverage of a
fresh multi-server install at the default serial, the setting a cluster
that passes no serial variable actually runs. Put that back as the install
step and move tests/serial.yml to the version-bump re-run, where rolling
one node at a time is what the step is testing.

The inventory had no agent, so the agent play never batched and the agent
readiness gate never ran. Adding one covers both, and the job's container
loops and assertions follow it.

Signed-off-by: Kristofer <kristofer@atlascloud.is>

* feat: roll the servers one at a time with an etcd voter wait

k3s_server_serial sets the serial of the server play. It defaults to
100%, the whole group in one batch, so a run that does not set it behaves
as before. Set it to 1 to restart the servers one at a time, and pass it
through extra vars or import_playbook vars, since serial is templated
before any inventory variable is bound.

The join check waits for the servers started so far rather than the whole
group, so a fresh HA install rolled one server at a time completes. A
multi-server cluster on embedded etcd waits until every server reports
EtcdIsVoter=True before the next batch starts. The agent play is
unchanged.

The HA integration job re-runs site.yml with k3s_server_serial=1 in place
of --forks=1.

Signed-off-by: Kristofer <kristofer@atlascloud.is>

* docs: clarify the serial server rollout in the README

Signed-off-by: Kristofer <kristofer@atlascloud.is>

* docs: describe the etcd voter wait precisely

Signed-off-by: Kristofer <kristofer@atlascloud.is>

---------

Signed-off-by: Kristofer <kristofer@atlascloud.is>
2026-10-05 11:10:49 -07:00

395 lines
15 KiB
YAML

---
- name: Get k3s installed version
ansible.builtin.command: k3s --version
register: k3s_server_version_output
changed_when: false
failed_when: false
- name: Set k3s installed version
when: not ansible_check_mode and k3s_server_version_output.rc == 0
ansible.builtin.set_fact:
k3s_server_installed_version: "{{ k3s_server_version_output.stdout_lines[0].split(' ')[2] }}"
# Limit join checks to completed and current batches during serial installation.
- name: Count the servers this play has already started
ansible.builtin.set_fact:
k3s_server_started_count: "{{ ansible_play_hosts_all.index(ansible_play_batch[-1]) + 1 }}"
- name: Construct K3s server config
block:
# Start with an empty config
- name: Set empty server config
ansible.builtin.set_fact:
k3s_server_config: {}
- name: Create k3s config directory
ansible.builtin.file:
path: /etc/rancher/k3s
state: directory
mode: '0755'
# If token is provided, add it to the config
- name: Add token to server config
when: token is defined
ansible.builtin.set_fact:
k3s_server_config: "{{ k3s_server_config | combine({'token': token}) }}"
- name: Determine if tls-san is already in config or args
# noqa var-naming[no-role-prefix]
ansible.builtin.set_fact:
_api_endpoint_in_config: >-
{% if server_config_yaml is defined and api_endpoint is defined and server_config_yaml | regex_search('tls-san:.*' + api_endpoint | regex_escape(), ignorecase=True) %}
true
{% else %}
false
{% endif %}
_api_endpoint_in_args: >-
{% if api_endpoint is defined and extra_server_args | regex_search('--tls-san[=\s]+' + api_endpoint | regex_escape(), ignorecase=True) %}
true
{% else %}
false
{% endif %}
- name: Add TLS SAN to config if needed
when:
- api_endpoint is defined
- api_endpoint != ansible_facts['hostname']
- not (_api_endpoint_in_config | trim | bool)
- not (_api_endpoint_in_args | trim | bool)
ansible.builtin.set_fact:
k3s_server_config: "{{ k3s_server_config | combine({'tls-san': api_endpoint}) }}"
- name: Add cluster-init to server config for first server in HA-IC setup
when:
- (groups[server_group] | length) > 1
- inventory_hostname == groups[server_group][0] or ansible_host == groups[server_group][0]
- not use_external_database
ansible.builtin.set_fact:
k3s_server_config: "{{ k3s_server_config | combine({'cluster-init': true}) }}"
# If not the first server in an HA-IC setup, setup the server: URL for joining the cluster
# server: https://{{ api_endpoint }}:{{ api_port }}
- name: Add server URL to server config for joining servers in HA-IC setup
when: (groups[server_group] | length) > 1 and inventory_hostname != groups[server_group][0] and not use_external_database
ansible.builtin.set_fact:
k3s_server_config: "{{ k3s_server_config | combine({'server': 'https://' + (api_endpoint | ansible.utils.ipwrap) + ':' + api_port | string}) }}"
# If the user has provided additional server config, merge it with the generated config
- name: Merge user server config with generated server config
when: server_config_yaml is defined
ansible.builtin.set_fact:
k3s_server_config: "{{ k3s_server_config | combine(server_config_yaml | from_yaml) }}"
# If airgapped, all K3s artifacts are already on the node.
# We should be downloading and installing the newer version only if we are in one of the following cases :
# - we couldn't get k3s installed version in the first task of this role
# - the installed version of K3s on the nodes is older than the requested version in ansible vars
- name: Download artifact only if needed
when:
- not ansible_check_mode
- airgap_dir is undefined
- ( k3s_server_version_output.rc != 0 or k3s_server_installed_version is version(k3s_version, '<') )
block:
- name: Download K3s install script
ansible.builtin.get_url:
url: https://get.k3s.io/
timeout: 120
dest: /usr/local/bin/k3s-install.sh
owner: root
group: root
mode: "0755"
- name: Set skip_download var for install script
# noqa var-naming[no-role-prefix]
ansible.builtin.set_fact:
skip_download: "false"
# We always run the install script, but we skip the download step as needed
- name: Run K3s install script
when: not ansible_check_mode
# For some reason, ansible-lint thinks using enviroment with command is an error
# even though its valid https://ansible.readthedocs.io/projects/lint/rules/inline-env-var/#correct-code
ansible.builtin.command: # noqa inline-env-var
cmd: /usr/local/bin/k3s-install.sh
# Ensures that extra_install_envs are combined with required env vars
environment: "{{ _install_envs }}"
vars:
_base_envs:
INSTALL_K3S_SKIP_DOWNLOAD: "{{ skip_download | default('true') }}"
INSTALL_K3S_SKIP_START: "true"
INSTALL_K3S_VERSION: "{{ k3s_version }}"
INSTALL_K3S_EXEC: "{{ extra_server_args }}"
# We overrides the extra_install_envs with required keys from _base_envs on purpose
_install_envs: "{{ extra_install_envs | default({}) | combine(_base_envs) }}"
changed_when: true
- name: Check if user bashrc exists
when: ansible_user is defined
ansible.builtin.stat:
path: "~{{ ansible_user }}/.bashrc"
register: k3s_server_bashrc
- name: Add K3s autocomplete to user bashrc
when:
- ansible_user is defined
- k3s_server_bashrc.stat.exists
ansible.builtin.lineinfile:
path: "~{{ ansible_user }}/.bashrc"
regexp: '\.\s+<\(k3s completion bash\)'
line: ". <(k3s completion bash) # Added by k3s-ansible"
- name: Set k3s server environment file based on init system
ansible.builtin.set_fact:
k3s_server_env_file: "{{ (ansible_facts['service_mgr'] == 'systemd') | ternary(systemd_dir ~ '/k3s.service.env', '/etc/rancher/k3s/k3s.env') }}"
- name: Add service environment variables
when: extra_service_envs is defined
ansible.builtin.lineinfile:
path: "{{ k3s_server_env_file }}"
line: "{{ item }}"
loop: "{{ extra_service_envs }}"
- name: Init first server node
when: inventory_hostname == groups[server_group][0] or ansible_host == groups[server_group][0]
block:
- name: Convert server config to YAML and write to file
when: not ansible_check_mode
ansible.builtin.copy:
content: "{{ k3s_server_config | to_nice_yaml }}"
dest: "/etc/rancher/k3s/config.yaml"
mode: "{{ k3s_server_config_mode }}"
register: k3s_server_config_result
- name: Delete any existing token from the environment if different from the new one
ansible.builtin.lineinfile:
state: absent
path: "{{ k3s_server_env_file }}"
regexp: "^K3S_TOKEN=\\s*(?!{{ token | default('') | regex_escape }}\\s*$)"
- name: Reload systemd daemon
when:
- not ansible_check_mode
- ansible_facts['service_mgr'] == 'systemd'
ansible.builtin.systemd:
daemon_reload: true
- name: Enable and start K3s service
when: not ansible_check_mode
ansible.builtin.service:
name: k3s
state: restarted
enabled: true
- name: Pause to allow first server startup
when: (groups[server_group] | length) > 1
ansible.builtin.pause:
seconds: 10
- name: Check whether kubectl is installed on control node
# noqa var-naming[no-role-prefix]
ansible.builtin.command: 'kubectl'
register: kubectl_installed
tags: kubeconfig
ignore_errors: true
delegate_to: 127.0.0.1
become: false
changed_when: false
# Copy the k3s config to a second file to detect changes.
# If no changes are found, we can skip copying the kubeconfig to the control node.
# This is dependent on the speed of the target node for k3s startup time, so retries are used.
- name: Copy k3s.yaml to second file
when: not ansible_check_mode
ansible.builtin.copy:
src: /etc/rancher/k3s/k3s.yaml
dest: /etc/rancher/k3s/k3s-copy.yaml
mode: "0600"
remote_src: true
retries: 3
register: k3s_server_copy_yaml
tags: kubeconfig
- name: Apply K3S kubeconfig to control node
when:
- kubectl_installed.rc == 0 and (k3s_server_copy_yaml.changed or 'kubeconfig' in ansible_run_tags)
block:
- name: Copy kubeconfig to control node
ansible.builtin.fetch:
src: /etc/rancher/k3s/k3s.yaml
dest: "{{ kubeconfig }}"
flat: true
- name: Change server address in kubeconfig on control node
ansible.builtin.shell: |
KUBECONFIG={{ kubeconfig }} kubectl config set-cluster default --server=https://{{ api_endpoint | ansible.utils.ipwrap }}:{{ api_port }}
delegate_to: 127.0.0.1
become: false
register: k3s_server_csa_result
changed_when:
- k3s_server_csa_result.rc == 0
- name: Setup kubeconfig context on control node - {{ cluster_context }}
when: kubeconfig == "~/.kube/config.new"
ansible.builtin.replace:
path: "{{ kubeconfig }}"
regexp: 'default'
replace: '{{ cluster_context }}'
delegate_to: 127.0.0.1
become: false
- name: Merge with any existing kubeconfig on control node
when: kubeconfig == "~/.kube/config.new"
ansible.builtin.shell: |
TFILE=$(mktemp)
KUBECONFIG={{ kubeconfig }}:~/.kube/config kubectl config set-context {{ cluster_context }} --user={{ cluster_context }} --cluster={{ cluster_context }}
KUBECONFIG={{ kubeconfig }}:~/.kube/config kubectl config view --flatten > ${TFILE}
mv ${TFILE} ~/.kube/config
delegate_to: 127.0.0.1
become: false
register: k3s_server_mv_result
changed_when:
- k3s_server_mv_result.rc == 0
- name: Get the token if randomly generated
when:
- not ansible_check_mode
- token is not defined
block:
- name: Wait for token
ansible.builtin.wait_for:
path: /var/lib/rancher/k3s/server/token
- name: Read node-token from first server
ansible.builtin.slurp:
src: /var/lib/rancher/k3s/server/token
register: k3s_server_node_token
- name: Store random token for later servers
# noqa var-naming[no-role-prefix]
ansible.builtin.set_fact:
random_token: "{{ k3s_server_node_token.content | b64decode | regex_replace('\n', '') }}"
- name: Start other server if any and verify status
when:
- (groups[server_group] | length) > 1
- inventory_hostname != groups[server_group][0] and ansible_host != groups[server_group][0]
block:
- name: Get token from first server if needed
when: token is not defined and hostvars[groups[server_group][0]].random_token is defined
# noqa var-naming[no-role-prefix]
ansible.builtin.set_fact:
k3s_server_config: "{{ k3s_server_config | combine({'token': hostvars[groups[server_group][0]].random_token}) }}"
- name: Convert server config to YAML and write to file
when: not ansible_check_mode
ansible.builtin.copy:
content: "{{ k3s_server_config | to_nice_yaml }}"
dest: "/etc/rancher/k3s/config.yaml"
mode: "{{ k3s_server_config_mode }}"
register: k3s_server_config_result
- name: Delete any existing token from the environment if different from the new one
ansible.builtin.lineinfile:
state: absent
path: "{{ k3s_server_env_file }}"
regexp: "^K3S_TOKEN=\\s*(?!{{ token | default('') | regex_escape }}\\s*$)"
- name: Reload systemd daemon
when:
- not ansible_check_mode
- ansible_facts['service_mgr'] == 'systemd'
ansible.builtin.systemd:
daemon_reload: true
# Always restart a joined server so a re-run of site.yml — whether it only
# bumped k3s_version or changed config — brings it onto the new runtime, the
# same way the first server above always restarts. On a multi-server cluster
# set k3s_server_serial to 1 so the servers restart one at a time (see README).
- name: Restart K3s service
when:
- ansible_facts.services['k3s.service'] is defined
- ansible_facts.services['k3s.service'].state == 'running'
ansible.builtin.service:
name: k3s
state: restarted
- name: Enable and start K3s service
when: ansible_facts.services['k3s.service'] is not defined or ansible_facts.services['k3s.service'].state != 'running'
ansible.builtin.service:
name: k3s
state: started
enabled: true
- name: Verify that the servers started so far joined
when: not ansible_check_mode
ansible.builtin.command:
cmd: >
k3s kubectl get nodes -l "node-role.kubernetes.io/control-plane=true" -o=jsonpath="{.items[*].metadata.name}"
register: k3s_server_nodes
until:
- k3s_server_nodes.rc == 0
- (k3s_server_nodes.stdout.split() | length) >= (k3s_server_started_count | int)
retries: 20
delay: 10
changed_when: false
- name: Wait for control plane to be ready
ansible.builtin.wait_for:
host: "{{ api_endpoint }}"
port: "{{ api_port }}"
timeout: 60
run_once: true
changed_when: false
- name: Wait for the servers started so far to be etcd voters
when:
- not ansible_check_mode
- (groups[server_group] | length) > 1
- not use_external_database
ansible.builtin.command:
cmd: >-
k3s kubectl --request-timeout=10s get nodes -l "node-role.kubernetes.io/etcd=true"
-o=jsonpath='{range .items[*]}{.metadata.name}={.status.conditions[?(@.type=="EtcdIsVoter")].status}{"\n"}{end}'
register: k3s_server_etcd_voters
until:
- k3s_server_etcd_voters.rc == 0
- (k3s_server_etcd_voters.stdout.split() | length) >= (k3s_server_started_count | int)
- (k3s_server_etcd_voters.stdout.split() | reject('search', '=True$') | list | length) == 0
retries: 30
delay: 10
changed_when: false
- name: Setup kubectl for user
when: user_kubectl
block:
- name: Create directory .kube
ansible.builtin.file:
path: ~{{ ansible_user }}/.kube
state: directory
owner: "{{ ansible_user }}"
mode: "u=rwx,g=rx,o="
- name: Copy config file to user home directory
when: not ansible_check_mode
ansible.builtin.copy:
src: /etc/rancher/k3s/k3s.yaml
dest: ~{{ ansible_user }}/.kube/config
remote_src: true
owner: "{{ ansible_user }}"
mode: "u=rw,g=,o="
- name: Configure default KUBECONFIG for user
when: k3s_server_bashrc.stat.exists
ansible.builtin.lineinfile:
path: ~{{ ansible_user }}/.bashrc
regexp: 'export KUBECONFIG=~/.kube/config'
line: 'export KUBECONFIG=~/.kube/config # Added by k3s-ansible'
state: present
- name: Configure kubectl autocomplete
when: k3s_server_bashrc.stat.exists
ansible.builtin.lineinfile:
path: ~{{ ansible_user }}/.bashrc
regexp: '\.\s+<\(kubectl completion bash\)'
line: ". <(kubectl completion bash) # Added by k3s-ansible"