k3s-io / k3s-ansible

Apache License 2.0
1.89k stars 780 forks source link

k3s-server: overwrites user's `~/.kube/config` even when a different `kubeconfig` value is provided #295

Closed nickto closed 5 months ago

nickto commented 5 months ago

Seems like after https://github.com/k3s-io/k3s-ansible/pull/288, when kubeconfig is explicitly set to a value other than ~/.kube/config, some unexpected behavior appears:

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.

I believe both of these things happen in here:

[...]
        - name: Merge with any existing kubeconfig on control node
          when: kubeconfig != "~/.kube/config"  # task gets triggered
          ansible.builtin.shell: |
            TFILE=$(mktemp)
            KUBECONFIG={{ kubeconfig }} kubectl config set-context k3s-ansible --user=k3s-ansible --cluster=k3s-ansible
            KUBECONFIG={{ kubeconfig }}:~/.kube/config kubectl config view --flatten > ${TFILE}
            mv ${TFILE} ~/.kube/config # user config file is changed, although `kubeconfig` is provided
            rm {{ kubeconfig }} # an existing config file removed
          delegate_to: 127.0.0.1
[...]

I think that something along these lines could be more appropriate:

        - name: Merge with any existing kubeconfig on control node
          when: kubeconfig != "~/.kube/config"
          ansible.builtin.shell: |
            TFILE=$(mktemp)
            KUBECONFIG={{ kubeconfig }} kubectl config set-context k3s-ansible --user=k3s-ansible --cluster=k3s-ansible
            KUBECONFIG={{ kubeconfig }} kubectl config view --flatten > ${TFILE}
            mv ${TFILE} {{ kubeconfig }}
          delegate_to: 127.0.0.1