Ansible run “kubectl apply kube-flannel.yml" not work

2/22/2019

This is the ansible yml, I run it on an ansible control node to apply flannel network of the master node. And I am a root user.

- name: Apply flannel network
  shell: sudo kubectl apply -f /tmp/.ansible/files/kube-flannel.yml

And the ansible give me this error:

"unable to recognize \"/tmp/.ansible/files/kube-flannel.yml\": Get http://localhost:8080/api?timeout=32s: dial tcp [::1]:8080: connect: connection refused"]}

But,when I manually login the master node and run sudo kubectl apply -f /tmp/.ansible/files/kube-flannel.yml it works without error.

root@PC:~# kubectl apply -f /tmp/.ansible/files/kube-flannel.yml
clusterrole.rbac.authorization.k8s.io/flannel created
clusterrolebinding.rbac.authorization.k8s.io/flannel created
serviceaccount/flannel created
configmap/kube-flannel-cfg created
daemonset.extensions/kube-flannel-ds-amd64 created
daemonset.extensions/kube-flannel-ds-arm64 created
daemonset.extensions/kube-flannel-ds-arm created
daemonset.extensions/kube-flannel-ds-ppc64le created
daemonset.extensions/kube-flannel-ds-s390x created

The final qustion is, how to fixs the ansible error?

-- pocky0719
flannel
kubernetes

2 Answers

2/22/2019

I have add the following cmd in the ansible yml, then the pod has been applied successfully. Cause the ansible access master node with an new ssh session, the enviroment value has been discarded.

mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
-- pocky0719
Source: StackOverflow

10/10/2019

Just use KUBECONFIG as env variable as below:

- name: Apply flannel
  shell: |
    kubectl apply -f  /home/ubuntu/kube-flannel.yml
  environment:
    KUBECONFIG: /home/ubuntu/.kube/config
  when: inventory_hostname == "kube-master" 
-- 3sky
Source: StackOverflow