Get the nodes/pods information using cluster name or context name when we have multiple configs

9/5/2019

I'm trying to fetch nodes list via ansible playbook using a context name. but its not working

my playbook:

getnodes.yaml

- name: "get nodes"
  hosts: kubernetes
  tasks:
    - name: "nodes"
      command: "kubectl get nodes --context='contextname'"

I do have multiple clusters in config file. I need to either specify cluster name or context name and get the nodes list or to perform any activity on a particular cluster

-- user
ansible
kubernetes

1 Answer

9/6/2019

As far as I understand you when you run the command kubectl get nodes --context='contextname' directly on your master node, everything works fine, right ? And it fails only when you run it as a part of your ansible playbook against the master node ? What errors do you get ?

Yes that's correct. i'm able to execute from command line

"The connection to the server localhost:8080 was refused - did you specify the right host or port?"

Are you sure it is available on the same host as you run your ansible playbook ? I mean your Kubernetes master node, on which you have kubectl binary installed ? My guess is that it is not and even if it is on the same host you'll not be able to connect to it using localhost:8080.

Look. You're not using here any particular Ansible module specific to manage Kubernetes cluster like this one, which you run directly against the API server and you need to provide its valid URL. Instead here you are just using simple command module which doesn't care what command you want to run as long as you provide a valid hostname with ssh access and Python installed.

In this case your Ansible simply tries to ssh to your Kubernetes master node and execute the shell command you passed to it:

kubectl get nodes --context='contextname'

I really doubt that your ssh server listens on port 8080. If you run your ansible playbook on same host you can run your kubectl commands there are much easier solutions in Ansible for such cases like:

local_action or delegate_to: localhost statements in your task or more globally connection: local More details on usage of all above mentioned statements in your Ansible plays you can find in Ansible docs and in this article. I hope it will help you.

-- mario
Source: StackOverflow