Jinja转义评论标签的开头

时间:2019-11-13 21:00:02

标签: ansible jinja2 template-engine templating

我正在尝试在Jinja模板中创建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逻辑的情况下是否有解决方法?

谢谢

更新:包括示例

可播放的剧本:

... 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模块找到{{ '{$' }}并应用文字替换。

1 个答案:

答案 0 :(得分:0)

如果我将其放入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[@]}

据我所知,一切似乎都按预期进行。