Implementing Conditional State Execution in SaltStack

Adding Authentication too a PHP Application Directory

Create a PHP info file in the existing LAMP environment:

mkdir -p /var/www/html/admin
cat > /var/www/html/admin/info.php << EOF
<?php
phpinfo();
?>
EOF

Configuring HTTP Authentication

Modify the Apache configuration to add password protection for the admin directory. Add this section to the virtual host configuration:

<Directory "/var/www/html/admin">
    AllowOverride All
    Order allow,deny
    Allow from All
    AuthUserFile /etc/httpd/conf/htpasswd_file
    AuthName "Restricted Area"
    AuthType Basic
    Require user admin
</Directory>

SaltStack State Configuration

Create a SaltStack state file (/srv/salt/base/web/lamp.sls) to manage the LAMP stack with authentication:

lamp-packages:
  pkg.installed:
    - pkgs:
      - httpd
      - php
      - php-pdo
      - php-mysql

apache-main-config:
  file.managed:
    - name: /etc/httpd/conf/httpd.conf
    - source: salt://web/files/httpd.conf
    - user: root
    - group: root
    - mode: 644
    - require:
      - pkg: lamp-packages

authentication-tools:
  pkg.installed:
    - name: httpd-tools
    - require_in:
      - cmd: create-auth-file

create-auth-file:
  cmd.run:
    - name: htpasswd -bc /etc/httpd/conf/htpasswd_file admin admin
    - unless: test -f /etc/httpd/conf/htpasswd_file

apache-conf-d:
  file.recurse:
    - name: /etc/httpd/conf.d
    - source: salt://web/files/apache-conf.d

php-ini-config:
  file.managed:
    - name: /etc/php.ini
    - source: salt://web/files/php.ini
    - user: root
    - group: root
    - mode: 644

apache-service:
  service.running:
    - name: httpd
    - enable: True
    - reload: True
    - watch:
      - file: apache-conf-d
      - file: apache-main-config

Conditional Execution with Unless Clause

The unless parameter prevents the command from running if the specified condition evaluates to true. In this case, the authentication file creation command only executes when the file doesn't exist:

create-auth-file:
  cmd.run:
    - name: htpasswd -bc /etc/httpd/conf/htpasswd_file admin admin
    - unless: test -f /etc/httpd/conf/htpasswd_file

This ensures idempotent execution where the authentication file is created only once, preventing redundant operations during subsequent state applications.

Tags: SaltStack configuration-management apache Authentication idempotent-execution

Posted on Tue, 30 Jun 2026 17:35:36 +0000 by jburfield