Bisshwajit Samanta
Bisshwajit Samanta

Reputation: 79

Unable to fit the ansible code in playbook

This is a log file stored in Yaml Format.

My job is to find out the hostname which belongs to hostclass ess, which in this case the answer is host002.

hostinfo:
  'host001':
    ip: 192.168.43.10
    hostclass: 'puppet'
  'host002':
    ip: 192.168.43.11
    hostclass: 'ess'
  'host003':
    ip: 192.168.43.21
    hostclass: 'mdb'

i got one solution from some friend, but i am unable to fit it my ansible playbook.

- debug:
    msg: "{{ hostinfo|dictsort|selectattr('1.hostclass', 'equalto', 'ess')|first|first }}"

My playbook i am writing, It is wrong but i am not able to figure out how to fit the code in my playbook. Can anyone help me in modifying the code of mine.

---

- hosts: somehost
  gather_facts: no
  vars_files:
    file: sometext.yaml
    name: sometext

  - debug:
        msg: "{{ hostinfo|dictsort|selectattr('1.hostclass', 'equalto', 'ess')|first|first }}"

Upvotes: 0

Views: 64

Answers (2)

techraf
techraf

Reputation: 68559

Here's the code you've been looking for:

(on top of the query, you also have a problem with vars_files)

tasks:
  - include_vars:
      file: ./sometext.yaml
      name: sometext

  - debug:
      msg: "{{ sometext.hostinfo | dict2items | json_query('[?value.hostclass==`ess`] | [0].key') }}"

The last filter in the query returns a single string, if there are multiple hosts with hostclass equal to ess, you need to change it and it will generate a list.

Upvotes: 1

George Shuklin
George Shuklin

Reputation: 7907

You are using Ansible in a wrong way. It's possible to write a complicated query (You can use json_query filter for that), but it will be extremely hard to read and maintain.

What you need to do: Instead of using hostclass: something, use groups. Groups are designed for that.

Your inventory should look like this:

[puppet]
host001 ip=192.168.43.10
[ess]
host002 ip=192.168.43.11
[mdb]
host003 ip=192.168.43.21

[hostinfo:children]
puppet
ess
mdb

After that it's trivial to query groups if you need them (groups.puppet for example), and it's easy to access their variables: (hostvars[groups.puppet][0]).ip

Upvotes: 2

Related Questions