自动化运维工具-Ansible Jinja2模板

annan 2020-06-20

自动化运维工具-Ansible Jinja2模板

jinja2

jinja2跟ansible的关系

Ansible通常会使用jinja2模板来修改被管理主机的配置文件等...在saltstack中同样会使用到jinja2

为了方便,使用jinja2语法,渲染配置文件

jinja2的语法

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


## 调用变量
{{ 变量名 }}  ## jinja2会自动把带有{{ 变量名 }} 替换成变量值

## 模板文件:也就是我们的配置文件(要推送的文件,并且文件中需要变量)


## 模板文件里的变量
1.可以调用自己设置的web_user_group: www
{{ web_user_group }}

2.可以调用facts变量:ansible web01 -m setup
{{ ansible_fqdn }}  ## 获取主机名
{{ ansible_memtotal_mb }}  ## 获取总内存大小
案例:MySQL根据物理主机的内存大小,来设置分配的内存空间
MySQL占物理内存的 75% ~ 80%



## 逻辑判断语法:
注释:{# 被注释的内容 #}

循环:{% for 变量名 in range(1,101) %}
        {{ 变量名 }}
	 {% endfor %}


判断: 
{% if ansible_fqdn == ‘db01‘ %}
	mem=16G
{% elif ansible_fqdn == ‘db02‘ %}
	mem=8G
{% else %}
	mem=4G
{% endif %}

Jinja2的使用

案例一:使用变量推送motd

{# 直接调用变量的方式 #}
[ ~]# cat motd.j2
欢迎来到红浪漫
总共技师个数: {{ ansible_memtotal_mb }}
剩余技师个数: {{ ansible_memfree_mb }}
红浪漫浦东新区地址: {{ ansible_eth0[‘ipv4‘][‘address‘] }}

[ ~]# cat push_motd.yml 
- hosts: all
  tasks:
    - name: Push Motd File
      template:
        src: ./motd.j2
        dest: /etc/motd

案例二:使用Jinja2管理nginx

[ ~]# cat proxy.conf 
upstream web {
	{# 下面的循环是1-100的IP #}
	{% for num in range(1,101) %}
	server 10.0.0.{{ num }}:{{ backend_port }}
	{% endfor %}
}
server {
	listen {{ port }};

	{% if ansible_hostname == ‘web01‘ %}
		server_name {{ domain_name1 }};
	{% elif ansible_hostname == ‘web02‘ %}
		server_name {{ domain_name2 }};
	{% else %}
		server_name {{ domain_name3 }};
	{% endif %}

	location / {
		proxy_pass http://web;
		proxy_set_header Host $host;
	}
}


[ ~]# cat a.yml 
- hosts: web_group
  vars:
    - backend_port: 8080
    - port: 80
  tasks:
    - name: config nginx conf
      template:
        src: ./proxy.conf
        dest: /root

使用jinja2管理keepalived

{# keepalived的配置文件 #}
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
    }
}


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配置文件改成模板文件 #}
global_defs {
    router_id {{ ansible_fqdn }}
}

vrrp_instance VI_1 {
	{% if ansible_fqdn == ‘lb01‘ %}
    state MASTER
    priority 150
    {% elif ansible_fqdn == ‘lb02‘ %}
    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
    }
}

{# 推送的文件 #}

[ ~]# vim a.yml
- hosts: lb_group
  vars:
  tasks:
    - name: config keep conf
      template:
        src: ./keep.conf
        dest: /root

    - name: xxx shell
      copy:
        src:
        dest:
      when: ansible_fqdn == ‘lb01‘

Jinja2管理MySQL

{# 安装配置MySQL #}
- hosts: db_group
  tasks:
    - name: i m
      yum:
        name:
          - mariadb-server
          - MySQL-python
        state: present

    - name: t c
      template:
        src: ./my.j2
        dest: /etc/my.cnf

{# MySQL的模板文件 #}
[ ~]# vim my.j2 

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
innodb_buffer_pool_size = {{ (ansible_memtotal_mb * 80 / 100)|int }}
symbolic-links=0
[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid

!includedir /etc/my.cnf.d

ansible roles

官方推荐目录层级

[ roles]# tree wordpress/
wordpress/          #项目名称
├── defaults        #低优先级变量
├── files           #存放文件
├── handlers        #触发器文件
├── meta            #依赖关系文件
├── tasks           #工作任务文件
├── templates       #jinja2模板文件
├── tests           #测试文件
└── vars            #变量文件

ansible roles 最佳实践

# 1.创建一个roles的项目
[ roles]# ansible-galaxy init rsync
[ roles]# tree rsync/
rsync/
├── defaults
│?? └── main.yml
├── files
├── handlers
│?? └── main.yml
├── meta
│?? └── main.yml
├── README.md
├── tasks
│?? └── main.yml
├── templates
├── tests
│?? ├── inventory
│?? └── test.yml
└── vars
    └── main.yml


# 2.维护roles中的主机清单
[ roles]# cat /etc/ansible/roles/hosts 
[web_group]
web01 ansible_ssh_host=10.0.0.7
web02 ansible_ssh_host=10.0.0.8
[lb_group]
lb01 ansible_ssh_host=10.0.0.5
lb02 ansible_ssh_host=10.0.0.6
[backup_group]
backup ansible_ssh_host=10.0.0.41
[nfs_group]
nfs ansible_ssh_host=10.0.0.31
[db_group]
db01 ansible_ssh_host=10.0.0.51
db02 ansible_ssh_host=10.0.0.52
[install_nfs:children]
web_group
nfs_group
[install_rsync:children]
nfs_group
backup_group
# 写一个ansible roles入口文件,必须命名site.yml
[ roles]# vim site.yml
- hosts: all
  roles:
    ## 按照目录名来写
    - rsync
  when: anisble_fqdn == ‘backup‘


## 准备rsync的配置文件
[ rsync]# cat templates/rsyncd.j2 
uid = www
gid = www
port = 873
fake super = yes
use chroot = no
max connections = 200
timeout = 600
ignore errors
read only = false
list = false
auth users = {{ ansible_fqdn }}
secrets file = /etc/rsync.passwd
log file = /var/log/rsyncd.log
#####################################
[backup]
comment = welcome to oldboyedu backup!
path = /backup

## 编写rsync安装文件
[ rsync]# vim tasks/install_rsync.yml 
- name: Install Rsync Server
  yum:
    name: rsync
    state: present

## 编写rsync的配置
[ rsync]# vim tasks/config_rsync.yml
- name: Configure Rsync Config
  template:
    src: rsyncd.j2
    dest: /etc/rsyncd.conf
  notify: Restart Rsync

## 编写rsync启动文件
[ rsync]# vim tasks/start_rsync.yml

- name: Start Rsync Server
  service:
    name: rsyncd
    state: started
    enabled: true


## 编写触发器
[ rsync]# vim handlers/main.yml 
# handlers file for rsync
- name: Restart Rsync
  service:
    name: rsyncd
    state: restarted

相关推荐