HiveBrain v1.2.0
Get Started
← Back to all entries
patternyamlMinor

Is it possible to use multiple if statements in a salt state?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
statementssaltpossiblestatemultipleuse

Problem

I have a Salt state which checks multiple files exist on our webservers, we have 4 webservers and 2 environments so a combined total of 8. This state is applied to all by using a grain 'webserver'.

As the webservers are different (same underlying back end, different directory/file names) I have implemented an if statement which makes use of the inbuilt grains functionality 'host'.

{% if grains['host'] == 'dev-server1', 'test-server1' %}

dart-index.html:
  file.exists:
    - name: /opt/tomcat/webapps/example1/index.html

{% endif %}


When applying my state to all 'webserver' minions, this worked as expected. It checked for the above file on the target minions (dev-server1/test-server1) and ignored the others. However I have since added another if statement below this for dev-server2/test-server2:

{% if grains['host'] == 'dev-server2', 'test-server2' %}

tees-index.html:
  file.exists:
    - name: /opt/tomcat/webapps/example2/index.html

{% endif %}


Now whenever I run the state against the minions it fails as it attempts to check whether both of the above files exist across all minions (which of course won't exist).

So, is it possible to use multiple if statements in a state? Alternatively is there another method in which I could achieve the same goal? I would like to identify multiple files with a specific directory/file name in each type of webserver.

Solution

You can have more than if statement per state. The issue is that your conditional doesn't seem actually be checking the hostname, it's just passing everything. Try this:

{% if grains['host'] in ['dev-server2', 'test-server2'] %}

Code Snippets

{% if grains['host'] in ['dev-server2', 'test-server2'] %}

Context

StackExchange DevOps Q#2058, answer score: 3

Revisions (0)

No revisions yet.