第四章:jianja2模板用法

第一节:jinja2介绍

Jinja2是基于python的模板引擎,功能比较类似于PHP的smarty,J2ee的Freemarker和velocity。它能完全支持unicode,并具有集成的沙箱执行环境,应用广泛。jinja2使用BSD授权

第二节:jianja2判断语句

{% if EXPR %}...{% elif EXPR %}...{% endif%} 作为条件判断

1.EXAMPLE:

{% if ansible_fqdn == "web01" %}
echo "123"
{% elif ansible_fqdn == "web02" %}
echo "456"
{% else %}
echo "789"
{% endif %}

2.jianja2渲染keepalived配置文件

[root@m01 /roles]# cat keepalived/templates/keepalived.conf.j2
global_defs {
router_id {{ ansible_hostname }}
}

vrrp_script check_web {
script "/server/scripts/check_web.sh"
interval 5
weight 50
}

{% if ansible_hostname == "lb03" %}
vrrp_script check_vip {
script "/server/scripts/check_vip.sh"
interval 5
weight 50
}
{% endif %}

vrrp_instance VI_1 {
state {{ state }}
interface eth0
virtual_router_id 50
priority {{ priority }}
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.3
}
track_script {
check_web
{% if ansible_hostname == "lb03" %}
check_vip
{% endif %}
}
}

第三节:jianja2循环语句

1.EXAMPLE

{% for i in EXPR %}...{% endfor%} 作为循环表达式
{% for i in range(1,10) %}
server 172.16.1.{{i}};
{% endfor %}
{# COMMENT #} 表示注释

2.jinja2 渲染 nginx_proxy配置文件

[root@m01 project1]# cat kod_proxy.conf.j2
upstream web_pools {
{% for i in range(1,10) %}
server 172.16.1.{{i}}:{{http_port}} weight=2;
{% endfor %}
}

server {
listen 80;
server_name web_pools;
location / {
proxy_pass http://{{ server_name }};
include proxy_params;
}
}

第四节:jinja循环高级用法

1.循环inventory主机清单(hosts文件)中的webserver组,将提取到的IP赋值给i变量.

upstream web_pools {
{% for i in groups['webserver'] %}
server {{i}}:80;
{% endfor %}

2.官方举例

{% for host in groups['app_servers'] %}

something that applies to all app servers.

{% endfor %}

https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html

3.Inventory中的host_vars根据不同主机设定不同的变量。

[root@m01 project1]# cat host_vars/172.16.1.5
state: MASTER
prioroty: 150
[root@m01 project1]# cat host_vars/172.16.1.6
state: BACKUP
prioroty: 100

4.判断变量是否有值

- hosts: webservers
gather_facts: no
vars:
PORT: 13306
tasks:

  • name: Copy MySQL Configure
    template:
    src: my.cnf.j2
    dest: /tmp/my.cnf

    [root@m01 project1]# cat my.cnf.j2
    {% if PORT %}
    bind-address=0.0.0.0:{{ PORT }}
    {% else %}
    bind-address=0.0.0.0:3306
    {% endif %}

你可能感兴趣的:(第四章:jianja2模板用法)