5

I have several states that are almost the same. All of them deploy project, create virtualenv and configure supervisor. Difference is only in repo, project name and some additional actions.

A lot of code is duplicated. Is it possible to put the same parts into file and include it with additional variables?

In Ansible it can be done this way:

tasks:
  - include: wordpress.yml
    vars:
        wp_user: timmy
        ssh_keys:
          - keys/one.txt
          - keys/two.txt
Raz
  • 7,508
  • 4
  • 27
  • 25

3 Answers3

5

This question looks similar to this one

If I understood your question correctly - I believe the best way to achieve what you want is to use Salt Macros.

With this most of your state will go to macros with placeholders being parameters like:

# lib.sls
{% macro create_user(user, password) %}
{{user}}:
  user.present:
    - home: /home/{{user}}
    - password: {{password}}
{% endmacro %}

Then your state will look like:

# john.sls
{% from 'lib.sls' import create_user with context %}
{{ create_user('john', '<password hash>') }}

and:

# jane.sls
{% from 'lib.sls' import create_user with context %}
{{ create_user('john', '<password hash>') }}
Community
  • 1
  • 1
alexK
  • 963
  • 1
  • 7
  • 17
2

As I found out there is another way to archive it without messing with templates (more Ansible way). Create an abstract state "python-project". Create concrete roles then and provide different pillars to these roles:

salt/top.sls:

base:
  'roles:python-project-1':
    - match: grain
    - python-project

  'roles:python-project-2':
    - match: grain
    - python-project

pillar/top.sls:

base:
  'roles:python-project-1':
    - match: grain
    - common-pillars
    - pillars-for-the-first

  'roles:python-project-2':
    - match: grain
    - common-pillars
    - pillars-for-the-second

Structure:

pillar/top.sls
pillar/common-pillars/init.sls
pillar/pillars-for-the-first/init.sls
pillar/pillars-for-the-second/init.sls
salt/top.sls
salt/python-project/init.sls
Raz
  • 7,508
  • 4
  • 27
  • 25
2

You can use Jinja imports to do that:

top.sls

{% set user = 'john' %}
{% include 'config.sls' %}

config.sls

file.managed:
  - name: '/Users/{{ user }}/.config
  - user: {{ user }}
Maxime
  • 1,095
  • 1
  • 11
  • 20