使用 SAN 中的所有主机名模板化 Jinja2 CSR conf

Templating a Jinja2 CSR conf with all hostnames in SAN

我的 Ansible 库存中有 3 台服务器:

[hosts]
ServerA ansible_host=hostname1.domain ...
ServerB ansible_host=hostname2.domain ...
ServerC ansible_host=hostname3.domain ...

我想用主题备用名称中的所有主机名生成 CSR,前段时间,我听说了 Jinja 模板,所以我认为准备模板并从 Ansible 动态获取主机名列表会很好。有人可以帮我告诉我如何在 Jinja 模板中搜索 ansible_host 吗?我可以使用魔法变量吗?

所以我的 CSR 配置如下:

[req]
distinguished_name = req_distinguished_name
req_extensions = req_ext
prompt = no
[req_distinguished_name]
emailAddress = email@address.com
C            = US
O            = Google
OU           = HR
CN           = {{ AppNameDns }}
[req_ext]
subjectAltName = @alt_names
[alt_names]
DNS.1=hostname1.domain
DNS.2=hostname2.domain
DNS.3=hostname3.domain

确实,使用特殊变量 groups 可以列出特定组的所有主机,使用特殊变量 hostvars 可以访问这些主机的变量。

也可以使用Jinja中的the special variables of the loop来创建索引。

所以你的配置文件的结尾是:

[alt_names]
{% for alt_host in groups['hosts'] %}
DNS.{{ loop.index }}={{ hostvars[alt_host].ansible_host }}
{% endfor %}