Home Extracting all named values from an ansible array
Reply: 2

Extracting all named values from an ansible array

Max Allan
1#
Max Allan Published in 2017-12-07 16:31:24Z

I'm not even quite sure how to describe what I'm trying to do! So I'll just jump straight in. I have a hosts file :

[jvbservers]
jvb0  ansible_host=serverA
jvb1  ansible_host=serverB

etc...

And I want a list of the servers in the jvbservers group. What I've come up with so far feels a bit OTT.

  set_fact:
    jvb_names: "{{ jvb_names|default([]) + [ hostvars[groups.jvbservers[item|int]].ansible_host ] }}"
  with_sequence: start=0 end="{{groups.jvbservers|length-1}}"

Gives me a result like I want :

ok: [localhost] => {
    "jvb_names": [
        "serverA", 
        "serverB"
    ]
}

Is this sensible? It feels like there should be a neater way to do something like :

hostvars[groups.jvbservers[*]].ansible_host

(Where "*" would be a pattern matching all valid options. Obvs that particular syntax doesn't exist!)

Christina A
2#
Christina A Reply to 2017-12-07 18:10:38Z

Have you tried this?:

- name: show all the hosts matching jvbservers
  debug:
    msg: "{{ item }}"
  with_inventory_hostnames:
    - all: jvbservers

https://docs.ansible.com/ansible/devel/plugins/lookup/inventory_hostnames.html

Konstantin Suvorov
3#
Konstantin Suvorov Reply to 2017-12-07 18:11:19Z

You may want to check extract filter:

{{ groups['jvbservers'] | map('extract', hostvars, 'ansible_host') | list }}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.34841 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO