0%

Ansible-jinja2-roles

ansible jinja2 roles

jinja2基本 语法

1
2
3
{{ EXPR }}输出变量值,会输出自定义的变量值或facts
1)playbook文件使用template模块
2)模板文件里面变量使用{{名称}},比如{{PORT}}或使用facts

逻辑判断语法

1
2
3
4
5
6
7
8
9
10
11
12
#循环表达式
{% for i in EXPR %}
{% endfor %}

#条件判断
{% if EXPR %}
{% elif EXPR %}
{% else %}
{% endif %}

#注释
{# COMMENT #}

测试jinja2

1
2
3
4
5
6
7
8
9
10
11
12
- hosts: all
tasks:
- name: scp motd
template:
src: /etc/motd
dest: /etc/motd


[root@m01 ~]# vim /etc/motd
Welcome to {{ ansible_fqdn }}
This system total mem is : {{ ansible_memtotal_mb }} MB
This system free mem is: {{ ansible_memfree_mb }} MB

ansible jinja2渲染负载均衡配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[root@m01 ~]# cat nginx.conf.j2 
upstream {{ domain_name }} {
{% for ip in range(1,16) %}
server 172.16.1.{{ ip }}:{{ upstream_port }};
{% endfor %}
}

server {
listen {{ server_port }};
server_name {{ domain_name }};

location / {
root {{ code_dir }};
index index.html;
proxy_pass http://{{ domain_name }};
proxy_set_header HOST $http_host;
}
}
1
2
3
4
5
6
7
8
[root@m01 ~]# cat  nginx.yml 
- hosts: all
vars_files: ./wordpress_vars.yml
tasks:
- name: configure nginx conf
template:
src: ./nginx.conf.j2
dest: /opt/{{ domain_name }}.conf
1
2
3
4
5
[root@m01 ~]# cat wordpress_vars.yml 
domain_name: www.drz.com
upstream_port: 8080
server_port: 80
code_dir: /code/wordpress

ansible jinja2 推送keepalived配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#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
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[root@m01 ~]# cat keepalived.conf.j2 
global_defs {
router_id {{ ansible_fqdn }}
}

vrrp_instance VI_1 {
{% if ansible_fqdn == 'web01' %}
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
}
}
1
2
3
4
5
6
7
[root@m01 ~]# cat keep.yml 
- hosts: webs
tasks:
- name: configure keep conf
template:
src: ./keepalived.conf.j2
dest: /opt/keepalive.conf

ansible roles

roles依赖关系

1
2
3
4
5
6
7
8
dependencies: 
- { role: nginx }
- { role: php }


[root@m01 meta]# vim main.yml
dependencies:
- { role: rsync_server }
1
2
3
4
5
6
- name: xx
mysql_user:
name: rep
password: 123
priv: '*.*:replication slave'
state: present