我在SaltStack状态下使用了一个Jinja一对多键值字典:
{% 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 %}
我要实现的是不仅要通过此字典中的键进行迭代,而且还要通过分配给该键的值进行迭代。例如,在name
中使用第一个值,在comment
中使用第二个值,依此类推。目前,我已经设法使用[key][0]
语句遍历键,如上所示。
我是否需要在内部使用第二个循环来迭代每个键的值?而我该怎么做呢?
答案 0 :(得分:1)
您是否尝试过设置项目变量?
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())
答案 1 :(得分:1)
从字面上看,您可以执行以下操作:
{%- 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 %}
但是,如果您的示例接近您的实际用例,那么我认为您只需要简单的命令即可。看看这是否更适合您的需求:
{%- 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 %}