问题
I am trying to match hosts using a regex pattern with ansible but it is not working as expected. My inventory is as seen below:
[group1]
hello1
world1
hello2
world2
[group2]
hello3
And my task is:
- debug:
msg: "{{ item }}"
with_inventory_hostnames:
- ~hello*
From their documentation:
Using regexes in patterns
You can specify a pattern as a regular expression by starting the pattern with ~:
~(web|db).*\.example\.com
When I execute the task there is no output. I am a n00b with regex so could it be possible my regex is wrong?
回答1:
Q: "Could it be possible my regex is wrong?"
A: It's a bug. See inventory_hostnames lookup doesn't support wildcards in patterns #17268. It will be probably fixed in 2.10. But your pattern wouldn't work, I think, because the doc says: "You can use wildcard patterns with FQDNs or IP addresses, as long as the hosts are named in your inventory by FQDN or IP address"
. The hosts in your inventory are neither FQDN nor IP.
Q: "Is there a way to use a regular expression to match hosts in ansible?"
A: Yes. It is. A very convenient way is to create dynamic groups with the module add_host. For example the playbook below
- hosts: localhost
tasks:
- add_host:
name: "{{ item }}"
groups: my_dynamic_group
loop: "{{ groups.all|select('match', my_pattern)|list }}"
vars:
my_pattern: '^hello\d+$'
- hosts: my_dynamic_group
tasks:
- debug:
var: inventory_hostname
gives
"inventory_hostname": "hello2"
"inventory_hostname": "hello1"
"inventory_hostname": "hello3"
来源:https://stackoverflow.com/questions/60084905/is-there-a-way-to-use-a-regular-expression-to-match-hosts-in-ansible