Search code examples
jinja2salt-project

How can I recursively filter config data using Salt Jinja2 template


I want to filter my data by server name. Here is my config and map file. I try to filter first by pillar (which works), then by grain (which doesn't work). How do I do a double filter? Goal is to pull the configs for each server.

# defaults.yaml
Dev:
  server1:
    options:
      - name: app1
        run: true
  
  server2:
    options:
      - name: app1
        run: true
        
      - name: app2
        run: false
        
Prod:
  server1:
    options:
      - name: app1
        run: true
        
  server2:
    options:
      - name: app1
        run: false
        
      - name: app2
        run: true
{% import_yaml tpldir ~ '/defaults.yaml' as defs %}
{% set data = salt['pillar'].filter_by( defs,
pillar='env' , 
default=''
) %}

{% set location_data = salt['grains'].filter_by( data,
grains='hostname', 
default=''
) %}

My use case requires passing commandline pillar - env: dev


Solution

  • The argument is grain, not grains:

    {% set location_data = salt["grains.filter_by"](data, grain="hostname", default="") %}
    

    But, as you aren't actually providing any defaults, merges, nor base; you don't need any filter_by at all:

    {% set location_data = defs[pillar["env"]][grains["hostname"]] %}
    

    Overall it looks like you're just trying to reimplement Salt's existing topfile system. It may be simpler still to just use that:

    Dev:
      server1:
        - app1
      server2:
        - app1
            
    Prod:
      server1:
        - app1
      server2:
        - app2
    

    Which can be simplified even further with minion matching, env merging, etc.