裸机K8s集群中Ansible执行kubeadm token命令报错求助
I’ve run into this exact issue a few times, and it almost always boils down to subtle differences between the environment Ansible runs in versus your interactive shell session. Let’s walk through the most common fixes:
1. Fix Environment Variable Mismatches
When you run commands directly on the master or via a remote shell, your user’s profile (like .bashrc or .profile) loads important variables like KUBECONFIG or updates the PATH to include Kubernetes tools. Ansible’s shell module doesn’t load these profiles by default, which can break kubeadm.
Solution: Explicitly load your profile or specify the kubeconfig path in the task:
- name: Get join command from master shell: | source ~/.bashrc && kubeadm token create --print-join-command when: role == "master" run_once: true register: join_command become: yes
Or directly reference the admin kubeconfig file (more reliable for root users):
- name: Get join command from master shell: kubeadm token create --print-join-command --kubeconfig=/etc/kubernetes/admin.conf when: role == "master" run_once: true register: join_command become: yes
2. Ensure Proper Privileges
kubeadm requires root-level permissions to create tokens, and Ansible might not be running the task with elevated privileges by default. Even if you’re using a user with sudo access, you need to explicitly enable privilege escalation.
Solution: Add become: yes to your task (as shown in the examples above) to run the command as root.
3. Wait for kube-apiserver to Fully Initialize
Sometimes Ansible runs the token creation task before the kube-apiserver is fully ready on the master node. Even though the command works when you run it manually later, the timing in your playbook might be off.
Solution: Add a wait step to ensure the apiserver is up before trying to create the token:
- name: Wait for kube-apiserver to be ready wait_for: host: "{{ ansible_default_ipv4.address }}" port: 6443 delay: 10 timeout: 300 when: role == "master" - name: Get join command from master shell: kubeadm token create --print-join-command --kubeconfig=/etc/kubernetes/admin.conf when: role == "master" run_once: true register: join_command become: yes
4. Use Absolute Path for kubeadm
In some cases, Ansible’s default PATH doesn’t include the directory where kubeadm is installed, while your interactive shell does.
Solution: First run which kubeadm on the master node to get the full path, then use that in your task:
- name: Get join command from master shell: /usr/bin/kubeadm token create --print-join-command --kubeconfig=/etc/kubernetes/admin.conf when: role == "master" run_once: true register: join_command become: yes
Start with the environment variable and privilege fixes first—those are the most common culprits. If those don’t work, move on to the apiserver wait step or absolute path check.
内容的提问来源于stack exchange,提问作者Stingus

