How to get list of volume names from PVC list using ansible?

5/28/2019

In my machines , 4 pvc are created. Now i need to get all volume name associated with the pvc in a list. Then those list will be passed to storage array and i will ensure that the volumes are created in storage server.

- name: Verify whether the PVC is created
    command: "kubectl get pvc pvc{{local_uuid}}-{{item}} -o json"
    with_sequence: start=1 end=4
    register: result

- set_fact: 
      pvcstatus: "{{ (item.stdout |from_json).status.phase }}"
      volume_name: "{{(item.stdout |from_json).spec.volumeName}}"
    with_items: "{{ result.results}}"

 - debug: var=volume_name

But when i run the above tasks , volume_name is having last volumename alone instead of all the volumes as a list. How to get all the volume names in a list?

-- Samselvaprabu
ansible
kubernetes

1 Answer

5/28/2019

Your set_fact task is setting volume_name to a single value in each iteration...so of course, when the loop completes, the variable has the value from the final iteration. That's the expected behavior. If you want a list, you need to create a list. You can do this by appending to a list in your set_fact loop:

- set_fact: 
    volume_name: "{{ volume_name|default([]) + [(item.stdout |from_json).spec.volumeName] }}"
  with_items: "{{ result.results}}"

The expression volume_name|default([]) will evaluate to an empty list when volume_name is undefined (which is the case on the first iteration of the loop).

I tested this out using the following playbook:

---
- hosts: localhost
  gather_facts: false
  vars:
    result:
      results:
        - stdout: '{"spec": {"volumeName": "volume1"}}'
        - stdout: '{"spec": {"volumeName": "volume2"}}'
        - stdout: '{"spec": {"volumeName": "volume3"}}'
  tasks:
    - debug:
        var: result

    - set_fact: 
        volume_name: "{{ volume_name|default([]) + [(item.stdout |from_json).spec.volumeName] }}"
      with_items: "{{ result.results}}"

    - debug:
        var: volume_name

Which results in:

TASK [debug] *****************************************************************************************************************************************************************
ok: [localhost] => {
    "volume_name": [
        "volume1",
        "volume2",
        "volume3"
    ]
}
-- larsks
Source: StackOverflow