简体   繁体   中英

Access yaml list of dictionaries file with ansible

So I am trying take values from file, let's call it "test.yaml"

file looks like this (sorry for long output, but it is the shortest cut containing all patterns and structure):

---
results:
- failed: false
  item: XXX.XX.XX.XX
  invocation:
    module_args:
      validate_certs: false
      vm_type: vm
      show_tag: false
      username: DOMAIN\domain-user
      proxy_host:
      proxy_port:
      show_attribute: false
      password: VALUE_SPECIFIED_IN_NO_LOG_PARAMETER
      port: XXX
      folder:
      hostname: XXX.XX.XX.XX
  changed: false
  virtual_machines:
  - ip_address: XXX.XX.XX.XX
    mac_address:
    - XX:XX:XX:aa:XX:XX
    uuid: XXXX-XX-XX-XXXX-XXXXX
    guest_fullname: Red Hat Enterprise Linux X (XX-bit)
    moid: vm-XXX
    folder: "/DOMAIN-INTERXION/vm"
    cluster:
    attributes: {}
    power_state: poweredOn
    esxi_hostname: esx.hostname 
    tags: []
    guest_name: VMnameXX
    vm_network:
      XX:XX:XX:aa:XX:XX:
        ipv6:
        - XX::XXX:XX:XXXX
        ipv4:
        - XXX.XX.XX.XX

I would like, for example to have something like:

results.invocation.virtual_machines.ip_address
results.invocation.module_args.user_name

I tried all kind of stuff but it doesn't work :)

last attempt is this:

---
- name: demo how register works
  hosts: localhost
  tasks:
   - name: Include all .json and .jsn files in vars/all and all nested directories (2.3)
     include_vars: 
        file: test.yml
        name: vm

   - name: debug
     debug: 
        msg: "{{ item.0.item }}"
     with_subelements:
       - "{{ vm.results }}"
       - virtual_machines
     register: subelement


following your structure and after fixing some errors:

results.invocation.virtual_machines.ip_address is results[0].virtual_machines[0].ip_address and results.invocation.module_args.user_name is results[0].invocation.module_args.username

(results and virtual_machines are arrays, write results[0] or results.0 is same)

so a sample of playbook doing job:

- name: vartest
  hosts: localhost

  tasks: 
    - name: Include all .json and .jsn files in vars/all and all nested directories (2.3)
      include_vars: 
          file: test.yml
          name: vm

    - name: ip
      set_fact:
        ipadress: "{{ vm.results[0].virtual_machines[0].ip_address }}"

    - name: username
      set_fact:
        username: "{{ vm.results[0].invocation.module_args.username }}"
    - name: display
      debug:
        msg: "ip: {{ ipadress }}  and username: {{ username }}"

result:

ok: [localhost] => 
  msg: 'ip: XXX.XX.XX.XX  and username: DOMAIN\domain-user'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM