9uz*_*an7 7 template-engine templating jinja2 ansible
我正在尝试在 jinja 模板中创建 bash 脚本。我有以下几行:
SOME_ARRAY_COUNT=${#SOME_ARRAY[@]}
Run Code Online (Sandbox Code Playgroud)
但它会抛出一个错误:
AnsibleError: template error while templating string: Missing end of comment tag
Run Code Online (Sandbox Code Playgroud)
经过调查,我发现{% raw %}...{% endraw %}可以使用块来获取文字,但它仍然无法{#获得类似的错误:
An unhandled exception occurred while templating
Error was a <class 'ansible.errors.AnsibleError'>, original message: template error while templating string: Missing end of comment tag
Run Code Online (Sandbox Code Playgroud)
有没有解决这个问题而不改变 bash 逻辑的方法?
谢谢
更新:包括示例
Ansible 剧本:
... more ansible playbook stuff ...
tasks:
- name: create script
template:
src: "src/path/to/script.sh.j2"
dest: "dest/path/to/output/script.sh"
- name: user data script as string
set_fact:
userdata: "{{ lookup('file', 'path/to/script.sh') }}"
- name: some cloudformation thing
cloudformation:
stack_name: "stack_name"
state: present
region: "some region"
template: "path/to/template/cloudformation.json"
template_parameters:
... a bunch of params ...
UserDataScript: "{{ userdata }}"
tags:
... tags ..
metadata: "... metadata ..."
register: cloudformation_results
Run Code Online (Sandbox Code Playgroud)
jinja 模板(script.sh.j2):
... more script stuff ...
SOME_ARRAY="some array with elements"
SOME_ARRAY=($SOME_ARRAY)
SOME_ARRAY_COUNT=${#SOME_ARRAY[@]}
... more script stuff ...
Run Code Online (Sandbox Code Playgroud)
问题:
此行:SOME_ARRAY_COUNT=${#SOME_ARRAY[@]}导致第一个模板任务请求结束#}注释标签。首先修复添加原始块:
{% raw %}
SOME_ARRAY_COUNT=${#SOME_ARRAY[@]}
{% endraw %}
Run Code Online (Sandbox Code Playgroud)
修复了模板部分,但 cloudformation 模块还应用了模板替换,因此会出现相同的错误。
修复:
{% raw %}
SOME_ARRAY_COUNT=${{ '{#' }}SOME_ARRAY[@]}
{% endraw %}
Run Code Online (Sandbox Code Playgroud)
第一个模板模块删除原始块并保留{{ '{$' }},cloudformation 模块查找{{ '{$' }}并应用文字替换。
如果我把它放入script.sh:
SOME_ARRAY="some array with elements"
SOME_ARRAY=($SOME_ARRAY)
{% raw %}
SOME_ARRAY_COUNT=${#SOME_ARRAY[@]}
{% endraw %}
Run Code Online (Sandbox Code Playgroud)
这变成playbook.yml:
---
- hosts: localhost
gather_facts: false
tasks:
- name: create script
template:
src: ./script.sh.j2
dest: ./script.sh
Run Code Online (Sandbox Code Playgroud)
当我运行时ansible-playbook playbook.yml,我得到输出:
PLAY [localhost] *************************************************************************************************************************************************************
TASK [create script] *********************************************************************************************************************************************************
changed: [localhost]
Run Code Online (Sandbox Code Playgroud)
看起来script.sh像:
SOME_ARRAY="some array with elements"
SOME_ARRAY=($SOME_ARRAY)
SOME_ARRAY_COUNT=${#SOME_ARRAY[@]}
Run Code Online (Sandbox Code Playgroud)
据我所知,一切似乎都按预期进行。