修复 Ansible Jinja2 模板语法 | AI生成和翻译
错误很明显,来自于您的 hello.yml playbook 中的这一行:
content: "Managed by Ansible — hello from \n"
dest: /tmp/hello.txt
选项 2 – 如果您确实想显示字面量 “” 字符串(而不是求值)
- name: Create a file with some text
ansible.builtin.copy:
content: "Managed by Ansible — hello from ' }}\n"
dest: /tmp/hello.txt
选项 3 – 使用 | 的多行(字面量块标量)
- name: Create a file with some text
ansible.builtin.copy:
content: |
Managed by Ansible — hello from
This is line 2
This is line 3
dest: /tmp/hello.txt
选项 4 – 使用 > 的折叠样式
- name: Create a file with some text
ansible.builtin.copy:
content: >-
Managed by Ansible — hello from
Second line starts here.
dest: /tmp/hello.txt
完整修正后的最小 playbook(工作示例)
---
- name: Tiny demo
hosts: localhost
gather_facts: yes
tasks:
- name: Create a file with some text
ansible.builtin.copy:
content: "Managed by Ansible — hello from on \n"
dest: /tmp/hello_from_ansible.txt
mode: '0644'
再次运行它:
ansible-playbook scripts/ansible/hello.yml
现在它将成功运行,没有任何模板语法错误。
根本原因只是那个多余的 ! 和未处理的 \n。移除 !,使用一个真正的变量(或者如果您想让大括号字面化,就转义它们),您就可以顺利进行!