如何在我的j2模板中使用主机名?我在尝试时遇到了一些错误

时间:2019-05-22 05:42:53

标签: ansible jinja2

我尝试使用j2模板生成ssl密钥。但是我遇到了一个问题,我的conf文件可以加载可用的主机名。

我所有的服务器都是Centos7

我的j2:

{% set count=2 %}
[ req ]
default_bits = 4096
prompt = no
default_md = sha512
req_extensions = req_ext
distinguished_name = dn

[ dn ]
C = CN
ST = GZ
L = SZ
O = TR_Cloud
OU = dev
CN = {{ ansible_hostname }}

[ req_ext ]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = localhost
{% for host in groups['etcd'] %}
DNS.{{ count }} = {{ host }}
{% set count=count+1 %}
{% endfor %}
{% set count=2 %}
IP.1 = 127.0.0.1
{% for host in groups['etcd'] %}
DNS.{{ count }} = {{ host['ansible_hostname'] }}
{% set count=count+1 %}
{% endfor %}

[ v3_ext ]
authorityKeyIdentifier=keyid,issuer:always
basicConstraints=CA:FALSE
keyUsage=keyEncipherment,dataEncipherment
extendedKeyUsage=serverAuth,clientAuth
subjectAltName=@alt_names

错误: “ unicode对象”没有属性“ ansible_hostname”

我要在空白处更新主机名。

1 个答案:

答案 0 :(得分:0)

正如@Zeitounator所说。 host ['ansible_hostname']中存在错误。我已经修改了代码,以便与其他情况很好地复制。

{% set count=2 %}
[ req ]
default_bits = 4096
prompt = no
default_md = sha512
req_extensions = req_ext
distinguished_name = dn

[ dn ]
C = CN
ST = GZ
L = SZ
O = TR_Cloud
OU = dev
CN = {{ inventory_hostname }}

[ req_ext ]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = localhost
{% for host in groups['etcd'] %}
DNS.{{ count }} = {{ host }}
{% set count=count+1 %}
{% endfor %}
{% set count=2 %}
IP.1 = 127.0.0.1
{% for host in groups['etcd'] %}
IP.{{ count }} = {{ hostvars[host]['ansible_'+interface]['ipv4']['address'] }}
{% set count=count+1 %}
{% endfor %}

[ v3_ext ]
authorityKeyIdentifier=keyid,issuer:always
basicConstraints=CA:FALSE
keyUsage=keyEncipherment,dataEncipherment
extendedKeyUsage=serverAuth,clientAuth
subjectAltName=@alt_names