是否可以迭代多个 jinja 列表?尝试构建一个包含值的数组,然后将这些值迭代到渲染的输出中。
这是我尝试过的,for 循环似乎只迭代用户列表。我试图从定义的 jinja 列表 (用户、哈希、键) 中填充用户数据,然后为每个用户呈现值。
## template: jinja
#cloud-config
{% set users = ['usr1','usr2'] %}
{% set hashes = ['$6$usr1-hash/','$6$usr2-hash'] %}
{% set keys = ['ssh-ed25519 usr1-key','ssh-ed25519 usr2-key'] %}
{% for user in users %}
users:
- name: {{ user }}
{% set group = 'wheel' %}
groups: {{ group }}
sudo: ALL=(ALL) NOPASSWD:ALL
lock_passwd: false
passwd: {{ hashes }}
ssh_authorized_keys:
- {{ keys }}
shell: /bin/bash
user = {{ user }}
hash = {{ hash }}
key = {{ key }}
{% endfor %}
这只是填充了整个列表,那么让它迭代所有三个列表的正确语法是什么呢?我尝试了索引值(例如:hashes.1),这为每个用户提供了相同的值。
输出示例:
users:
- name: usr1
groups: wheel
sudo: ALL=(ALL) NOPASSWD:ALL
lock_passwd: false
passwd: ['$6$usr1-hash/', '$6$usr2-hash']
ssh_authorized_keys:
- ['ssh-ed25519 usr1-key', 'ssh-ed25519 usr2-key']
shell: /bin/bash
user = usr1
hash = CI_MISSING_JINJA_VAR/hash
key = CI_MISSING_JINJA_VAR/key
users:
- name: usr2
groups: wheel
sudo: ALL=(ALL) NOPASSWD:ALL
lock_passwd: false
passwd: ['$6$usr1-hash/', '$6$usr2-hash']
ssh_authorized_keys:
- ['ssh-ed25519 usr1-key', 'ssh-ed25519 usr2-key']
shell: /bin/bash
user = usr2
hash = CI_MISSING_JINJA_VAR/hash
key = CI_MISSING_JINJA_VAR/key
期望输出:
users:
- name: usr1
groups: wheel
sudo: ALL=(ALL) NOPASSWD:ALL
lock_passwd: false
passwd: '$6$usr1-hash/'
ssh_authorized_keys:
- 'ssh-ed25519 usr1-key'
shell: /bin/bash
user = usr1
hash = '$6$usr1-hash/'
key = 'ssh-ed25519 usr1-key'
users:
- name: usr2
groups: wheel
sudo: ALL=(ALL) NOPASSWD:ALL
lock_passwd: false
passwd: '$6$usr2-hash'
ssh_authorized_keys:
- 'ssh-ed25519 usr2-key'
shell: /bin/bash
user = usr2
hash = '$6$usr2-hash'
key = 'ssh-ed25519 usr2-key'
2
最佳答案
1
最终什么满足了我的需求。
## template: jinja
#cloud-config
{% set users = ['joe' , 'ansible' , 'foo' , 'bar'] %}
{% set hashes = '$6$eMxyzabc123/Mzt/','$6$ansiblehash','$7$foo-hash','$2$barhash' %}
{% set keys = ['- ssh-ed25519 joekey XX-ed25519-ansible','- ssh-ed25519 ansible_keyAAAAC3Nz','fookey','barkey' %}
{% set group = 'wheel' %}
users:
{% for i in users %}
{% set user = users[loop.index-1] %}
{% set hash = hashes[loop.index-1] %}
{% set key = keys[loop.index-1] %}
- name: {{ user }}
groups: {{ group }}
sudo: ALL=(ALL) NOPASSWD:ALL
lock_passwd: false
passwd: {{ hash }}
ssh_authorized_keys:
{{ key }}
shell: /bin/bash
{% endfor %}
|
for
模板中唯一的循环。预期结果是什么?对于其他列表,循环可能不是最佳解决方案,简单的join
可能更好。–
–
|