我有许多用户公钥,通过使用 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/