Support user defined kubeconfig, fix merging context (#266)

* Support user defined kubeconfig, fix merging context

Signed-off-by: Derek Nola <derek.nola@suse.com>
This commit is contained in:
Derek Nola 2023-12-06 09:13:05 -08:00 committed by GitHub
parent 4d6e60281e
commit 9998f503b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 4 deletions

View File

@ -94,13 +94,16 @@ It is assumed that the control node has access to the internet. The playbook wil
## Kubeconfig
After successful bringup, the kubeconfig of the cluster is copied to the control node and set as default (`~/.kube/config`).
Assuming you have [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) installed, you to confirm access to your **Kubernetes** cluster use the following:
After successful bringup, the kubeconfig of the cluster is copied to the control node and merged with `~/.kube/config` under the `k3s-ansible` context.
Assuming you have [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) installed, you can confirm access to your **Kubernetes** cluster with the following:
```bash
kubectl config use-context k3s-ansible
kubectl get nodes
```
If you wish for your kubeconfig to be copied elsewhere and not merged, you can set the `kubeconfig` variable in `inventory.yml` to the desired path.
## Local Testing
A Vagrantfile is provided that provision a 5 nodes cluster using Vagrant (LibVirt or Virtualbox as provider). To use it:

View File

@ -2,3 +2,4 @@
k3s_server_location: "/var/lib/rancher/k3s"
systemd_dir: "/etc/systemd/system"
api_port: 6443
kubeconfig: ~/.kube/config.new

View File

@ -91,13 +91,33 @@
- name: Copy kubectl config to local machine
ansible.builtin.fetch:
src: ~{{ ansible_user }}/.kube/config
dest: ~/.kube/config.new
dest: "{{ kubeconfig }}"
flat: true
- name: Check whether kubectl is installed on control node
ansible.builtin.command: 'kubectl'
register: kubectl_installed
ignore_errors: yes
delegate_to: 127.0.0.1
become: false
changed_when: false
- name: Setup kubeconfig k3s-ansible context
when: kubeconfig == "~/.kube/config.new" && kubectl_installed.rc == 0
ansible.builtin.replace:
path: "{{ kubeconfig }}"
regexp: 'name: default'
replace: 'name: k3s-ansible'
delegate_to: 127.0.0.1
become: false
- name: Merge with any existing kube config
when: kubeconfig == "~/.kube/config.new" && kubectl_installed.rc == 0
ansible.builtin.shell: |
TFILE=$(mktemp)
KUBECONFIG=~/.kube/config:~/.kube/config.new kubectl config view --flatten > ${TFILE}
KUBECONFIG=~/.kube/config.new kubectl rename-context default k3s-ansible
KUBECONFIG=~/.kube/config.new kubectl config set-context k3s-ansible --user=k3s-ansible --cluster=k3s-ansible
KUBECONFIG=~/.kube/config.new:~/.kube/config kubectl config view --flatten > ${TFILE}
mv ${TFILE} ~/.kube/config
rm ~/.kube/config.new
delegate_to: 127.0.0.1