Python 金甲2号';{%set…%}';ansible playbook中的处理
我不明白如何在ansible剧本中使用jinja2模板命令 我的理解是,在执行之前,playbook应该作为jinja2模板处理,但显然不能在文件解析为yaml之前处理,因为在文件顶部使用jinja2命令会产生语法错误,例如:Python 金甲2号';{%set…%}';ansible playbook中的处理,python,ansible,jinja2,ansible-template,Python,Ansible,Jinja2,Ansible Template,我不明白如何在ansible剧本中使用jinja2模板命令 我的理解是,在执行之前,playbook应该作为jinja2模板处理,但显然不能在文件解析为yaml之前处理,因为在文件顶部使用jinja2命令会产生语法错误,例如: {% set test_var = "test_value" %} - hosts: all remote_user: "my_user" tasks: - debug: var=test_var {% set another_var = "ano
{% set test_var = "test_value" %}
- hosts: all
remote_user: "my_user"
tasks:
- debug: var=test_var
{% set another_var = "another_value" %}
- debug: var=another_var
如果对JICAN2命令进行注释以避免该解析错误,则在顶部处理第一个命令,而不是在PooBooad中间的其他命令:
# {% set test_var = "test_value" %}
- hosts: all
remote_user: "my_user"
tasks:
- debug: var=test_var # this works
# {% set another_var = "another_value" %}
- debug: var=another_var
# ok: [localhost] => {
# "another_var": "VARIABLE IS NOT DEFINED!: 'another_var' is undefined"
# }
我不明白ansible是如何处理剧本模板的。难道不应该有一个只处理jinja2语法的第一个过程,然后在删除jinja2语法的情况下输出yaml吗
$ ansible-playbook --version
ansible-playbook 2.9.1
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/me/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/me/.local/lib/python3.7/site-packages/ansible
executable location = /home/me/.local/bin/ansible-playbook
python version = 3.7.3 (default, Apr 3 2019, 19:16:38) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]]
谢谢 jinja2在ansible运行时处理的是yaml变量的内容,而不是yaml文件本身。这是在几个过程中完成的,如果你想确切地了解引擎盖下面是什么,请仔细阅读ansible代码 为了让你走上正轨,这是你在问题中尝试的可行方法
- hosts: all
remote_user: "my_user"
# These are playbook vars set at playbook level
# Vars can also be in inventories, roles....
# see https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html
vars:
test_var: test_value
tasks:
- name: debug my test_var
debug:
var: test_var
- name: if you need to set var at run time you can use set_fact
set_fact:
# Jinja2 templating will be honored here
another_var: "another_{{ test_var }}"
- name: debug var we just valued
debug:
var: another_var
- hosts: all
remote_user: "my_user"
# These are playbook vars set at playbook level
# Vars can also be in inventories, roles....
# see https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html
vars:
test_var: test_value
tasks:
- name: debug my test_var
debug:
var: test_var
- name: if you need to set var at run time you can use set_fact
set_fact:
# Jinja2 templating will be honored here
another_var: "another_{{ test_var }}"
- name: debug var we just valued
debug:
var: another_var