Fit*_*uan 2 regex search count ansible find-occurrences
我已经到处搜索如何查找 Ansible 变量中出现的单词,但没有找到。我发现的最接近的方法是搜索变量中的任何“单词”,但它不计算有多少单词并且只返回布尔值。这是我的剧本:
---
- 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')
Run Code Online (Sandbox Code Playgroud)
这是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"]}
Run Code Online (Sandbox Code Playgroud)
有什么方法可以调整这个脚本来满足我的目的吗?我需要计算变量“向下”有多少个单词。
我尝试过使用 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"
Run Code Online (Sandbox Code Playgroud)
如果用于普通字符串就很好,但在这种情况下我会得到模板错误,我不知道为什么:
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"}
Run Code Online (Sandbox Code Playgroud)
$ 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
Run Code Online (Sandbox Code Playgroud)
输出是一个变量,它没有属性stdout,所以只是{{输出}},如果您还有其他问题,请告诉我。