How to get kubernetes node name and IP address as dictionary in ansible?

12/13/2019

I need to get node name and IP address of each node and then create dictionary object. I am able to get Kubernetes node list using below command

 - hosts: k8s

  tasks:
  - name: get cluster nodes 
    shell: "kubectl get nodes -o wide --no-headers | awk '{ print $1 ,$7}'"
    register: nodes

  - debug: var=nodes

  - set_fact:
      node_data: {}  

  - name: display node name
    debug:
      msg: "name is {{item.split(' ').0}}"
    with_items: "{{nodes.stdout_lines}}"

  - set_fact:
      node_data: "{{ node_data | combine ( item.split(' ').0 : { 'name': item.split(' ').0 , 'ip' : item.split(' ').1 }, recursive=True) }}"
    with_items: "{{ nodes.stdout_lines }}"

  - debug: var=node_data

I got below error:

FAILED! => {"msg": "template error while templating string: expected token ',', got ':'. String: {{ node_data | combine ( item.split(' ').0 : { 'name':item.split(' ').0 , 'ip': item.split(' ').1 }, recursive=True) }}"}

Output of kubectl command given below

kubectl get nodes -o wide --no-headers | awk '{ print $1 ,$7}'

is as follows

> ip-192-168-17-93.ec2.internal 55.175.171.80
> ip-192-168-29-91.ec2.internal 3.23.224.95
> ip-192-168-83-37.ec2.internal 54.196.19.195
> ip-192-168-62-241.ec2.internal 107.23.129.142

How to get the nodename and ip address into dictionary object in ansible?

-- Samselvaprabu
ansible
kubernetes

1 Answer

12/13/2019

The first argument to the combine filter must be a dictionary. You're calling:

  - set_fact:
      node_data: "{{ node_data | combine ( item.split(' ').0 : { 'name': item.split(' ').0 , 'ip' : item.split(' ').1 }, recursive=True) }}"
    with_items: "{{ nodes.stdout_lines }}"

You need to make that:

  - set_fact:
      node_data: "{{ node_data | combine ({item.split(' ').0 : { 'name': item.split(' ').0 , 'ip' : item.split(' ').1 }}, recursive=True) }}"
    with_items: "{{ nodes.stdout_lines }}"

Note the new {...} around your first argument to combine. You might want to consider reformatting this task for clarity, which might make this sort of issue more obvious:

    - set_fact:
        node_data: >-
          {{ node_data | combine ({
            item.split(' ').0: {
              'name': item.split(' ').0,
              'ip': item.split(' ').1
            },
          }, recursive=True) }}
      with_items: "{{ nodes.stdout_lines }}"

You could even make it a little more clear by moving the calls to item.split into a vars section, like this:

    - set_fact:
        node_data: >-
          {{ node_data | combine ({
            name: {
              'name': name,
              'ip': ip
            },
          }, recursive=True) }}
      vars:
        name: "{{ item.split(' ').0 }}"
        ip: "{{ item.split(' ').1 }}"
      with_items: "{{ nodes.stdout_lines }}"
-- larsks
Source: StackOverflow