gpt4 book ai didi

regex - 有没有办法使用正则表达式来匹配 ansible 中的主机?

转载 作者:行者123 更新时间:2023-12-04 15:34:50 27 4
gpt4 key购买 nike

我正在尝试使用正则表达式模式与 ansible 匹配主机,但它没有按预期工作。
我的库存如下所示:

[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,所以我的正则表达式有可能是错误的吗?

最佳答案

Q: "Could it be possible my regex is wrong?"



答:这是一个错误。见 inventory_hostnames lookup doesn't support wildcards in patterns #17268 .可能是 fixed in 2.10 .但是我认为您的模式不起作用,因为 doc说: "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" .您 list 中的主机既不是 FQDN 也不是 IP。

Q: "Is there a way to use a regular expression to match hosts in ansible?"



答:是的。这是。一个非常方便的方法是使用模块 add_host 创建动态组。 .例如下面的剧本
- 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"

关于regex - 有没有办法使用正则表达式来匹配 ansible 中的主机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60084905/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com