0

I'm trying to fetch the names of host groups in Ansible that have a specific prefix. Right now, I'm trying to delegate a template task to servers under host groups with the prefix "config_".

I'm using json_query which uses JMESPath expressions. The query however is incorrect. Can anyone guess what I'm missing?

- name: Create configsvr config file   
  template: src=mongod.conf.j2 dest={{ mongod.conf.path }} owner=mongod group=mongod mode=0600
  delegate_to: "{{ groups|json_query([?starts_with(@, `config_`)]) }}" 

Error msg:

 FAILED! => {"failed": true, "msg": "template error while templating string: unexpected char u'?' at 22. String: {{ groups|json_query([?starts_with(@, `config_m`)]) }}"}

2 Answers2

0

You should simply use built-in patterns to select your target hosts.

---
- hosts: conf_*
  tasks:
    - name: Create configsvr config file   
      template:
        src: mongod.conf.j2
        dest: "{{ mongod.conf.path }}"
        owner: mongod
        group: mongod
        mode: 0600
Eric Citaire
  • 3,700
  • 1
  • 22
  • 47
  • That would select all hosts with with a prefix of "conf_". I'm looking specifically for host groups with certain prefixes in the name of the group itself. – AmineGherib Jul 29 '17 at 07:18
  • It would select both hosts and groups with a name beginning with `conf_`. If you want to target specifically groups with this prefix and not hosts, you should consider using groups of groups (see my second answer). – Eric Citaire Jul 29 '17 at 12:33
  • I posted a response comment on your second answer. – AmineGherib Jul 30 '17 at 00:26
0

You can improve your inventory by using groups of groups, like so:

[conf:children]
conf_a
conf_b
conf_c

[conf_a]
srv1

[conf_b]
srv2

[conf_c]
srv3

And then target conf group in your playbook:

---
- hosts: conf
  tasks:
    - name: Create configsvr config file   
      template:
        src: mongod.conf.j2
        dest: "{{ mongod.conf.path }}"
        owner: mongod
        group: mongod
        mode: 0600
Eric Citaire
  • 3,700
  • 1
  • 22
  • 47
  • I'm sorry but I should have used a better example for a task instead of a creating a template file. I'm trying to figure how to extract certain parts of a json with json_query. The groups collection in ansible is a collection of collections. Those inner collections are host groups that contain hosts. Every host not under a host group is under "ungrouped". This is why I want to use ansible "json_query" feature. FYI, the children feature doesn't create a group of groups. It creates a super set of groups that contains the contents of all groups you specify under it. – AmineGherib Jul 30 '17 at 00:24