自动化运维利器Ansible-jinja2模板
JnJa2模板
要学会Ansible 中的模板(template)使用,前提我们必须要学会JinJa2模板。学会了它,就相当于我们学会了Ansible 模板。
JinJa2 是什么
Jinja2是基于Python书写的模板引擎。功能比较类似于PHP的smarty模板。
JinJa2 必知必会
- jinja2 文件以
.j2
为后缀, 也可以不写后缀。 - jinja2 中存在 三种定界符
- 注释: {# 注释内容 #}
- 变量引用: { { var }}
- 逻辑表达: {% %}
JinJa2 逻辑控制
条件表达
{% if 条件表达式 %}
条件表达式为真,显示的内容
{% elif 条件表达式 %}
条件表达式为真,显示的内容
{% else %}
...
{% endif %}
Example
{# 如果定义了 idc 变量, 则输出 #}
{% if idc is defined %}
{
{ idc }}
{% else %}
没有定义
{% endif %}
循环控制
{% for %}
...
...
{% endfor %}
Example
{# 列举出 dbservers 这个 group 中的所有主机 #}
{% for host in groups['dbservers'] %}
{
{ host }}
{% endfor %}
{#与Python 语法不通,模板中的循环内不能break或continue。但你可以在迭代中过滤序列来跳过某些项#}
{#打印dbservers 组中的所有主机,但是不打印1.1.1.1 这台主机#}
{% for host in groups['dbservers'] if host != "1.1.1.1" %}
{
{host}}
{% endfor %}
如何使用模板
一个基于Facts的Jinja2 实例
# cat config.j2
{# use variable example #}
wlecome host {
{ ansible_hostname }}, os is {
{ ansible_os_family }}
today is {
{ ansible_date_time.date }}
cpucore numbers {
{ ansible_processor_vcpus }}
{# use condition example #}
{% if ansible_processor_vcpus > 1 %}
OS CPU more than one core
{% endif %}
{% for m in ansible_mounts if m['mount'] != "/" %}
mount {
{ m['mount'] }}, total size is {
{m['size_total']}}, free size is {
{m['size_available']}}
{% endfor %}
在Ansible 中使用模板
---
- name: a template example
hosts