【问题标题】:Is there a way to use a regular expression to match hosts in ansible?有没有办法使用正则表达式来匹配ansible中的主机?
【发布时间】:2020-02-05 22:15:24
【问题描述】:

我正在尝试使用带有 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,所以我的正则表达式可能是错误的吗?

【问题讨论】:

标签: regex ansible ansible-inventory ansible-bug


【解决方案1】:

问:“我的正则表达式有可能是错误的吗?”

A:这是一个错误。见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"。您清单中的主机既不是 FQDN 也不是 IP。

问:“有没有办法使用正则表达式来匹配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"

【讨论】:

    猜你喜欢
    • 2019-02-11
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多