4.9 template模板

模板是一个文本文件,可以做为生成文件的模板,并且模板文件中还可嵌套jinja用法

4.9.1 jiaja2语言

jinja2语言使用字面,有下面形成
字符串:使用单引号或双引号
数字:整数,浮点数
列表:[item1 ,item2 …]
元组:{itm1,item2…}
字典:{key1:value,key2:value2,…}
布尔型:true/false
算术运算:+,-,/,//,%,%,**
比较操作:==,!=,>,<,>=,<=
逻辑运算:and,or,not
流表达式:For,if,When
jinja2相关

字面量:

表达最简答的形式就是字面量,字面量表示诸如字符和数字的Python对象,如“Hello World”
双引号和单引号中间的一切都是字符串,无论何时你需要在模板中使用一个字符串,(比如函数调用,过滤器或只是包含或继承一个模板的参数),如42,42.23
数值可以为整数和浮点型,如果有小数点,则为整数,在Python里,42和42.0是不一样的

算术运算

jinja允许用计算值,支持下面的运算符
+:把两个对象加载一起,通常对象是素质,但是如果两则是字符串或者列表,你可以用这种方式来衔接它们,无论如何这不是首选的连接字符串的方式!连接字符串见~运算符。{{ 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

4.9.2 template

template功能:可以根据和参考模块文件,动态生成类似的配置文件
template文件必须存放于template目录下,且命名为,j2结尾
yaml/yml 文件需和template目录平级,目录结构如下

jinja2的网站:
https://jinja.palletsprojects.com/en/3.0.x/

————————————

[root@hdss7-11 ansible]# cat templnginx.yml
---
- hosts: websrvsremote_user: roottasks:- name: install nginxyum: name=nginx- name: template config to remote hoststemplate: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf- name: start serviceservice: name=nginx state=started enabled=yes
[root@hdss7-11 ansible]# dnf install nginx -y
[root@hdss7-11 ansible]# ansible all -a 'rpm -q httpd'
卸载httpd
[root@hdss7-11 ansible]# ansible all -m yum -a 'name=httpd state=absent'
[root@hdss7-11 ansible]# mkdir templates
[root@hdss7-11 ansible]# cp /etc/nginx/nginx.conf templ
templates/      templnginx.yml
[root@hdss7-11 ansible]# cp /etc/nginx/nginx.conf templates/nginx.conf.j2
[root@hdss7-11 ansible]# vim templates/nginx.conf.j2
user nginx;
worker_processes 6;     ##改为6
error_log /var/log/nginx/error.log;
然测试下配置文件是否有语法错误
[root@hdss7-11 ansible]# ansible-playbook -C templnginx.yml
[root@hdss7-11 ansible]# ansible-playbook templnginx.yml --limit=10.4.7.22
检查下是否正常,是否有6的nginx的进程
[root@hdss7-11 ansible]# ansible 10.4.7.22 -a 'pstree'


我们也可以让模板参与cpu格式让它进行加减乘除

——————————

首先我们去22上看下cpu的格式
[root@node2 ~]# lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    1
Core(s) per socket:    2
Socket(s):             2
NUMA node(s):          1
然后修改模板
[root@hdss7-11 ansible]# vim templates/nginx.conf.j2user nginx;
worker_processes {{ ansible_processor_vcpus**3 }};   #让它进行计算
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
然后增加触发启动的配置
[root@hdss7-11 ansible]# cat templnginx.yml
---
- hosts: websrvsremote_user: roottasks:- name: install nginxyum: name=nginx- name: template config to remote hoststemplate: src=nginx.conf.j2 dest=/etc/nginx/nginx.confnotify: restart service- name: start serviceservice: name=nginx state=started enabled=yeshandlers:- name: restart serviceservice: name=nginx state=restarted
测试是成功
[root@hdss7-11 ansible]# ansible-playbook  templnginx.yml  --limit=10.4.7.22
[root@hdss7-11 ansible]# ansible 10.4.7.22 -a 'pstree'
因为我的是双核双线程的所以变成了64

4.9.3 template 中使用流程控制for和if

template中可以使用流程控制for循环和if条件判断,实现动态生成文件功能
范例
定义一个特殊的元素是一个字典

范例
定义多个元素,有几个元素执行几次



说明:我们现在创建一个nginx的模板文件叫temnginx2.yml,然后它调用了模板文件nginx.conf2,j2,它引用了循环,而这个循环的个数是有yml文件决定的,yml里面有三个元素也就是意味着三次循环,也就意味着会生成三个语句块server–listen。。。最后的配置文件就成我们想要的了。比手工创建快吧

[root@hdss7-11 ansible]# cat templnginx2.yml
---
- hosts: websrvsremote_user: rootvars:nginx_vhosts:- 81- 82- 83tasks:- name: template configtemplate: src=nginx.conf2.j2 dest=/data/nginx.conf
[root@hdss7-11 ansible]# cat templates/nginx.conf2.j2
{% for vhost in nginx_vhosts %}
server {listen {{ vhost }}
}
{% endfor %}
[root@hdss7-11 ansible]# ansible-playbook -C templnginx2.yml --limit 10.4.7.22PLAY [websrvs] **********************************************************************************************************************************************TASK [Gathering Facts] **************************************************************************************************************************************
ok: [10.4.7.22]TASK [template config] **************************************************************************************************************************************
changed: [10.4.7.22]PLAY RECAP **************************************************************************************************************************************************
10.4.7.22                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0[root@hdss7-11 ansible]# ansible-playbook templnginx2.yml --limit 10.4.7.22      ##在这里我遇到一个因为少了s耽误时间的事PLAY [websrvs] **********************************************************************************************************************************************TASK [Gathering Facts] **************************************************************************************************************************************
ok: [10.4.7.22]TASK [template config] **************************************************************************************************************************************
changed: [10.4.7.22]PLAY RECAP **************************************************************************************************************************************************
10.4.7.22                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
[root@hdss7-11 ansible]# ansible 10.4.7.22 -a "cat /data/nginx.conf"
10.4.7.22 | CHANGED | rc=0 >>
server {listen 81
}
server {listen 82
}
server {listen 83
}

————————————
利用字典来实现调用的循环的列子

[root@hdss7-11 ansible]# cat templnginx3.yml
---
- hosts: websrvsremote_user: rootvars:nginx_vhosts:- listen: 8080tasks:- name: template filetemplate: src=nginx.conf3.j2 dest=/data/nginx3.conf
[root@hdss7-11 ansible]# cat templates/nginx.conf3.j2
{% for vhost in nginx_vhosts %}
server {listen {{ vhost.listen }}
}
{% endfor %}
[root@hdss7-11 ansible]# ansible-playbook templnginx3.yml --limit 10.4.7.22
[root@hdss7-11 ansible]# ansible 10.4.7.22 -a 'cat /data/nginx3.conf'
10.4.7.22 | CHANGED | rc=0 >>
server {listen 8080
}

范例
字典用多个key value值的



————————————

[root@hdss7-11 ansible]# cat templnginx4.yml
---
- hosts: websrvsremote_user: rootvars:nginx_vhosts:- listen: 8080server_name: "web1.magedu.com"root: "/var/www/nginx/web1/"- listen: 8081server_name: "web2.magedu.com"root: "/var/www/nginx/web2/"- listen: 8082server_name: "web3.magedu.com"root: "/var/www/nginx/web3/"tasks:- name: template configtemplate: src=nginx.conf4.j2 dest=/data/nginx4.conf
[root@hdss7-11 ansible]# cat templates/nginx.conf4.j2
{% for vhost in nginx_vhosts %}
server {listen {{ vhost.listen }}server_name {{ vhost.server_name }}root {{ vhost.root }}
}
{% endfor %}
[root@hdss7-11 ansible]# ansible-playbook  templnginx4.yml --limit 10.4.7.22
[root@hdss7-11 ansible]# ansible 10.4.7.22 -a 'cat /data/nginx4.conf'
10.4.7.22 | CHANGED | rc=0 >>
server {listen 8080server_name web1.magedu.comroot /var/www/nginx/web1/
}
server {listen 8081server_name web2.magedu.comroot /var/www/nginx/web2/
}
server {listen 8082server_name web3.magedu.comroot /var/www/nginx/web3/
}

范例:
在模板文件中还可以使用if条件判断,决定是否生成相关的配置信息
下面的web1,web2和web3相当于是一个空值键可以省略不写


————————————
主要用于有的小公司,一个物理机上搭建上百个小网站,快速搭建小网站用

[root@hdss7-11 ansible]# cat templnginx5.yml
---
- hosts: websrvsremote_user: rootvars:nginx_vhosts:- web1:listen: 8080root: "/var/www/nginx/web1/"- web2:listen: 8080server_name: "web2.dong.com"root: "/var/www/nginx/web2/"- web3:listen: 8080server_name: "web3.dong.com"root: "/var/www/nginx/web3/"tasks:- name: template configtemplate: src=nginx.conf5.j2 dest=/data/nginx5.conf
[root@hdss7-11 ansible]# cat templates/nginx.conf5.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 %}
[root@hdss7-11 ansible]# ansible-playbook templnginx5.yml --limit 10.4.7.22
[root@hdss7-11 ansible]# ansible 10.4.7.22 -a 'cat /data/nginx5.conf'
10.4.7.22 | CHANGED | rc=0 >>
server {listen 8080root /var/www/nginx/web1/
}
server {listen 8080server_name web2.dong.comroot /var/www/nginx/web2/
}
server {listen 8080server_name web3.dong.comroot /var/www/nginx/web3/
}

4.10 playbook使用when

when语句,可以实现条件测试,如果需要根据变量,facts或此前任务的执行结果来做为某个task执行与否的前提时要用条件测试,通过在task后添加when子语句即使用条件测试,jinja2的语法格式
范例

范例

范例

安装的时候用when,,需要针对不同的版本

[root@hdss7-11 ansible]# cat when.yml
---
- hosts: appsrvstasks:- name: install mysqlyum: name=mysql-serverwhen: ansible_distribution_major_version == "6"- name: install mariadbyum: name=mariadb-serverwhen: ansible_distribution_major_version == "7"

这里遇到一个小问题,centos6.6配置yum仓库总是报错


解决版本。配置yum仓库

[root@dong etc]# mkdir /media/CentOS
[root@dong etc]# mount /dev/cdrom /media/CentOS
[root@dong etc]# pwd
/etc
[root@dong etc]# mv yum.repos.d yum.repos.d.bak
[root@dong etc]# cp yum.repos.d.bak/CentOS-Base.repo yum.repos.d/CentOS-Base.repo.bak
[root@dong etc]# cd yum.repos.d
[root@dong yum.repos.d]# cat local.repo
[base]
name=CentOS6.6
baseurl=file:///media/CentOS
enabled=1
gpgcheck=0
[root@dong yum.repos.d]# ll
总用量 8
-rw-r--r--. 1 root root 1991 8月  17 06:53 CentOS-Base.repo.bak
-rw-r--r--. 1 root root   72 8月  17 07:02 local.repo
然后就可以yum -y install mysql-server 了

执行ansible的when

 ansible-playbook when.yml注意呀 下面的这个报错很可能是网络有问题,去检查下21上的/etc/resolv.conf文件是否有网关能否通百度

搞通网络重新执行完毕后可以去25上执行 rpm -qi mysql-server[root@dong yum.repos.d]# service mysqld start
正在启动 mysqld:                                          [确定]
[root@dong yum.repos.d]# mysql -uroot
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.1.73 Source distribution
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
可以去21上执行
[root@node1 ~]# rpm -qi mariadb-server
[root@hdss7-11 yum.repos.d]# systemctl start  mariadb
[root@hdss7-11 yum.repos.d]# systemctl status  mariadb
● mariadb.service - MariaDB database serverLoaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled; vendor preset: disabled)Active: active (running) since 三 2021-08-18 22:00:21 CST; 5s agoProcess: 47622 ExecStartPost=/usr/libexec/mariadb-wait-ready $MAINPID (code=exited, status=0/SUCCESS)Process: 47538 ExecStartPre=/usr/libexec/mariadb-prepare-db-dir %n (code=exited, status=0/SUCCESS)Main PID: 47621 (mysqld_safe)Tasks: 20Memory: 101.9MCGroup: /system.slice/mariadb.service├─47621 /bin/sh /usr/bin/mysqld_safe --basedir=/usr└─47786 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-error=/var/log/mariadb/mariadb.log --pid-file=/var/run/mariadb/mariadb.pid --socket...8月 18 22:00:19 hdss7-11.host.com mariadb-prepare-db-dir[47538]: MySQL manual for more instructions.
8月 18 22:00:19 hdss7-11.host.com mariadb-prepare-db-dir[47538]: Please report any problems at http://mariadb.org/jira
8月 18 22:00:19 hdss7-11.host.com mariadb-prepare-db-dir[47538]: The latest information about MariaDB is available at http://mariadb.org/.
8月 18 22:00:19 hdss7-11.host.com mariadb-prepare-db-dir[47538]: You can find additional information about the MySQL part at:
8月 18 22:00:19 hdss7-11.host.com mariadb-prepare-db-dir[47538]: http://dev.mysql.com
8月 18 22:00:19 hdss7-11.host.com mariadb-prepare-db-dir[47538]: Consider joining MariaDB's strong and vibrant community:
8月 18 22:00:19 hdss7-11.host.com mariadb-prepare-db-dir[47538]: https://mariadb.org/get-involved/
8月 18 22:00:19 hdss7-11.host.com mysqld_safe[47621]: 210818 22:00:19 mysqld_safe Logging to '/var/log/mariadb/mariadb.log'.
8月 18 22:00:19 hdss7-11.host.com mysqld_safe[47621]: 210818 22:00:19 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
8月 18 22:00:21 hdss7-11.host.com systemd[1]: Started MariaDB database server.
[root@hdss7-11 yum.repos.d]# mariadb -uroot
bash: mariadb: 未找到命令...
[root@hdss7-11 yum.repos.d]# mariadb
bash: mariadb: 未找到命令...
[root@hdss7-11 yum.repos.d]# mysql -uroot
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 5.5.68-MariaDB MariaDB ServerCopyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.MariaDB [(none)]> exit

运维自动化之----ansible中play的高级用法模板(7)相关推荐

  1. 运维自动化之ANSIBLE

    成功不易,加倍努力! 运维自动化之ANSIBLE 本章内容 1 自动化运维应用场景 1.1 云计算运维工程师核心职能 1.2 运维职业发展路线 1.3 企业实际应用场景分析 1.3.1 Dev开发环境 ...

  2. 第20章,运维自动化之ansible

    更多内容请点击: Linux学习从入门到打死也不放弃,完全笔记整理(持续更新,求收藏,求点赞~~~~) https://blog.51cto.com/13683480/2095439 第20章,运维自 ...

  3. 中国电信基于Mesos+Docker的运维自动化在CDN中的实践

    本文讲的是中国电信基于Mesos+Docker的运维自动化在CDN中的实践[编者的话]本次分享将讲解容器技术在CDN系统中的应用,包括应用的容器化,使用Mesos.Marathon.ZooKeeper ...

  4. 运维自动化之---ansilbe运维自动化和ansible架构介绍(1)

    运维自动化的发展历程 1.自动化运维应用场景 1.1云计算运维工程师核心职能 运维相关的工具 Podman是用来替代docker的工具 1.2 运维职业的发展路线 目标::一切皆自动化 1.3 企业实 ...

  5. 运维自动化之ansible,轻松实现企业级自动化运维

    Ansible是近年来越来越火的一款开源运维自动化工具,通过Ansible可以实现运维自动化,提高运维工程师的工作效率,减少人为失误. Ansible通过本身集成的非常丰富的模块可以实现各种管理任务, ...

  6. 运维自动化之Ansible 和 HTTP协议和APACHE

    云计算运维工程师核心职能 Linux运维工程师职能划分 企业实际应用场景分析 Dev开发环境 使用者:程序员 功能:程序员开发软件,测试BUG的环境 管理者:程序员 测试环境 使用者:QA测试工程师 ...

  7. 运维自动化工具-ansible的安装与ad-hoc模式场景应用

    使用 yum 安装 yum install epel-release -y yum install ansible –y 无论是yum安装还是pip安装,都会遇到各种意外的错误,主要是安装的时候依赖比 ...

  8. 3.2.1 运维自动化之ansible模块

    Ansible 原理 使用者使用Ansible或Ansible-playbooks时,在服务器终端输入Ansible的Ad-Hoc命令集或palybook后,Ansible会遵循预先编排的规则将Pla ...

  9. 运维自动化之ansible playbook安装apache

    上次介绍了如何使用ansible安装lnmp(地址是http://dl528888.blog.51cto.com/2382721/1440775),现在介绍如何使用ansible安装apache. 下 ...

最新文章

  1. codeforces708C
  2. 使用Sublime Text 3作为Python编辑器有关中文问题
  3. 使有用计算机不注意卫生,对您有用的与电脑清洁相关的知识
  4. POJ1724 ROADS 费用最短路
  5. Android自定义组合布局,Android 流式布局 + 自定义组合控件
  6. 计算机原理 逻辑单元,湘潭大学计算机原理 实验一 算术逻辑单元ALU实验报告
  7. C语言(CED)判断一个数是否是2的整数幂的简便方法!
  8. PyCharm 设置背景图片
  9. Android Studio(9)--添加应用资源
  10. java gzip 文件夹_Java GZip 基于磁盘实现压缩和解压的方法
  11. Spring源码之创建AOP代理(补)
  12. 手摸手-100行代码实现一个功能完善的图片懒加载
  13. IE8变成IE7的显示方式
  14. Python学习之——np.dot()与np.multiply()与*之间的区别
  15. SQL Server读写分离研究
  16. 图片从RGB转换成Lab
  17. python oserror捕获,Python3基础 try-指定except-as reason 捕获打开一个不存在的文件的时候,会产生OSError异常的示例...
  18. 股份制的起源—严谨版与趣味版
  19. emlog模板开发基础2022最新指南
  20. 《muduo网络库》学习笔记——时间轮Timeing wheel

热门文章

  1. [Delphi] 多线程编程
  2. 国际空间站ISS SSTV 2018 OCT
  3. 慢扫描电视 SSTV
  4. xmlhttp的实际使用
  5. Online Tools
  6. 适合后台管理系统开发的前端框架
  7. ExecutorUtil
  8. XML里的<![CDATA[<=]]>是什么意思?
  9. request 使用方法
  10. 赖大师新文章 :Xilinx 开箱-KV260相机,两个小时轻松搞定,文章不能用我坐飞机过去帮你调哈。