Co-blogged on make.rafflecopter.com

When I first created our SaltStack system, I violated the DRY (Don’t Repeat Yourself) principle somewhat due to speed, but mostly due to unfamiliarity with the system. I recently fixed that with a negative 3000 line commit. Here’s some of the things I learned that allowed me to create better (i.e. cleaner and reusable) salt states.

Jinja Imports

Use jinja imports! I was writing and rewriting the same jinja variable definitions in so many files. It turns out you can import those variables from a global location, eliminating jinja variable definitions!

<code data-gist-id=”6d1ed08b5aacc9b5690f” data-gist-file=”global_vars.jinja”} ``{data-gist-id=”6d1ed08b5aacc9b5690f” data-gist-file=”app-init.sls”></code>

Jinja Macros

Use jinja macros! I like to have our applications similarly configured, so I was also rewriting the same lines of json in so many files. Macros and importing helped eliminate this.

<code data-gist-id=”6d1ed08b5aacc9b5690f” data-gist-file=”macros.jinja”} ``{data-gist-id=”6d1ed08b5aacc9b5690f” data-gist-file=”app-config.json.jinja”></code>

Custom States

Use custom states. Sometimes theres a thing you want to configure on a machine, but no state exists in the extensive list of salt states for it. You can make your own! This example is taken from Publysher Dev Blog’s Infra As a Repo series. Just stick any module and state in /srv/salt/_modules or /srv/salt/_states (or wherever your file_roots are).

Build a System

Use everything I’ve said together to program saltstates using configuration (via pillar), code (via custom modules), state generation (via jinja templating), and generic states.

Pillar Configuration

Custom Module

State Generation

Theres so much more you can build on top of a system like this. It will save you code and sanity. You can create tens or hundreds of apps that are only differentiated by small configurations. You can deploy different revisions to different servers whenever you want. Good luck building a generic saltstack app deployment system of your own!