Skip to main content

Saltstack Refresh Course 2: Salt State

Shenzhen, China

Setting up a Webserver

I want to define a webserver state using a Salt state file and apply it to my minion server:

ApplicationApache
File/var/www/html/index.html
Userswebadmin
SSH KeyFor webadmin user

Init.sls

Every minion that with a name that starts with "salt-minion" should have the apache state applied to it. We can then continue and and create said state in:

/srv/salt/base/apache/init.sls

install_apache:
pkg.installed:
- pkgs:
- apache2

index_html:
file.managed:
- name: /var/www/html/index.html
- source: salt://apache/templates/index.html
- user: www-data
- group: www-data
- mode: 644

apache_service:
service.running:
- name: apache2
- enable: True

Note that the Apache package for Ubuntu is called apache2. For CentOS you would have to use the package name httpd instead.

File Management

This state file defines an index page that we want to use with Apache that we can now create in:

/srv/salt/base/apache/templates/index.html

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8" />

<title>Salty Dayz, Sailor!</title>
<meta name="description" content="Salt Apache Template" />
</head>

<body>
<h1>Salty Dayz, Sailor!</h1>
</body>
</html>

Run your State

We can now apply this state to our minion server with:

salt 'salt-minion*' state.sls apache

salt-minion:
----------
ID: install_apache
Function: pkg.installed
Result: True
Comment: All specified packages are already installed
Started: 10:05:29.993312
Duration: 37.941 ms
Changes:
----------
ID: index_html
Function: file.managed
Name: /var/www/html/index.html
Result: True
Comment: File /var/www/html/index.html updated
Started: 10:05:30.033993
Duration: 39.989 ms
Changes:
----------
diff:
---
+++
@@ -1,4 +1,14 @@
<!doctype html>
+
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+
+ <title>Salty Dayz, Sailor!</title>
+ <meta name="description" content="Salt Apache Template">
+</head>
+
<body>
- <h1>Ubuntu Rocks.</h1>
+ <h1>Salty Dayz, Sailor!</h1>
</body>
+</html>
group:
www-data
user:
www-data
----------
ID: apache_service
Function: service.running
Name: apache2
Result: True
Comment: The service apache2 is already running
Started: 10:05:30.074597
Duration: 38.561 ms
Changes:

Summary for salt-minion
------------
Succeeded: 3 (changed=1)
Failed: 0
------------
Total states run: 3
Total run time: 116.491 ms

Verify that the website is online by first getting your minions IP address:

salt 'salt-minion*' grains.get ipv4

salt-minion:
- 127.0.0.1
- 172.17.0.1
- 172.18.0.1
- 192.168.2.111

And then accessing the Apache service with your web browser http://192.168.2.111:80.