Jinja 转义评论标签的开头

Jinja escaping beginning of comment tag

我正在尝试在神社模板中创建一个 bash 脚本。我有以下行:

SOME_ARRAY_COUNT=${#SOME_ARRAY[@]}

但它抛出一个错误:

AnsibleError: template error while templating string: Missing end of comment tag

经过调查我发现 {% 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

有没有不改变 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

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 ...

问题:

此行:SOME_ARRAY_COUNT=${#SOME_ARRAY[@]} 在第一个模板任务中导致要求结束 #} 注释标记。首先修复添加原始块:

{% raw %}
SOME_ARRAY_COUNT=${#SOME_ARRAY[@]}
{% endraw %}

修复了模板部分,但 cloudformation 模块也应用了模板替换,因此它会出现相同的错误。

修复:

{% raw %}
SOME_ARRAY_COUNT=${{ '{#' }}SOME_ARRAY[@]}
{% endraw %}

第一个模板模块删除原始块并保留 {{ '{$' }},cloudformation 模块找到 {{ '{$' }} 并应用文字替换。

如果我把它放入 script.sh:

SOME_ARRAY="some array with elements"
SOME_ARRAY=($SOME_ARRAY)
{% raw %}
SOME_ARRAY_COUNT=${#SOME_ARRAY[@]}
{% endraw %}

然后变成 playbook.yml:

---
- hosts: localhost
  gather_facts: false

  tasks:
    - name: create script
      template:
        src: ./script.sh.j2
        dest: ./script.sh

当我 运行 ansible-playbook playbook.yml 时,我得到输出:

PLAY [localhost] *************************************************************************************************************************************************************

TASK [create script] *********************************************************************************************************************************************************
changed: [localhost]

script.sh 看起来像:

SOME_ARRAY="some array with elements"
SOME_ARRAY=($SOME_ARRAY)

SOME_ARRAY_COUNT=${#SOME_ARRAY[@]}

据我所知,一切似乎都按预期工作。