我已经到处搜索如何查找 Ansible 变量中出现的单词,但没有找到。我发现的最接近的方法是搜索变量中的任何“单词”,但它不计算有多少单词并且只返回 bool 值。这是我的剧本:
---
- hosts: localhost
name: Test Variable Manipulation and Searching
gather_facts: false
tasks:
- name: read the Output File
set_fact:
output: "{{lookup('file', 'inputFile.txt') }}"
- name: debug the input file
debug:
msg: "{{output.stdout}}"
- name: find word 'down'
debug:
msg: "Found the word 'down' in the Variables/Output"
when: output.stdout is search('down')
这是inputFile.txt内容:
{"failed": false, "changed": false, "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "stdout_lines": [["Gi1/0/14 down down"]], "stdout": ["Gi1/0/14 down down"]}
有什么方法可以调整这个脚本来满足我的目的吗?我需要计算变量“向下”有多少个单词。
我尝试过使用 regex_findall ,如下所示:
- name: check the down Status if EQUAL to 2
block:
- name: check the down Status if EQUAL to 2
debug:
msg: "Both Status is down. Check is clear"
when: (output.stdout|regex_findall('down')|length) == 2
rescue:
- debug:
msg: "Unable to use the regex_findall to desResult"
如果用于普通字符串就很好,但在这种情况下我会得到模板错误,我不知道为什么:
fatal: [localhost]: FAILED! => {"msg": "The conditional check '(output.stdout|regex_findall('down')|length) == 2' failed. The error was: Unexpected templating type error occurred on ({% if (output.stdout|regex_findall('down')|length) == 2 %} True {% else %} False {% endif %}): expected string or bytes-like object\n\nThe error appears to be in 'switchCheck.yml': line 17, column 11, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n block:\n - name: check the down Status if EQUAL to 2\n ^ here\n"}
最佳答案
$ cat test.yml
- hosts: localhost
name: Test Variable Manipulation and Searching
gather_facts: false
tasks:
- name: read the Output File
set_fact:
output: "{{lookup('file', 'inputFile.txt') }}"
- name: debug the input file
debug:
msg: "{{ output | regex_findall('down') | length }}"
when: (output | regex_findall('down') | length) == 3
$ cat inputFile.txt
Gi1/0/14 down down go down
output 是一个变量,它没有 stdout 属性,所以只需 {{ output }},如果您还有其他问题,请告诉我。
关于regex - Ansible:如何查找变量中出现的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61356545/