Reputation: 87
I have an ansible inventory file that looks like this:
[web]
web1.so.com tech=apache
web2.so.com tech=nginx
I'd like to list the web hosts in a config file only if the tech is nginx. So in this case i'd like the ansible template to produce the below in the config file.
server: web2.so.com
How can I get ansible to insert web hosts only if tech=nginx?
I would usually access hosts by setting using groups in the ansible template:
server: "{{groups['web']}}"
But i'm aware this will list all of the hosts in the web group.
I can't figure out how to only choose hosts that have tech=nginx
, and in this use case it's not possible to split them up into web-nginx and web-apache groups.
It's also not possible to hardcode it to use web2 as the apache host could change with each rebuild.
Upvotes: 0
Views: 1197
Reputation: 44799
You can create groups dynamically with the add_host
or group_by
modules.
In your case, using group_by
as in the following example should meet your requirements:
---
- name: Create dynamic tech groups
hosts: all
gather_facts: false
tasks:
- name: Create the groups depending on tech
group_by:
key: "tech_{{ tech }}"
when: tech is defined
- name: Do something on nginx group
hosts: tech_nginx
gather_facts: false
tasks:
- name: Show it works
debug:
msg: "I'm running on {{ inventory_hostname }}"
Of course, once this is done, you can use groups['tech_nginx']
elsewhere in your playbook to get the list of hosts in that group.
Upvotes: 1
Reputation: 68189
Q: "List the web hosts in a config file only if the tech is nginx."
A: It is possible to use json_query. For example the play below
- hosts: all
tasks:
- set_fact:
nginx_list: "{{ hostvars|dict2items|
json_query('[?value.tech==`nginx`].key') }}"
run_once: true
- debug:
var: nginx_list
gives the variable nginx_list which can be used in the configuration.
ok: [web1.so.com] => {
"nginx_list": [
"web2.so.com"
]
}
ok: [web2.so.com] => {
"nginx_list": [
"web2.so.com"
]
}
For example lineinfile below
- lineinfile:
path: /tmp/webservers.cfg
regex: "^nginx\\s*=(.*)$"
line: "nginx = {{ nginx_list|join(', ') }}"
create: true
delegate_to: localhost
gives
$ cat /tmp/webservers.cfg
nginx = web2.so.com
Upvotes: 0