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

标签 python regex ansible python-3.6

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

- name: find users UID within key
  debug: 
    msg: uid is "{{ item.content | regex_search( 'unixid=(\d+)', '\\1') }}"
这失败并出现错误:
'NoneType' object has no attribute 'group'
如果我在 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))
相比之下,如果我在没有组搜索的情况下执行相同的正则表达式,则该命令可以正常工作,否则会返回更多我想要的 id。
通过将两个 regex_search 命令链接在一起,我能够获得所需的功能,但它很难看。我宁愿知道为什么组不为 regex_search 工作。

最佳答案

regex_search旨在返回正则表达式的匹配项,而不是组,或者至少在 Ansible 的当前版本中 (although there are signs that it should work on the latest version?) .
您可以使用 regex_findall 解决此问题相反,但您必须添加 first过滤器来处理创建的列表:
鉴于剧本:

- hosts: localhost
  gather_facts: no

  tasks:
    - debug: 
        msg: uid is "{{ item.content | regex_findall('unixid=(\d+)', '\\1') | first }}"
      vars:
        item:
          content: 000 foo unixid=123 bar 987
这产生了回顾:
PLAY [localhost] **************************************************************************************************

TASK [find users UID within key] **********************************************************************************
ok: [localhost] => 
  msg: uid is "123"

PLAY RECAP ********************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

关于python - 当我尝试使用错误 'NoneType' 对象没有属性 'group' 的组时,Ansible regex_search 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67711421/

相关文章:

python - 与 CNN 交叉验证

python - 使用 Python 使用来自 Azure 事件中心的消息?

ruby - 计算正则表达式效率

ansible - 如何使用ansible遍历文件中的每一行?

Ansible:如何使用 `ansible -a` 执行多个命令

python - 退出时出现 SystemExit 和 NameError 问题

javascript - 如何编写正则表达式来将 XML 节点与大型文本流中的特定文本进行匹配

php - 仅当被文本包围时才拆分

ansible - 如何根据 Ansible 剧本中的 arch 做出决策?

python - numpy 数组或 pandas DataFrame 中的条件过滤