user3323536
user3323536

Reputation: 673

Saltstack variables

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

example working:

{% 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/" like variable like {{ old_stable }}to put on top of file

Inserting of variable in if statement doesn't work

example(not working)

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

My code is

{% 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  %}

Upvotes: 3

Views: 8667

Answers (3)

nmadhok
nmadhok

Reputation: 1784

Firstly, you're code snippet is wrong in the way that you have't taken care of the single apostrophe's. Notice you have one less.

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

This is the correct version as far as the single apostrophe goes:

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

Secondly, concatenate the variable value with the command by using ~ operator that concatenates two strings.

Here's what i found about the ~ operator on 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's the final correct version:

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

Upvotes: 0

quanta
quanta

Reputation: 4530

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

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

Upvotes: 6

Jason Zhu
Jason Zhu

Reputation: 2294

From the jinja documentation:

It’s important to know that the curly braces are not part of the variable but the print statement. If you access variables inside tags don’t put the braces around.

So to get your not working example to be working you would need to do remove the curly brace as shown below:

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

Upvotes: 0

Related Questions