目录
- ansible jinja2模板概述
- ansible jinja2模板使用
- 基本语法
- jinja2模板逻辑判断
- ansible jinja2管理nginx
- ansible jinja2管理keepalived
- keepalived原配
- 推送keepalived配置文件
- 准备keepalived配置文件
ansible jinja2模板概述
ansible允许jinja2模板中使用条件判断和循环,但是不允许在playbook中使用
ansible jinja2模板使用
基本语法
{{ EXPR }}输出变量值,会输出自定义的变量值或facts
1)playbook文件使用template模块
2)模板文件里面变量使用{{名称}},比如{{PORT}}或使用facts
jinja2模板逻辑判断
#循环表达式
{% for i in EXPR %}
{% endfor %}
#条件判断
{% if EXPR %}
{% elif EXPR %}
{% else %}
{% ednif %}
#注释
{# COMMENT #}
jinja2示例
- 编辑playbook
[root@m01 ~]# vim jinja2.yml
- hosts: web_group
tasks:
- name: Copy Template File
template:
src: ./motd.j2
dest: /etc/motd
- 准备motd.j2
[root@m01 ~]# vim motd.j2
Welcome to {{ ansible_fqdn }}
This system total mem is : {{ ansible_memtotal_mb }} MB
This system free mem is: {{ ansible_memfree_mb }} MB
- 执行playbook
ansible jinja2管理nginx
使用playbook推送文件
1.编辑playbook
[root@m01 ~]# vim lb.yml
- hosts: lb_group
vars:
http_port: 80
server_name: www.drz.com
tasks:
- name: copy
template:
src: ./www.drz.com.conf.j2
dest: /etc/nginx/conf.d/www.drz.com.conf
notify: reload nginx
handlers:
- name: reload nginx
systemd:
name: nginx
state: reloaded
2.准备配置文件
[root@m01 ~]# vim lb.yml
- hosts: lb_group
vars:
http_port: 80
server_name: www.drz.com
tasks:
- name: copy
template:
src: ./www.drz.com.conf.j2
dest: /etc/nginx/conf.d/www.drz.com.conf
notify: reload nginx
handlers:
- name: reload nginx
systemd:
name: nginx
state: reloaded
ansible jinja2管理keepalived
keepalived原配
#keepalived master 配置文件
global_defs {
router_id lb01
}
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
}
}
#keepalived backup配置文件
global_defs {
router_id lb02
}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 50
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.3
}
}
推送keepalived配置文件
[root@m01 ~]# vim keepalived.yml
- hosts: lb_group
tasks:
- name: copy file
template:
src: ./keepalived.j2
dest: /etc/keepalived/keepalived.conf
notify: restart keepalived
handlers:
- name: restart keepalived
systemd:
name: keepalived
state: restarted
准备keepalived配置文件
[root@m01 ~]# vim keepalived.j2
global_defs {
router_id {{ ansible_fqdn }}
}
vrrp_instance VI_1 {
{% if ansible_fqdn == "lb01" %}
state MASTER
priority 150
{% else %}
state BACKUP
priority 100
{% endif %}
interface eth0
virtual_router_id 50
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.3
}
}