Ansible:如何使用基于分隔符(.)的分割字符串,使用列表中存在的项目的映射

问题描述 投票:0回答:3

在 ansible 中,如果存在具有完全限定域名的主机名列表:

 "groups[group_names[0]]": [
        "node1.in.labs.corp.netin",
        "node2.in.labs.corp.netin"
    ]

如何从这些字符串中仅获取节点名称?比如说,答案列表应该只有这些条目:

[节点1,节点2]

尝试使用map和split操作,但它似乎不起作用。它失败说split操作没有为map定义。

msg={{ groups[group_names[0]] | map('split','@') | flatten }}

还有其他办法吗?预先感谢您。


我尝试这样使用 regex_replace 选项:

这里 groups[group_names[0]] 是节点名称列表

 "groups[group_names[0]]": [
        "node1.in.labs.corp.netin",
        "node2.in.labs.corp.netin"
    ]
- set_fact:
      groups[group_names[0]]={{ groups[group_names[0]] |
                   map('regex_replace', _regex, _replace)|list }}
  vars:
    _regex: '^(.*?)\.(.*)$'
    _replace: '-n \1'

点击以下错误行:

{"changed": false, "msg": "The variable name 'groups[group_names[0]]' is not valid. Variables must start with a letter or underscore character, and contain only letters, numbers and underscores."}

我可以分配回同一个列表吗?替换正则表达式后? 另外 -n 选项正在使用,所以我的预期输出应该是

-n node1 -n node2

ansible ansible-inventory ansible-facts ansible-template
3个回答
3
投票

如果您没有运行 Ansible 2.11 或更高版本,则 split jinja 过滤器将不起作用

但你仍然可以做

{{ var.split('-').0 }}
并避免丑陋的正则表达式


1
投票

鉴于数据

  my_groups:
    group_names:
      - ["node1.in.labs.corp.netin", "node2.in.labs.corp.netin"]

下面的表达式可以完成工作

  nodes: "{{ my_groups.group_names.0|map('split', '.')|map('first')|list }}"

给予

  nodes:
  - node1
  - node2

下一个选项是使用regex_replace,例如,下面的任务给出相同的结果

    - set_fact:
        nodes: "{{ my_groups.group_names.0|
                   map('regex_replace', _regex, _replace)|list }}"
      vars:
        _regex: '^(.*?)\.(.*)$'
        _replace: '\1'

0
投票

你可以使用jinja2模板

循环浏览您的列表
创建一个临时变量节点
并附加到它拆分第一个元素
然后通过

- set_fact:
    groups[group_names[0]]: "{% set nodes = [] %}{% for x in groups[group_names[0]] %}{{ nodes.append(x.split('.')[0])  }}{% endfor %}{{ nodes }}"
          
© www.soinside.com 2019 - 2024. All rights reserved.