Search code examples
if-statementsalt-project

Salt states. If variables have some word in stdout


There is a web page with a large piece of text on it.

I want to configure the state to perform a certain action if curl returns an error.

If the variable doesn't contain 'StatusDescription : OK'

How can I set up a check for a piece of text that is inside a variable

{% set seqstat = salt['cmd.run']('powershell.exe curl http://127.0.0.1:5001 -UseBasicParsing') %}

{% if seqstat is sameas '*StatusDescription : OK*'  %}

module_run:
  cmd.run:
    - name: 'powershell.exe WRITE-HOST have no Error'

{% else %}

module_run1:
  cmd.run:
    - name: 'powershell.exe WRITE-HOST have Error'

{%- endif -%}
Salt Version:
           Salt: 3002.1
 
Dependency Versions:
           cffi: 1.12.2
       cherrypy: unknown
       dateutil: 2.7.3
      docker-py: 3.4.1
          gitdb: 2.0.5
      gitpython: 2.1.11
         Jinja2: 2.10
        libgit2: 0.27.7
       M2Crypto: Not Installed
           Mako: 1.0.7
   msgpack-pure: Not Installed
 msgpack-python: 0.5.6
   mysql-python: 1.3.10
      pycparser: 2.19
       pycrypto: 2.6.1
   pycryptodome: 3.6.1
         pygit2: 0.27.4
         Python: 3.7.3 (default, Jul 25 2020, 13:03:44)
   python-gnupg: 0.4.4
         PyYAML: 3.13
          PyZMQ: 17.1.2
          smmap: 2.0.5
        timelib: Not Installed
        Tornado: 4.5.3
            ZMQ: 4.3.1
 
System Versions:
           dist: debian 10 buster
         locale: UTF-8
        machine: x86_64
        release: 4.19.0-6-amd64
         system: Linux
        version: Debian GNU/Linux 10 buster

Solution

  • I want to configure the state to perform a certain action if curl returns an error.

    There is a Salt state called http which can query a URL and return the status. Using this (instead of curl) we can check for the status code(s) (200, 201, etc.), as well as matching text. Then we can use requisites to run subsequent states depending on the success/failure of the http.query.

    Example:

    I have added a check for status code of 200, you can omit - status: 200 if you don't care about the status code.

    check-application:
      http.query:
      - name: http://127.0.0.1:5001
      - status: 200
      - match: 'StatusDescription : OK'
    
    app-running:
      cmd.run:
      - name: 'powershell.exe WRITE-HOST have no Error'
      - require:
        - http: check-application
    
    app-not-running:
      cmd.run:
      - name: 'powershell.exe WRITE-HOST have Error'
      - onfail:
        - http: check-application