有没有办法使用正则表达式来匹配ansible中的主机? [英] Is there a way to use a regular expression to match hosts in ansible?

查看:32
本文介绍了有没有办法使用正则表达式来匹配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?

推荐答案

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

A:这是一个错误.请参阅inventory_hostnames 查找不支持模式 #17268 中的通配符.它可能会在 2.10 中修复.但是我认为您的模式不起作用,因为 doc 说:您可以将通配符模式与 FQDN 或 IP 地址一起使用,只要您的清单中的主机是按 FQDN 或 IP 地址命名的".您清单中的主机既不是 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.

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

答:是的.这是.一个非常方便的方法是使用模块 add_host.例如下面的剧本

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆