04-template模板与roles
template模板
jinja2概述
- Jinja2 是一个现代的,设计者友好的,仿照 Django 模板的 Python 模板语言。 它速度快,被广泛使用,并且提供了可选的沙箱模板执行环境保证安全
- 特点:
-
沙箱中执行
-
强大的 HTML 自动转义系统保护系统免受 XSS
-
模板继承
-
及时编译最优的 python 代码
-
可选提前编译模板的时间
-
易于调试。异常的行数直接指向模板中的对应行
- 可配置语法
-
-
官方中文文档
http://docs.jinkan.org/docs/jinja2/ https://www.w3cschool.cn/yshfid/
- jinja2 语言支持多种数据类型和操作
字面量,如: 字符串:使用单引号或双引号,数字:整数,浮点数 列表:[item1, item2, ...] 元组:(item1, item2, ...) 字典:{key1:value1, key2:value2, ...} 布尔型:true/false 算术运算:+, -, *, /, //, %, ** 比较操作:==, !=, >, >=, <, <= 逻辑运算:and,or,not 流表达式:For,If,When
- 算术运算
+:把两个对象加到一起。通常对象是素质,但是如果两者是字符串或列表,你可以用这 种方式来衔接它们。无论如何这不是首选的连接字符串的方式!连接字符串见 ~ 运算符。 {{ 1 + 1 }} 等于 2 -:用第一个数减去第二个数。 {{ 3 - 2 }} 等于 1 /:对两个数做除法。返回值会是一个浮点数。 {{ 1 / 2 }} 等于 0.5 //:对两个数做除法,返回整数商。 {{ 20 // 7 }} 等于 2 %:计算整数除法的余数。 {{ 11 % 7 }} 等于 4 *:用右边的数乘左边的操作数。 {{ 2 * 2 }} 会返回 4 。也可以用于重 复一个字符串多次。 {{ '=' * 80 }} 会打印 80 个等号的横条\ **:取左操作数的右操作数次幂。 {{ 2**3 }} 会返回 8
- 比较操作符
== 比较两个对象是否相等 != 比较两个对象是否不等 > 如果左边大于右边,返回 true >= 如果左边大于等于右边,返回 true < 如果左边小于右边,返回 true <= 如果左边小于等于右边,返回 true
- 逻辑运算符
对于 if 语句,在 for 过滤或 if 表达式中,它可以用于联合多个表达式 and 如果左操作数和右操作数同为真,返回 true or 如果左操作数和右操作数有一个为真,返回 true not 对一个表达式取反 (expr)表达式组 true / false true 永远是 true ,而 false 始终是 false
template
template功能:可以根据和参考模块文件,动态生成相类似的配置文件
template文件必须存放于templates目录下,且命名为 .j2 结尾
yaml/yml 文件需和templates目录平级,目录结构如下示例:
./
├── temnginx.yml
└── templates
└── nginx.conf.j2
范例:利用template 同步nginx配置文件
#准备templates/nginx.conf.j2文件 [root@ansible ~]#vim temnginx.yml --- - hosts: websrvs remote_user: root tasks: - name: template config to remote hosts template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf [root@ansible ~]#ansible-playbook temnginx.yml
范例:template变更替换
#修改文件nginx.conf.j2 [root@ansible ~]#mkdir templates [root@ansible ~]#vim templates/nginx.conf.j2 ...... worker_processes {{ ansible_processor_vcpus }}; ...... [root@ansible ~]#vim temnginx2.yml --- - hosts: websrvs remote_user: root tasks: - name: install nginx yum: name=nginx - name: template config to remote hosts template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf - name: start service service: name=nginx state=started enabled=yes [root@ansible ~]#ansible-playbook temnginx2.yml
范例:template算术运算
vim nginx.conf.j2 worker_processes {{ ansible_processor_vcpus**2 }}; worker_processes {{ ansible_processor_vcpus+2 }}; [root@ansible ansible]#vim templates/nginx.conf.j2 worker_processes {{ ansible_processor_vcpus**3 }}; [root@ansible ansible]#cat templnginx.yml --- - hosts: websrvs remote_user: root tasks: - name: install nginx yum: name=nginx - name: template config to remote hosts template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf notify: restart nginx - name: start service service: name=nginx state=started enabled=yes handlers: - name: restart nginx service: name=nginx state=restarted [root@ansible ~]#-playbook templnginx.yml --limit 192.168.56.18
template中使用流程控制 for 和 if
- template中也可以使用流程控制 for 循环和 if 条件判断,实现动态生成文件功能
for 循环
格式: {% for i in EXPR %} ... {% endfor %} 示例: {% for i in range(1,10) %} server_name web{{i}}; {% endfor %}
- 范例:生成nginx端口81-83的server配置
#temlnginx2.yml --- - hosts: websrvs remote_user: root vars: nginx_vhosts: - 81 - 82 - 83 tasks: - name: template config template: src=nginx.conf2.j2 dest=/data/nginx.conf #templates/nginx.conf2.j2 {% for vhost in nginx_vhosts %} server { listen {{ vhost }} }{% endfor %} ansible-playbook -C templnginx2.yml --limit 192.168.18 #生成的结果: server { listen 81 } server { listen 82 } server { listen 83 }
#temlnginx3.yml --- - hosts: websrvs remote_user: root vars: nginx_vhosts: - listen: 8080 tasks: - name: config file template: src=nginx.conf3.j2 dest=/data/nginx3.conf #templates/nginx.conf3.j2 {% for vhost in nginx_vhosts %} server { listen {{ vhost.listen }} } {% endfor %} [root@ansible ~]#ansible-playbook templnginx3.yml --limit 10.0.0.8 #生成的结果 server { listen 8080 }
#templnginx4.yml - hosts: websrvs remote_user: root vars: nginx_vhosts: - listen: 8080 server_name: "web1.chengzi.com" root: "/var/www/nginx/web1/" - listen: 8081 server_name: "web2.chengzi.com" root: "/var/www/nginx/web2/" - {listen: 8082, server_name: "web3.chengzi.com", root: "/var/www/nginx/web3/"} tasks: - name: template config template: src=nginx.conf4.j2 dest=/data/nginx4.conf # templates/nginx.conf4.j2 {% for vhost in nginx_vhosts %} server { listen {{ vhost.listen }} server_name {{ vhost.server_name }} root {{ vhost.root }} }{% endfor %}
[root@ansible ~]#ansible-playbook templnginx4.yml --limit 192.168.56.18 #生成结果: server { listen 8080 server_name web1.chengzi.com root /var/www/nginx/web1/ } server { listen 8081 server_name web2.chengzi.com root /var/www/nginx/web2/ } server { listen 8082 server_name web3.chengzi.com root /var/www/nginx/web3/ }
#nginx.conf5.j2 upstream webservers { {% for in range(1,11) %} server 10.0.0.{{i}}:{{http_port}} {% endfor %} server { listen {{http_port}}; server_name {{server_name}}; location / { proxy_pass http://webservers; } } #templnginx5.yml - hosts: websrvs vars: http_port: 80 server_name: www.chengzi.org tasks: - name:install nginx yum: name=nginx - name: config file template: src=nginx.conf5.j2 dest=/etc/nginx/conf.d/web_proxy.conf - name: start nginx service: name=nginx state=started
#nginx.conf6.j2 upstream webservers { {% for in groups['webservers] %} server {{i}}:{{http_port}} {% endfor %} vim hosts [webservers] 192.168.56.101 192.168.56.102
if 条件判断
- 在模版文件中还可以使用 if条件判断,决定是否生成相关的配置信息
#templnginx6.yml - hosts: websrvs remote_user: root vars: nginx_vhosts: - web1: listen: 8080 root: "/var/www/nginx/web1/" - web2: listen: 8080 server_name: "web2.chengzi.com" root: "/var/www/nginx/web2/" - web3: listen: 8080 server_name: "web3.chengzi.com" root: "/var/www/nginx/web3/" tasks: - name: template config to template: src=nginx.conf5.j2 dest=/data/nginx5.conf #templates/nginx.conf6.j2 {% for vhost in nginx_vhosts %} server { listen {{ vhost.listen }} {% if vhost.server_name is defined %} server_name {{ vhost.server_name }} #注意缩进 {% endif %} root {{ vhost.root }} #注意缩进 }{% endfor %} #生成的结果 server { listen 8080 root /var/www/nginx/web1/ } server { listen 8080 server_name web2.chengzi.com root /var/www/nginx/web2/ } server { listen 8080 server_name web3.chengzi.com root /var/www/nginx/web3/ }
- 范例: 生成keepalived配置文件
vrrp_instrance VI_1 { {% if ansible_fqdn == "ka1" %}
state MASTER
priority 100
{% elif ansible_fqdn == "ka2" %}
state SLAVE
priority 80
{% endif% }
......
}
使用循环迭代
- 迭代:当有需要重复性执行的任务时,可以使用迭代机制
迭代 with_items(loop)
- 对迭代项的引用,固定内置变量名为"item"
- 要在task中使用with_items给定要迭代的元素列表
- 注意: ansible2.5版本后,可以用loop代替with_items
--- - hosts: websrvs remote_user: root tasks: - name: add several users user: name={{ item }} state=present groups=wheel with_items: - testuser1 - testuser2 - testuser3 #上面语句的功能等同于下面的语句 - name: add several users user: name=testuser1 state=present groups=wheel - name: add several users user: name=testuser2 state=present groups=wheel - name: add several users user: name=testuser3 state=present groups=wheel
- 范例:卸载 mariadb
--- #remove mariadb server - hosts: appsrvs:!192.168.18 remote_user: root tasks: - name: stop service shell: /etc/init.d/mysqld stop - name: delete files and dir file: path={{item}} state=absent with_items: - /usr/local/mysql - /usr/local/mariadb-10.2.27-linux-x86_64 - /etc/init.d/mysqld - /etc/profile.d/mysql.sh - /etc/my.cnf - /data/mysql - name: delete user user: name=mysql state=absent remove=yes
--- - hosts:websrvs remote_user: root tasks - name: install some packages yum: name={{ item }} state=present with_items: - nginx - memcached - php-fpm
--- - hosts: websrvs remote_user: root tasks: - name: copy file copy: src={{ item }} dest=/tmp/{{ item }} with_items: - file1 - file2 - file3 - name: yum install httpd yum: name={{ item }} state=present with_items: - apr - apr-util - httpd
迭代嵌套子变量
- 在迭代中,还可以嵌套子变量,关联多个变量在一起使用
--- - hosts: websrvs remote_user: root tasks: - name: add some groups group: name={{ item }} state=present with_items: - nginx - mysql - apache - name: add some users user: name={{ item.user }} group={{ item.group }} uid={{item.uid}} state=present with_items: - { user: 'nginx', group: 'nginx',uid: "80" } - { user: 'mysql', group: 'mysql' ,uid: "3306"} - { user: 'apache', group: 'apache',uid: "8080"}
- hosts: websrvs vars: rsyncd_conf: /etc/rsync.conf rsync_pass: /etc/rsync.pass tasks: - name: Configure Rsyncd Service template: src={{ item.src }} dest={{ item.dest }} mode={{ item.mode }} with items: - {src: './rsyncd.conf.j2', dest: {{ rsyncd_conf }}, mode: 0644 } - {src: './rsync.pass.j2', dest: {{ rsync_pass }}, mode: 0600 } #范例: 批量修改用户密码 --- - hosts: ssh-host gather_facts: false tasks: - name: change user passwd user: name={{ item.name }} password={{ item.chpass | password_hash('sha512') }} update_password=always with_items: - { name: 'root', chpass: '123456' } - { name: 'app', chpass: '654321' }
until 循环
#until为false时才会执行循环,为true则退出循环 [root@ansible ansible]#cat until.yml - hosts: localhost gather_facts: false tasks: - debug: msg="until" until: false retries: 3 #默认值即为3次 delay: 1 [root@ansible ansible]#ansible-playbook until.yml
with_lines 逐行处理
[root@ansible ansible]#cat with_lines.yml - hosts: localhost tasks: - debug: msg={{ item }} with_lines: ps aux
playbook使用 when
- when语句可以实现条件测试。如果需要根据变量、facts或此前任务的执行结果来做为某task执行与否的前提时要用到条件测试
- 通过在task后添加when子句即可使用条件测试,jinja2的语法格式
--- - hosts: websrvs remote_user: root tasks: - name: "shutdown RedHat flavored systems" command: /sbin/shutdown -h now when: ansible_os_family == "RedHat"
- 范例: 对主机名进行条件判断
--- - hosts: websrvs remote_user: root tasks: - name: install nginx yum: name=nginx when: ansible_fqdn is match ("web*")
- 范例: 判断服务状态决定是否重新启动
--- - hosts: websrvs tasks : - name: Check nginx Service #检查nginx服务是否是活动的 command: systemctl is-active nginx ignore_ errors: yes register: check_nginx - name: Httpd Restart #如果check nginx执行命令结果成功,即check_nginx.rc等于0,则执行重启nginx,否则跳过 service: name=nginx state=restarted when: check_nginx.rc == 0
- 范例: 分组判断
tasks: - name: "shut down CentOS 6 and Debian 7 systems" command: /sbin/shutdown -t now when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "6") \
or (ansible_facts['distribution'] == "Debian" and ansible_facts['distribution_major_version'] == "18")
- 范例: when的列表形式表示 and 关系
--- #关闭CentOS 7 版本的主机 - hosts: all tasks: - name: "shut down CentOS 7 systems" reboot: when: - ansible_facts['distribution'] == "CentOS" - ansible_facts['distribution_major_version'] == "7"
- 范例: 和循环一起使用
- hosts: localhost tasks: - debug: msg="item > 3" with_items: [1,2,3,4,5] when: item > 3
- 范例: 判断执行状态
--- - hosts: localhost tasks: - command: /bin/true register: result ignore_errors: True - debug: msg="failed" when: result is failed - debug: msg="succeeded" when: result is succeeded - debug: msg="skipped" when: result is skipped
- 范例: failed_when 满足条件时,使任务失败,和when功能相反
tasks: - command: echo failed register: result failed_when: "'failed' in result.stdout" #failed_when: false 不满足条件,任务正常执行 #failed_when: true 满足条件,使用任务失败 - debug: msg="echo failed_when"
--- - hosts: websrvs remote_user: root tasks: - name: add group nginx tags: user user: name=nginx state=present - name: add user nginx user: name=nginx state=present group=nginx - name: Install Nginx yum: name=nginx state=present - name: restart Nginx service: name=nginx state=restarted when: ansible_distribution_major_version == "6"
--- - hosts: websrvs remote_user: root tasks: - name: install conf file to centos7 template: src=nginx.conf.c7.j2 dest=/etc/nginx/nginx.conf when: ansible_distribution_major_version == "7" - name: install conf file to centos6 template: src=nginx.conf.c6.j2 dest=/etc/nginx/nginx.conf when: ansible_distribution_major_version == "6"
分组 block
- 当想在满足一个条件下,执行多个任务时,就需要分组了。而不再每个任务都是用when
[root@ansible ansible]#cat block.yml --- - hosts: localhost tasks: - block: - debug: msg="first" - debug: msg="second" when: - ansible_facts['distribution'] == "CentOS" - ansible_facts['distribution_major_version'] == "8" #相当于下面写法 --- - hosts: localhost tasks: - debug: msg="first" when: - ansible_facts['distribution'] == "CentOS" - ansible_facts['distribution_major_version'] == "8" - debug: msg="second" when: - ansible_facts['distribution'] == "CentOS" - ansible_facts['distribution_major_version'] == "8"
changed_when
关闭 changed 状态
- 当确定某个task不会对被控制端做修改时但执行结果却显示是黄色的changed状态,可以通过changed_when: false 关闭changed状态,减少信息输出
[root@ansible ansible]#cat test_changed.yml --- - hosts: websrvs tasks: - name: check sshd service shell: ps aux| grep sshd changed_when: false #关闭changed状态
利用 changed_when 检查task返回结果,决定是否向下执行
[root@ansible ansible]#cat test_changed_when.yml --- - hosts: websrvs tasks: - name: install nginx yum: name=nginx - name: config file template: src="nginx.conf.j2" dest="/etc/nginx/nginx.conf" notify: restart nginx - name: check config shell: /usr/sbin/nginx -t register: check_nginx_config changed_when: - (check_nginx_config.stdout.find('successful')) #如果执行结果中有successful字符串,则继续执行,如果没有则停止向下执行 - false #nginx -t 每次成功执行是changed状态,关闭此changed状态 - name: start service service: name=nginx state=started enabled=yes handlers: - name: restart nginx service: name=nginx state=restarted
滚动执行
- 管理节点过多导致的超时问题解决方法
- 默认情况下,Ansible将尝试并行管理playbook中所有的机器。
- 对于滚动更新用例,可以使用serial关键字定义Ansible一次应管理多少主机,还可以将serial关键字指定为百分比,表示每次并行执行的主机数占总数的比例
#vim test_serial.yml --- - hosts: all serial: 2 #每次只同时处理2个主机,将所有task执行完成后,再选下2个主机再执行所有task,直至所有主机 gather_facts: False tasks: - name: task one comand: hostname - name: task two command: hostname
- name: test serail hosts: all serial: "20%" #每次只同时处理20%的主机 [root@ansible ansible]#cat test_serial.yml --- - hosts: websrvs serial: 1 tasks: - name: task1 shell: wall "{{ansible_nodename}} is running task1" - name: task2 shell: wall "{{ansible_nodename}} is running task2" - name: task3 shell: wall "{{ansible_nodename}} is running task3"
委派至其它主机执行
- 利用委托技术,可以在非当前被控主机的其它主机上执行指定操作
[root@ansible ~]#cat delegate.yml #在192.168.56.18上执行hostname -I,而非当前主机localhost - hosts: localhost tasks: - name: show ip address command: hostname -I delegate_to: 192.168.56.18
#在本地执行ifconfig,而非192.168.56.18 [root@ansible ~]#cat delegate2.yml - hosts: 192.168.56.18 tasks: - name: show ip address local_action: command ifconfig
只执行一次
- 利用 run_once 指令可以只执行一次,而非在所有被控主机都执行
[root@ansible ~]#cat run_once.yml - hosts: websrvs tasks: - command: hostname run_once: true [root@ansible ~]#ansible-playbook run_once.yml --list-hosts
环境变量
- 临时修改环境变量
[root@ansible ~]#cat environment.yml - hosts: localhost tasks: - shell: echo $PATH environment: PATH: /usr/local/app/bin:{{ ansible_env.PATH }} [root@ansible ~]#ansible-playbook environment.yml -v
wait_for 等待条件再执行
#等待端口可用,才能执行任务 #暂停10s等待端口80打开,否则出错 wait_for: port=80 delay=10 #等待直到锁定文件被删除 wait_for: path=/var/lock/file.lock state=absent
yaml文件的相互调用
- 利用include 或 include_tasks 可以在某个task中调用其它的只有task内容的yaml文件
[root@ansible ansible]#cat a.yml --- - hosts: websrvs tasks: - name: run a job command: wall run a job - name: excute b.yml include: b.yml #调用另一个yaml文件 #include_tasks: b.yml #另一种写法 [root@ansible ansible]#cat b.yml - name: run b job command: wall run b job
- 多个包含完整内容的yml文件由一个yml统一调用
[root@ansible ansible]#cat total_tasks.yml - import_playbook: tasks1.yml - import_playbook: tasks2.yml [root@ansible ansible]#cat tasks1.yml --- - hosts: websrvs tasks: - name: run task1 job command: wall run task1 job [root@ansible ansible]#cat tasks2.yml --- - hosts: websrvs tasks: - name: run task2 job command: wall run task2 job
roles 角色
- roles用于层次性、结构化地组织playbook。roles能够根据层次型结构自动装载变量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令即可。
- 简单来讲,roles就是通过分别将变量、文件、任务、模板及处理器放置于单独的目录中,并可以便捷地include它们的一种机制。角色一般用于基于主机构建服务的场景中,但也可以是用于构建守护进程等场景中
- 运维复杂的场景:建议使用 roles,代码复用度高
- roles:多个角色的集合目录, 可以将多个的role,分别放至roles目录下的独立子目录中,如下示例
roles/ mysql/ nginx/ tomcat/ redis/ #roles默认存放路径 /root/.ansible/roles /usr/share/ansible/roles /etc/ansible/roles
范例:https://www.cnblogs.com/wt11/p/9391923.html
roles目录结构
playbook1.yml playbook2.yml roles/ project1/ tasks/ files/ vars/ templates/ handlers/ default/ meta/ project2/ tasks/ files/ vars/ templates/ handlers/ default/ meta/
Roles各目录作用
- roles/project/ :项目名称,有以下子目录
- files/ :存放由copy或script模块等调用的文件
- templates/:template模块查找所需要模板文件的目录
- tasks/:定义task,role的基本元素,至少应该包含一个名为main.yml的文件;其它的文件需要在此文件中通过include进行包含
- handlers/:至少应该包含一个名为main.yml的文件;此目录下的其它的文件需要在此文件中通过include进行包含
- vars/:定义变量,至少应该包含一个名为main.yml的文件;此目录下的其它的变量文件需要在此文件中通过include进行包含
- meta/:定义当前角色的特殊设定及其依赖关系,至少应该包含一个名为main.yml的文件,其它文件需在此文件中通过include进行包含
- default/:设定默认变量时使用此目录中的main.yml文件,比vars的优先级低
创建 role的步骤
- 创建role的目录结构.在以roles命名的目录下分别创建以各角色名称命名的目录,如mysql等
- 在每个角色命名的目录中分别创建相关的目录和文件,比如tasks、files、handlers、templates和vars等目录;用不到的目录可以创建为空目录,也可以不创建
- 编写和准备role的功能文件
- 编写playbook文件调用需要的角色应用于指定的主机
范例: 利用 ansible-galaxy 创建角色目录的结构
[root@ansible ansible]#ansible-galaxy init test_role - Role test_role was created successfully [root@ansible ansible]#tree test_role/ test_role/ ├── defaults │ └── main.yml ├── files ├── handlers │ └── main.yml ├── meta │ └── main.yml ├── README.md ├── tasks │ └── main.yml ├── templates ├── tests │ ├── inventory │ └── test.yml └── vars └── main.yml 8 directories, 8 files
范例:安装nginx的roles的目录结构
nginx-role.yml roles/ └── nginx ├── files │ └── nginx.conf ├── tasks │ ├── groupadd.yml │ ├── install.yml │ ├── main.yml │ ├── restart.yml │ └── useradd.yml └── vars └── main.yml
playbook 调用角色
调用角色方法1:
--- - hosts: websrvs remote_user: root roles: - mysql - memcached - nginx
调用角色方法2:
- 键role用于指定角色名称,后续的k/v用于传递变量给角色
--- - hosts: all remote_user: root roles: - role: mysql username: mysql - { role: nginx, username: nginx }
调用角色方法3:
- 基于条件测试实现角色调用
--- - hosts: all remote_user: root roles: - { role: nginx, username: nginx, when: ansible_distribution_major_version == '7' }
- 范例
--- - hosts: webservers roles: - common - role: foo_app_instance vars: dir: '/opt/a' app_port: 5000 tags: typeA - role: foo_app_instance vars: dir: '/opt/b' app_port: 5001 tags: typeB --- - hosts: webservers roles: - { role: foo, vars: { message: "first" } } - { role: foo, vars: { message: "second" } }
roles 中 tags 使用
[root@ansible ~]#vi app-role.yml --- #可以有多个play - hosts: lbserver roles: - role: haproxy - role: keepalived - hosts: appsrvs remote_user: root roles: - { role: nginx ,tags: [ 'nginx', 'web' ] ,when: ansible_distribution_major_version == "6" } - { role: httpd ,tags: [ 'httpd', 'web' ] } - { role: mysql ,tags: [ 'mysql', 'db' ] } - role: mariadb tags: - mariadb - db tags: app #play的tag [root@ansible ~]#ansible-playbook --tags="nginx,mysql" app-role.yml

浙公网安备 33010602011771号