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

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

我正在尝试使用正则表达式模式与 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. It will be probably fixed in 2.10. But your pattern wouldn't work, I think, because the 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"。您清单中的主机既不是 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"