我有以下 Ansible 变量:
environment:
CONFIG: |
external_url 'https://www.example.com'
external_port '9090'
USERNAME: root
ROOT_PASSWORD: verysecret
Ansible 模板文件:
environment:
{% for key, value in environment.items() %}
{{ key }}: {{ value }}
{% endfor %}
输出应该是:
environment:
CONFIG: |
external_url 'https://www.example.com'
external_port '9090'
USERNAME: root
ROOT_PASSWORD: verysecret
但是输出是:
environment:
CONFIG: external_url 'https://www.example.com'
external_port '9090'
USERNAME: root
ROOT_PASSWORD: verysecret
看起来
|
字符并没有按字面意思使用。它还打破了缩进。我应该在模板中使用哪个过滤器?
添加了我的剧本和更多内容,因为有人要求:
模板.j2:
---
- hosts: localhost
vars:
docker_compose_projects:
- name: project_1
services:
- service_name: some_service
image: some_image:latest
environment:
CONFIG: |
external_url 'https://www.example.com'
external_port '9090'
USERNAME: root
ROOT_PASSWORD: verysecret
tasks:
- name: template
ansible.builtin.template:
src: template.yml.j2
dest: "/home/username/{{ item.name }}"
loop: "{{ docker_compose_projects }}"
模板.yml.j2:
services:
{% for service in item.services %}
{{ service.service_name }}
image: {{ service.image }}
{% if service.environment is defined %}
environment:
{% for key, value in service.environment.items() %}
{{ key }}: {{ value }}
{% endfor %}
{% endif %}
{% endfor %}
输出(项目_1):
services:
some_service:
image: some_image:latest
environment:
CONFIG: external_url 'https://www.example.com'
external_port '9090'
USERNAME: root
ROOT_PASSWORD: verysecret
预期输出:
services:
some_service:
image: some_image:latest
environment:
CONFIG: |
external_url 'https://www.example.com'
external_port '9090'
USERNAME: root
ROOT_PASSWORD: verysecret
您只需将
|
放入模板本身即可保持多行格式。但正如评论中提到的U880D,你不能使用environment
作为你自己的变量,它将代表你在任务/游戏级别通过environment
关键字设置的变量:
# ...
services:
{% for service in item.services %}
{{ service.service_name }}
image: {{ service.image }}
{% if service.environment is defined %}
environment: |
{% for key, value in service.environment.items() %}
{{ key }}: {{ value }}
{% endfor %}
{% endif %}
{% endfor %}
# ...