什么是jinja2
jinja2是Python的全功能模板引擎
Jinja2模板和Ansible关系
Ansible通常会使用jinja2模板来修改被管理主机的配置文件等...在saltstack中同样会使用到jinja2 如果在100台主机 上安装nginx,每台nginx的端口都不一样,如何解决?
upstram www.yjt.com {
server 172.16.1.7;
server 172.16.1.8;
server 172.16.1.9;
}
这是原有的的样子
jiaja2模板基础语法
{{ 变量名 }} ## 调用变量
{# 注释 #}
jinja2判断语法
## shell判断
if [ 条件 ];then
xxx
elif [ 条件 ];then
aaa
else
bbb
fi
## Python判断
if 条件:
xxx
elif 条件:
aaa
else:
bbb
xxxx
## Jinja2判断
{% if 条件 %}
xxx
{% elif 条件 %}
aaa
{% else %}
bbb
{% endif %}
jinja2循环
{% for n in 条件 %}
xxx
{% endfor %}
jinja2实战部署keepalived
## keep配置文件(Master)
global_defs {
router_id lb01
}
vrrp_script check_web_yjt {
script "/root/check_web.sh"
interval 5
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 50
priority 150
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.3
}
track_script {
check_web_yjt
}
}
## keep配置文件(Backup)
global_defs {
router_id lb02
}
vrrp_instance VI_1 {
priority 100
state BACKUP
interface eth0
virtual_router_id 50
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.3
}
}
tasks.yml
- hosts: all
tasks:
- include: /root/ansible/keepalived/config_keepalived.yml
when: ansible_hostname is match 'web*'
handlers:
- name: Restart Keepalived
service:
name: keepalived
--------------------------------------------------------------------------
## 使用jinja2模板
keepalived.j2
global_defs {
router_id {{ ansible_hostname }}
}
{% if ansible_hostname == 'web01' %} # 如果主机名字是webo1,那么就执行下面的脚本
vrrp_script check_web_yjt {
script "/root/check_web.sh"
interval 5
}
vrrp_instance VI_1 {
track_script {
check_web_yjt
}
priority 150
state MASTER
{% else %} # 如果主机名字不是web01,那么就执行下面的
vrrp_instance VI_1 {
priority 100
state BACKUP
{% endif %} # 最后一样的内容
interface eth0
virtual_router_id 50
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.3
}
}
jinja2实战部署负载均衡
## nginx配置文件
upstream {{ wordpress_domain }} {
{% for num in range(7,10) %} # 循环,主机Ip为172.16.1.7到10
server 172.16.1.{{ num }};
{% endfor %}
}
server{
listen 80;
server_name {{ wordpress_domain }};
location /{
proxy_pass http://{{ wordpress_domain }};
}
}
- hosts: all
tasks:
- include: /root/ansible/lb/config_lb.yml
when: ansible_hostname is match 'web*'