Home > Software design >  How to use "maps" in anisble along with "with_items"
How to use "maps" in anisble along with "with_items"

Time:05-26

I am trying to add labels to each node where a label is a map as:

set_node_labels:
  topology.kubernetes.io/region: "syd"
  topology.kubernetes.io/zone: "syd01"

I have written the Ansible task as follows, however it does not work as expected:

- name: Get all Nodes
  shell: "oc get nodes | awk '(NR>1) { print $1 }'"
  register: node_names

- name: Print phone records
  k8s:
    state: present
    kind: Node
    name: "{{ item }}"
    definition:
      metadata:
        labels: "{{ item.key }} {{ item.value }}"
    loop: "{{ lookup('dict', set_node_labels) }}"
  with_items: "{{ node_names.stdout_lines }}"

CodePudding user response:

First things first, you should use the existing module, when they are available instead of a shell module.
In your case, you can get the information about your nodes thanks to the k8s_info module.

So, your first taks should be:

- name: Get all Nodes
  k8s_info:
      kind: Node
  register: node_names

Then in order to pass your labels, those should actually be in a dictionary, so you should be able to pass the whole set_node_labels as labels:

- name: Print phone records
  k8s:
    state: present
    kind: Node
    name: "{{ item.metadata.name }}"
    definition:
      metadata:
        labels: "{{ set_node_labels }}"
  loop: "{{ node_names.resources }}"
  • Related