Saltstack Variables

I have a question about variables in salt. I am trying to use if statements to create more complex salt states.

work example:

{% set old_stable = salt['cmd.run']('cd /home/project_name && ls -t|grep 2|grep -v tar.gz|tail -n +2|head -n 1') %}
{% set time_date = salt['cmd.run']('date +%Y%m%d%H%M') %}
{% if salt['cmd.run']('ls -lt /home/project_name/ | wc -l') == 2 %}
      <STATE>
{% endif  %}

So the question is: Can I define "/ home / project_name /" as a variable of type {{old_stable}} to be placed on top of the file

Inserting a variable into an if statement does not work

example (does not work)

{% set project = '/home/project_name' %}
 {% if salt['cmd.run']('ls -lt {{ project }}') | wc -l') == 2 %}
       <STATE>
 {% endif  %}

My code

{% set project = 'test_web_tool' %}

{% if salt['cmd.run']('ls -lt /home/project-user/project 2>/dev/null| wc -l') != "0" %}

output:
 cmd.run:
     - names:
       - echo "Rollback directory {{ project }}"
     - cwd: /root

{% else %}

error_output:
 cmd.run:
     - names:
       - echo "This is the last directory. Cant remove it"
    - cwd: /root

{% endif  %}
+3
source share
3 answers

You probably want to use ~operator to concatenate two lines:

{% set project = '/home/project_name' %}
{% if salt['cmd.run']('ls -lt ' ~ project ~ ' | wc -l') == 2 %}
    <STATE>
{% endif %}
+5
source

From jinja documentation :

, , . , .

, , , :

{% set project = '/home/project_name' %}
{% if salt['cmd.run']('ls -lt project') | wc -l') == 2 %}
       <STATE>
{% endif  %}
0

Firstly, the code snippet is incorrect in how you took care of the only apostrophe. Please note that you have less.

{% set project = '/home/project_name' %}
{% if salt['cmd.run']('ls -lt {{ project }}') | wc -l') == 2 %}
   <STATE>
{% endif  %}

This is the correct version as the only apostrophe goes:

{% set project = '/home/project_name' %}
{% if salt['cmd.run']('ls -lt {{ project }}) | wc -l') == 2 %}
   <STATE>
{% endif  %}

Second, combine the value of the variable with the ~ command, which concatenates the two lines.

Here is what I found about the ~ operator in the Jinja 2 2.7.2 documentation:

~
Converts all operands into strings and concatenates them. {{ "Hello " ~ name ~ "!" }} 
would return (assuming name is 'John') Hello John!.

So here is the final correct version:

{% set project = '/home/project_name' %}
{% if salt['cmd.run']('ls -lt' ~ project ~ ') | wc -l') == 2 %}
   <STATE>
{% endif  %}
0
source

All Articles