当我尝试使用错误“NoneType”对象没有属性“group”的组时,Ansible regex_search 失败

dso*_*len 5 python regex ansible python-3.6

我有许多用户公钥,通过使用 URI 模块进行的其余调用获得,并且我想提取该密钥中包含的 uid。这是我的角色的相关行

- name: find users UID within key
  debug: 
    msg: uid is "{{ item.content | regex_search( 'unixid=(\d+)', '\\1') }}"
Run Code Online (Sandbox Code Playgroud)

失败并出现以下错误:

'NoneType' object has no attribute 'group'
Run Code Online (Sandbox Code Playgroud)

如果我在 ansible 上使用 -vvv 我发现它在这条线上失败

file "/usr/lib/python3.6/site-package/ansible/plugins/filter/core.py", line 156, in regex_search
  match = int(re.match(r'\\(\d+)', arg).group(1))
Run Code Online (Sandbox Code Playgroud)

相比之下,如果我在没有组搜索的情况下执行相同的正则表达式,则该命令工作正常,然后返回的内容多于我想要的 id。

我能够通过将两个 regex_search 命令链接在一起来获得所需的功能,但它很丑陋。我更想知道为什么团体不为 regex_search 工作。

β.ε*_*.βε 7

regex_search旨在返回正则表达式的匹配项,而不是组,或者至少在当前版本的 Ansible 中(尽管有迹象表明它应该适用于最新版本?)

您可以使用regex_findall以下方法来解决此问题,但您必须添加一个first过滤器来处理创建的列表:

给定任务:

- debug: 
    msg: >-
      uid is {{ 
        item.content | regex_findall('unixid=(\d+)', '\\1') | first 
      }}
  vars:
    item:
      content: 000 foo unixid=123 bar 987
Run Code Online (Sandbox Code Playgroud)

这产生了回顾:

ok: [localhost] => 
  msg: uid is "123"
Run Code Online (Sandbox Code Playgroud)