working with file

Hi,

I have a file like : [1,2,3,4,5]
and I want to use loop for each number in this file on the playbook (I want to use the file, not write keys in the playbook). Could you help me please ?

The playbook: (and i need to loop on “variable_file”)

  • name: Gather info about all ESXi Host in given Cluster
    vmware_host_service_info:
    validate_certs: no
    hostname: xxxxx
    username: user
    password: password
    cluster_name: “{{variable_file}}”

Thanks for your help

Hi,

I have a file like : [1,2,3,4,5]

‘Like’ is ambiguous. What is like what?
Is the filename like 12345? Is the content a json list of integers? Please try to be precise.

and I want to use loop for each number in this file on the playbook (I want to use the file, not write keys in the playbook).

No idea again what ‘writing keys in the playbook’ means. So again please be precise.

Could you help me please ?

The playbook: (and i need to loop on “variable_file”)

  • name: Gather info about all ESXi Host in given Cluster
    vmware_host_service_info:
    validate_certs: no
    hostname: xxxxx
    username: user
    password: password
    cluster_name: “{{variable_file}}”

A wild guess, if you want to read the contents of a file ? Maybe this is what you want:

https://docs.ansible.com/ansible/latest/plugins/lookup/lines.html

Hi,

I have a json file-> cluster_name.json :
[“cluster1”,“cluster2”,“cluster3”,“cluster4”]

And I want to iterate on every cluster name to obtain some informations so I use the module vmware_host_service_info.
My playbook is → vmware.yml :

Hi,

I have a json file-> cluster_name.json :
["cluster1","cluster2","cluster3","cluster4"]

And I want to iterate on every cluster name to obtain some informations so I use the module vmware_host_service_info.
My playbook is -> vmware.yml :
---
- name: test
hosts: localhost
vars_files:
- cluster_name.json
tasks:
- name: Gather info about all ESXi Host in given Cluster
vmware_host_service_info:
validate_certs: no
hostname: hostname
username: user
password: password
cluster_name: "{{cluster}}" <-- HERE I WANT TO ITERATE ON EVERY CLUSTER_NAME IN cluster_name.json
delegate_to: localhost

Replace vars_files with a lookup:

vars:
    cluster_names: "{{ lookup( 'file', 'cluster_name.json' ) }}"

This automatically converts the file contents from JSON to a list.

You can now loop over that:

tasks:
   - name: Gather info about all ESXi Host in given Cluster
     vmware_host_service_info:
       validate_certs: no
       hostname: hostname
       username: user
       password: password
       cluster_name: "{{ item }}"
     with_items: "{{ cluster_names }}"
     delegate_to: localhost

Regards
        Racke

OK ! It works, thanks :slight_smile: