-1

I'm using a jinja one-to-many key-value dictionary in a SaltStack state:

{% for key in {'bash history': ['bash_history-backup.sh', 'History backup'],
                  'empty trash': ['delete-trash-files.sh', 'Delete trash files'],
                  'keepass backup': ['keepass-backup.sh', 'Backup KeePass'],
                  'db backup': ['mysql-backup.sh', 'Backup MySQL']} %}
{{ [key][0] }}:
  cron.present:
    - name: /home/vplagov/scripts/{{ [key][0] }}
    - user: vplagov
    - minute: 20
    - hour: 1
    - comment: 
    - require:
      - git: checkout latest bash_history backup
{% endfor %}

What I want to implement is to iterate not only through keys in this dictionary but through values assigned to this key as well. For example, use first value in name, second in comment and so on. Currently, I've managed to iterate through keys using [key][0] statement as shown above.

Do I need to use a second loop inside to iterate through values for each of a key? And how can I make it?

Vitali Plagov
  • 722
  • 1
  • 12
  • 31

2 Answers2

3

Taken literally, you can do something like this:

{%- set cronjobs = {'key1': [val1, val2], 'key2': [val1, val2]} %}
{%- for key, values in cronjobs.items() %}
{{ values[0] }}:
  cron.present:
    - name: /home/vplagov/scripts/{{ values[0] }}
    - comment: {{ values[1] }}
    # fixed values here...
{%- endfor %}

But if your example is close to your actual use case, I think you only need a flat dict. See if this suits your needs better:

{%- load_yaml as cronjobs %}
bash-history-backup.sh: History backup
delete-trash-files.sh: Delete trash files
keepass-backup.sh: Backup keepass
# ...more here...
{%- endload %}

{%- for script, comment in cronjobs.items() %}
cronjob-{{ script }}:
  cron.present:
    - name: /home/vplagov/scripts/{{ script }}
    - comment: {{ comment }}
    - minute: 20
    # etc
{%- endfor %}
Andrew
  • 4,058
  • 4
  • 25
  • 37
1

Have you tried to set an items variable?

from jinja2 import Template
tmpl = """
{% set items = {'bash history': ['bash_history-backup.sh', 'History backup'],
                  'empty trash': ['delete-trash-files.sh', 'Delete trash files'],
                  'keepass backup': ['keepass-backup.sh', 'Backup KeePass'],
                  'db backup': ['mysql-backup.sh', 'Backup MySQL']} %}
{% for key in items %}
{{ [key][0] }}:
  cron.present:
    - name: /home/vplagov/scripts/{{ items[key][0] }}
    - user: vplagov
    - minute: 20
    - hour: 1
    - comment: {{items[key][1]}}
    - require:
      - git: checkout latest bash_history backup
{% endfor %}
"""

template = Template(tmpl)
print(template.render())
Rafał
  • 685
  • 6
  • 13
  • Thanks for the answer! That worked. But I don't really understand how do `[key][0]` and `items[key][0]` work? I mean, why in the first declaration you didn't use the variable name and used it in a second and third declaration? – Vitali Plagov Aug 26 '18 at 22:01