Ansible:如何在变量中查找单词出现?

问题描述 投票:0回答:1

我到处都在搜索如何在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')  

这是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

有什么方法可以调整此脚本以满足我的目的?我需要计算变量中有多少个单词“ 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" 

如果用于普通的String很好,但是在这种情况下我会收到模板错误,我不知道为什么:

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"}

regex search count ansible find-occurrences
1个回答
1
投票
$ 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

输出是一个变量,它没有stdout属性,所以只有{{output}},如果还有其他问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.