SaltStack | How to assign the shell output from cmd.run to Jinja variable?

Solution 1:

I think the main problem is that load_avg from cmd is not a number but a string and you have to convert it. Using load_avg|float (or even load_avg|int) like this works:

{% set load_avg = salt['cmd.shell']('uptime | sed "s/.*load average: //" | cut -d " " -f2 | cut -d . -f1') %}
{% set threshold = 1 %}

check_load_avg:
  cmd.run:
{% if load_avg|float >= threshold %}
    - name: echo 'Load average is HIGH. load_avg={{ load_avg }}, threshold={{ threshold }}'
{% else %}
    - name: echo 'Load average is normal. load_avg={{ load_avg }}, threshold={{ threshold }}'
{% endif %}

Output:

----------
          ID: check_load_avg
    Function: cmd.run
        Name: echo 'Load average is HIGH. load_avg=1, threshold=1'
      Result: True
     Comment: Command "echo 'Load average is HIGH. load_avg=1, threshold=1'" run
     Started: 10:19:42.238409
    Duration: 9.731 ms
     Changes:
              ----------
              pid:
                  5976
              retcode:
                  0
              stderr:
              stdout:
                  Load average is HIGH. load_avg=1, threshold=1

With threshold=5:

----------
          ID: check_load_avg
    Function: cmd.run
        Name: echo 'Load average is normal. load_avg=1, threshold=5'
      Result: True
     Comment: Command "echo 'Load average is normal. load_avg=1, threshold=5'" run
     Started: 10:20:31.846864
    Duration: 9.361 ms
     Changes:
              ----------
              pid:
                  6184
              retcode:
                  0
              stderr:
              stdout:
                  Load average is normal. load_avg=1, threshold=5

EDIT:

You can get the load average using directly the salt module status.loadavg:

# salt-call status.loadavg
local:
    ----------
    1-min:
        0.12
    15-min:
        0.31
    5-min:
        0.25

In jinja:

{% set load_avg = salt['status.loadavg']()['1-min'] %}