Reputation: 840
This is a self-answered question.
Please provide edits, additional points of view and input if needed.
What is the best practice for conditionally enforcing states (depending on other command outputs)?
Here's my case:
# vim: set syntax=yaml:
# Ensures that outbound connections are allowed for httpd
httpd:selinux:
cmd.run:
- name: /usr/sbin/setsebool -P httpd_can_network_connect 1
Now, I only want to run this if SELinux is enabled (enforced).
Upvotes: 0
Views: 2810
Reputation: 840
One way of solving it is by using the onlyif
parameter of salt.states.cmd.run:
# Ensures that outbound connections are allowed for httpd
httpd:selinux:
cmd.run:
- name: /usr/sbin/setsebool -P httpd_can_network_connect 1
- onlyif:
- 'if [[ $(getenforce) == "Disabled" ]]; then exit 1; else exit 0; fi' # if SELinux is disabled, then don't enforce this state
This is a very quick and easy way of solving this problem and as we're dealing with Shell commands in this example it is probably the most preferable way.
Please note that onlyif
is dependent on the return status code of the command that is being tested, so if more flexibility is needed then this might not be what you're looking for.
Another way is to access execution modules with jinja templating, wrap your state in this conditional:
{% if salt.selinux.getenforce() == "Disabled" %}
httpd:selinux:
...
{% endif %}
This is a more flexible solution, but also takes up a bit more space.
More info on: salt.modules.selinux.getenforce()
Upvotes: 1