Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables between salt states

Tags:

salt-stack

In Saltstack, I have the following use case:

There is a state redis.sls which can be included by other states. The result of redis.sls should be configured differently, depending on the state which included redis.sls.

For example:

redis.sls:
--------
{% if x==1 %}
   #do something
{% else %}
   #do something else
{% endif %}


state_a.sls
-----------
{% set x=1 %}
include:
  - redis

state_b.sls
-----------
{% set x=2 %}
include:
  - redis

But x is not recognized in *state_a* and *state_b*

I also tried setting a pillar value with something like this:

{{salt['pillar.set']('x', 1)}}

but that didn't work either.

Any other ideas?

like image 494
lev Avatar asked Mar 19 '14 11:03

lev


People also ask

What are salt states?

States in the salt belt include Alaska, Connecticut, Delaware, Illinois, Indiana, Iowa, Kansas, Kentucky, Maine, Maryland, Massachusetts, Michigan, Minnesota, Missouri, Nebraska, New Hampshire, New Jersey, New York, North Dakota, Ohio, Pennsylvania, Rhode Island, South Dakota, Vermont, Virginia, West Virginia, ...

What is high state in salt?

A “highstate” is a way for Salt to dynamically determine which Salt Formulas should be applied to a certain minion. To start with you execute a “highstate” like this: salt 'minion01' state.highstate. This command causes the Minion to download and examine a file from the Salt Master called the “top file”.

Where are salt states stored?

Setting up the Salt State Tree States are stored in text files on the master and transferred to the minions on demand via the master's File Server. The collection of state files make up the State Tree .


2 Answers

I'd like to hear what the experts say but I have a similar use case. What I did was use the jinja template to extend a base template then my child templates populated the variables.

{% extends "base.template.sls" %}
{% block x %}1{% endblock %}

Only problem might be that you now have to call state_a and state_b separately but you can always put them in a comma separated list if you want both called.

like image 92
Jim K Avatar answered Jan 03 '23 22:01

Jim K


Make your redis state a jinja macro.

redis.sls:
--------
{% macro redis(x) %}
{% if x==1 %}
   #do something
{% else %}
   #do something else
{% endif %}
{% endmacro %}


state_a.sls
-----------
{% from 'redis.sls' import redis  %}
{{ redis(1) }}


state_b.sls
-----------
{% from 'redis.sls' import redis  %}
{{ redis(2) }}

For clarity redis.sls should be renamed to redis.jinja here.

This, and many other ways of managing state customization is best explained in the Salt Formulas conventions guide. Specifically the part about Jinja macros

Note that your if x==1 logic can be probably avoided altogether, take a look at the 'better' version of haproxy example in the guide.

like image 42
kert Avatar answered Jan 03 '23 23:01

kert