regex - Ansible:如何查找变量中出现的单词?

标签 regex search count ansible find-occurrences

我已经到处搜索如何查找 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"]}

这是上述剧本的结果: The playbook result

有什么方法可以调整这个脚本来满足我的目的吗?我需要计算变量“向下”有多少个单词。

我尝试过使用 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/

相关文章:

go - ldap搜索过滤器以检查特定域下是否存在任何用户

batch-file - 批处理脚本 - 在目录中的多个文件中查找和替换文本

php - 在 mysql/php 中编码多个计数查询

mysql - 多个表上的 SQL LEFT JOIN

java - 正则表达式匹配标点符号和小写罗马字

javascript - 如何在 AngularJs 中使用正则表达式和 ng-repeat?

php - 具有一个或多个(多个)参数的搜索表单

mysql - Rails 统计记录而无需再次查询

python - 如何删除Python中两个特定单词之间的文本

regex - Swift 中的 RegularExpression matchesInString 问题