有没有办法使用正则表达式匹配ansible中的主机? [英] Is there a way to use a regular expression to match hosts in ansible?
问题描述
我正在尝试使用正则表达式模式与ansible匹配主机,但是它无法按预期工作. 我的库存如下所示:
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
我的任务是:
- debug:
msg: "{{ item }}"
with_inventory_hostnames:
- ~hello*
从他们的文档中:
Using regexes in patterns
You can specify a pattern as a regular expression by starting the pattern with ~:
~(web|db).*\.example\.com
当我执行任务时,没有输出.我是使用正则表达式的n00b,所以我的正则表达式可能出错吗?
When I execute the task there is no output. I am a n00b with regex so could it be possible my regex is wrong?
推荐答案
Q:我的正则表达式是否可能是错误的?"
A:这是一个错误.请参见 inventory_hostnames查找不支持模式#17268 中的通配符.它可能是在2.10中修复的.但我认为您的模式无效,因为文档表示: "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"
.库存中的主机既不是FQDN也不是IP.
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:有没有办法使用正则表达式匹配ansible中的主机?"
A:是的.它是.一种非常方便的方法是使用模块添加主机.例如下面的剧本
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
给予
"inventory_hostname": "hello2"
"inventory_hostname": "hello1"
"inventory_hostname": "hello3"
这篇关于有没有办法使用正则表达式匹配ansible中的主机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!