title: Ansible: How to find word occurrence in a variable?
body: <p>I have searched everywhere on how to find the word occurrence in variable for Ansible but not found. The closest way I found is by searching any 'word' in a variable but it does not count how many words are there and only returning boolean value. Here is my playbook:</p>
  
  <pre><code>---
  
  - 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')  
  </code></pre>
  
  <p>This is the inputFile.txt content:</p>
  
  <pre><code>{"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"]}
  </code></pre>
  
  <p>This is the result of the above playbook:
  <a href="https://i.stack.imgur.com/uNFrn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uNFrn.png" alt="The playbook result"></a></p>
  
  <p>Is there any way I can tweak this script to meet my purpose? I need to count how many word 'down' from the variable. </p>
  
  <p>I have tried using regex_findall as well as shown below:</p>
  
  <pre><code>      - 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" 
  </code></pre>
  
  <p>It is fine if used towards normal String but I will get templating error for this case and i dont know why:</p>
  
  <pre><code>fatal: [localhost]: FAILED! =&gt; {"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"}
  
  </code></pre>