playbook.yml
---
hosts: local_host
connection: local
gather_facts: False
tasks:
- name: set-details
set_fact:
filter: "{{ lookup('file', 'tmp/task2.yml') | from_json }}"
- set_fact:
result: "{{ filter['msg'] }}"
- debug:
var: result
task2.yml
{
"ansible_loop_var": "item",
"_ansible_no_log": false,
"invocation": {
"module_args": {
"wait_for_task": true,
"policy_package": "Mills07_Simplified",
"version": null,
"wait_for_task_timeout": 30
}
},
"item": "Mills07_Simplified",
"changed": false,
"msg": "Task Verify policy operation with task id 01234567-89ab-cdef-928b-bef7e174fc7a failed. Look at the logs for more details",
"_ansible_item_label": "Mills07_Simplified"
}
调试消息
TASK [debug] *****************************************************************************************************************************************************************************
ok: [localhost] => {
"result": "Task Verify policy operation with task id 01234567-89ab-cdef-928b-bef7e174fc7a failed. Look at the logs for more details"
}
当我执行以下操作时,
- set_fact:
task_id: "{{ result |
select('regex', my_regex)|
first|
regex_replace(my_regex, my_replace) }}"
vars:
my_regex: '^Task Verify policy operation with task id (.*)$'
my_replace: '\1'
- debug:
var: task_id
我收到一条错误消息
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'my_regex' is undefined\n\nThe error appears to be in
目标:我想获取任务ID“01234567-89ab-cdef-928b-bef7e174fc7a”
如何获取此字符串01234567-89ab-cdef-928b-bef7e174fc7a
最佳答案
由于您正在寻找一个 universally unique identifier (or UUID),它的定义格式为 8-4-4-4-12
个字符,总共 36 个字符(32 个十六进制字符和 4 个连字符) source ,您可以使用简单的正则表达式来提取它。
可以使用以下正则表达式来处理:
[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}
您可以在那里测试:https://regex101.com/r/4Hs7il/1
所以,在set_fact
中:
- set_fact:
uuid: >-
{{ filter.msg
| regex_search(
'([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})',
'\1',
ignorecase=True
)
| first
}}
举个例子:
- set_fact:
uuid: >-
{{ filter.msg
| regex_search(
'([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})',
'\1',
ignorecase=True
)
| first
}}
vars:
filter:
msg: >-
Task Verify policy operation with task
id 01234567-89ab-cdef-928b-bef7e174fc7a failed.
Look at the logs for more details
- debug:
var: uuid
会产生:
TASK [set_fact] ***************************************************
ok: [localhost]
TASK [debug] ******************************************************
ok: [localhost] =>
uuid: 01234567-89ab-cdef-928b-bef7e174fc7a
关于filter - 如何过滤字符串中的某些元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67440816/