gpt4 book ai didi

regex - Ansible 和 regex_search

转载 作者:行者123 更新时间:2023-12-03 08:21:23 26 4
gpt4 key购买 nike

我目前正在努力使用 regex_search 制作一个有效的剧本,我试图让剧本通过网络命令的标准输出(显示运行 vlan ID),然后通过正则表达式来提取所有接口(interface)标记,

最终该变量将用于部署新的 VLAN 并匹配现有工作 VLAN 的配置

这是我正在尝试的代码,但返回以下错误;

fatal: [10.163.199.131]: FAILED! => {"msg": "Unexpected templatingtype error occurred on ({{ results.stdout.lines |regex_search(regexp,'\\1') }}): expected string or buffer"}

这是 STDOUT 的输出

TASK [debug] ********************************************************************************************************************************************************************************************************************************
ok: [10.163.199.131] => {
"msg": {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"failed": false,
"stdout": [
"vlan 1000 name Guest_WiFi by port\n tagged ethe 1/1/1 to 1/1/9 ethe 1/1/11 to 1/1/25 ethe 1/1/27 to 1/1/44 ethe 1/2/2 \n router-interface ve 1000\n!\n!"
],
"stdout_lines": [
[
"vlan 1000 name Guest_WiFi by port",
" tagged ethe 1/1/1 to 1/1/9 ethe 1/1/11 to 1/1/25 ethe 1/1/27 to 1/1/44 ethe 1/2/2 ",
" router-interface ve 1000",
"!",
"!"

我正在尝试从上面的 STDOUT 中提取以下内容;

1/1/1 to 1/1/9 ethe 1/1/11 to 1/1/25 ethe 1/1/27 to 1/1/44 ethe 1/2/2

这是我当前的剧本;

- hosts: icx
vars:
vlan_lookup: 1000
vlan_to_config: 1001
vlan_name: TestVlan


tasks:
- name: Show output of vlan {{ vlan_lookup }}
icx_command:
commands:
- show run vlan {{ vlan_lookup }}
register: results
- set_fact:
myvalue: "{{ results.stdout.lines | regex_search(regexp,'\\1') }}"
vars:
regexp: '\[1-9]+\D\w+\D'
- debug:
var: '{{myvalue}}'

最佳答案

我认为您需要使用regex_findall而不是regex_search。请注意,当您尝试解析 stdout_lines 时,它是一个 stdout 行列表。因此,您必须使用 string 过滤器转换为 string

- set_fact:
myvalue: "{{ results.stdout_lines|string|regex_findall('\\d+\/\\d+\/\\d+.*\\d+\/\\d+\/\\d+') }}"

- debug:
var: myvalue

将显示上述任务,您可以根据要求更改正则表达式:

TASK [set_fact] ********************************************************************************************************************************************************************************************************************************************************
ok: [localhost]

TASK [debug] ***********************************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"myvalue": [
"1/1/1 to 1/1/9 ethe 1/1/11 to 1/1/25 ethe 1/1/27 to 1/1/44 ethe 1/2/2"
]
}

关于regex - Ansible 和 regex_search,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67756333/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com