文章 92
评论 3
浏览 208687
运维自运化之ANSIBLE

运维自运化之ANSIBLE

一、Ansible 介绍和架构

公司计划在年底做一次大型市场促销活动,全面冲刺下交易额,为明年的上市做准备。公司要求各业务组对年底大促做准备,运维部要求所有业务容量进行三倍的扩容,并搭建出多套环境可以共开发和测试人员做测试,运维老大为了在年底有所表现,要求运维部门同学尽快实现,当你接到这个任务时,有没有更快的解决方案?

1.1 Ansible发展史

作者:Michael DeHaan( Cobbler 与 Func 作者)

ansible 的名称来自科幻小说《安德的游戏》中跨越时空的即时通信工具,使用它可以在相距数光年的距离,远程实时控制前线的舰队战斗2012-03-09,发布0.0.1版,2015-10-17,Red Hat宣布1.5亿美元收购

官网:https://www.ansible.com/

官方文档:https://docs.ansible.com/

1.2 Ansible 特性

  • 模块化:调用特定的模块完成特定任务,支持自定义模块,可使用任何编程语言写模块
  • Paramiko(python对ssh的实现),PyYAML,Jinja2(模板语言)三个关键模块
  • 基于Python语言实现
  • 部署简单,基于python和SSH(默认已安装),agentless,无需代理不依赖PKI(无需ssl)
  • 安全,基于OpenSSH
  • 幂等性:一个任务执行1遍和执行n遍效果一样,不因重复执行带来意外情况,此特性非绝对
  • 支持playbook编排任务,YAML格式,编排任务,支持丰富的数据结构
  • 较强大的多层解决方案 role

1.3 Ansible 架构

1.3.1 Ansible 组成

组合INVENTORY、API、MODULES、PLUGINS的绿框,为ansible命令工具,其为核心执行工具

clipboard

  • INVENTORY:Ansible管理主机的清单/etc/anaible/hosts
  • MODULES:Ansible执行命令的功能模块,多数为内置核心模块,也可自定义
  • PLUGINS:模块功能的补充,如连接类型插件、循环插件、变量插件、过滤插件等,该功能不常用
  • API:供第三方程序调用的应用程序编程接口

1.3.2 Ansible命令执行来源

  • USER 普通用户,即SYSTEM ADMINISTRATOR
  • PLAYBOOKS:任务剧本(任务集),编排定义Ansible任务集的配置文件,由Ansible顺序依次执行,通常是JSON格式的YML文件
  • CMDB(配置管理数据库) API 调用
  • PUBLIC/PRIVATE CLOUD API调用
  • USER-> Ansible Playbook -> Ansibile

1.3.3 注意事项

  • 执行ansible的主机一般称为管理端, 主控端,中控,master或堡垒机
  • 主控端Python版本需要2.6或以上
  • 被控端Python版本小于2.4,需要安装python-simplejson
  • 被控端如开启SELinux需要安装libselinux-python
  • windows 不能做为主控端

二、Ansible安装和入门

2.1 Ansible安装

ansible的安装方法有多种

官方文档:https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html

下载地址:https://releases.ansible.com/ansible

pip下载:https://pypi.org/project/ansible/

2.1.1 包安装方式

#ubuntu系统
[17:58:53 root@ubuntu ~]#apt install ansible
#centos系统
[17:58:53 root@centos ~]#yum install ansible

查看ansible版本

#ubuntu系统
[18:00:10 root@mysql-1 ~]#apt show ansible
#centos系统
[18:00:10 root@mysql-1 ~]#yum info ansible

2.1.2 编译安装

[18:02:02 root@mysql-1 ~]#apt install python
[18:02:19 root@mysql-1 ~]#wget https://releases.ansible.com/ansible/ansible-1.5.4.tar.gz
[18:02:35 root@mysql-1 ~]#tar xf ansible-1.5.4.tar.gz 
[18:05:16 root@mysql-1 ~]#python setup.py build
[18:05:16 root@mysql-1 ~]#python setup.py install
[18:05:16 root@mysql-1 ~]#mkdir /etc/ansible
[18:05:16 root@mysql-1 ~]#cp -r examples/* /etc/ansible/

2.1.3 pip安装

[18:09:02 root@mysql-1 ~]#apt install python-pip
[18:13:06 root@mysql-1 ~]#pip install ansible
[18:13:06 root@mysql-1 ~]#ansible --version

2.1.4 确认安装

[18:15:11 root@mysql-1 ~]#ansible --version 
[DEPRECATION WARNING]: Ansible will require Python 3.8 or newer on the controller 
starting with Ansible 2.12. Current version: 2.7.17 (default, Feb 27 2021, 
15:10:58) [GCC 7.5.0]. This feature will be removed from ansible-core in version 
2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in
 ansible.cfg.
ansible [core 2.11.2] 
  config file = None
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible
  ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/local/bin/ansible
  python version = 2.7.17 (default, Feb 27 2021, 15:10:58) [GCC 7.5.0]
  jinja version = 2.11.3
  libyaml = True

2.2 Ansible相关文件

2.2.1 配置文件

  • /etc/ansible/ansible.cfg 主配置文件,配置ansible工作特性
  • /etc/ansible/hosts 主机清单
  • /etc/ansible/roles/ 存放角色的目录

2.2.2 ansible主配置文件

Ansible 的配置文件 /etc/ansible/ansible.cfg ,其中大部分的配置内容无需进行修改

[defaults]
#inventory     = /etc/ansible/hosts # 主机列表配置文件
#library = /usr/share/my_modules/ # 库文件存放目录
#remote_tmp = $HOME/.ansible/tmp #临时py命令文件存放在远程主机目录
#local_tmp     = $HOME/.ansible/tmp # 本机的临时命令执行目录
#forks         = 5   # 默认并发数
#sudo_user     = root # 默认sudo 用户
#ask_sudo_pass = True #每次执行ansible命令是否询问ssh密码
#ask_pass     = True  
#remote_port   = 22
#host_key_checking = False # 检查对应服务器的host_key,建议取消注释
#log_path=/var/log/ansible.log #日志文件,建议启用
#module_name = command   #默认模块,可以修改为shell模块

2.2.3 inventory主机清单

ansible的主要功用在于批量主机操作,为了便捷地使用其中的部分主机,可以在inventory file中将其分组命名

默认的inventory file为 /etc/ansible/hosts

inventory file可以有多个,且也可以通过Dynamic Inventory来动态生成

官方文档:https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html

主机清单文件格式

inventory文件遵循INI文件风格,中括号中的字符为组名。可以将同一个主机同时归并到多个不同的组中此外,当如若目标主机使用了非默认的SSH端口,还可以在主机名称之后使用冒号加端口号来标明如果主机名称遵循相似的命名模式,还可以使用列表的方式标识各主机

范例:

ntp.magedu.com
[webservers]
www1.zhnagzhuo.com:2222
www2.zhnagzhuo.com

#www.1-100.example.com的主机
[websrvs]
www[1:100].example.com

#10.0.0.1-100的主机
[appsrvs]
10.0.0.[1:100]

[test]
10.0.0.8  ansible_connection=local   #指定本地连接,无需ssh配置

#ansible_connection=ssh 需要在/etc/ssh/ssh_config配置中添加StrictHostKeyChecking no
10.0.0.7  ansible_connection=ssh   ansible_port=2222  ansible_user=wang ansible_password=magedu  
10.0.0.6  ansible_connection=ssh   ansible_user=root  ansible_password=123456

2.3 Ansible相关工具

  • /usr/bin/ansible 主程序,临时命令执行工具
  • /usr/bin/ansible-doc 查看配置文档,模块功能查看工具,相当于man
  • /usr/bin/ansible-playbook 定制自动化任务,编排剧本工具,相当于脚本
  • /usr/bin/ansible-pull 远程执行命令的工具
  • /usr/bin/ansible-vault 文件加密工具
  • /usr/bin/ansible-console 基于Console界面与用户交互的执行工具
  • /usr/bin/ansible-galaxy 下载/上传优秀代码或Roles模块的官网平台

利用ansible实现管理的主要方式:

  • Ad-Hoc 即利用ansible命令,主要用于临时命令使用场景
  • Ansible-playbook 主要用于长期规划好的,大型项目的场景,需要有前期的规划过程

2.3.1 ansible-doc

此工具用来显示模块帮助,相当于man

#格式
ansible-doc [options] [module...]
-l --list   #列出可用模块
-s, --snippet #显示指定模块的playbook片段

#范例
#列出所有模块
[18:38:21 root@mysql-1 ~]#ansible-doc -l
#查看指定模块帮助用法
[18:38:53 root@mysql-1 ~]#ansible-doc ping
#查看指定模块帮助用法
[18:38:53 root@mysql-1 ~]#ansible-doc -s ping

2.3.2 ansible

此工具通过ssh协议,实现远程主机的配置管理、应用部署、任务执行等功能

建议:使用此工具前,先配置ansible主控端能基于密钥认证的方式联系各个被管理节点

范例:利用sshpass批量实现基于key验证脚本1

IP="
192.168.10.81
192.168.10.82
192.168.10.71
"

rpm -q sshpass &>/dev/null || yum -y install sshpass

[ -f /root/.ssh/id_rsa ] || ssh-keygen -f /root/.ssh/id_rsa -P ''
export SSHPASS=123456

for HOST in $IP;do
     sshpass -e ssh-copy-id -o StrictHostKeyChecking=no $HOST
done

命令格式参数

--version    #显示版本
-m module    #指定模块,默认为command
-v           #详细过程 –vv -vvv更详细
--list-hosts #显示主机列表,可简写 --list
-C, --check  #检查,并不执行
-T, --timeout=TIMEOUT  #执行命令的超时时间,默认10s
-k, --ask-pass         #提示输入ssh连接密码,默认Key验证
-u, --user=REMOTE_USER #执行远程执行的用户,默认root
-b, --become           #代替旧版的sudo 切换
--become-user=USERNAME #指定sudo的runas用户,默认为root
-K, --ask-become-pass  #提示输入sudo时的口令

2.3.2.1 ansible的主机清单匹配

用于匹配被控制的主机的列表

All :表示所有Inventory中的所有主机

ansible all –m ping

*:通配符

[13:49:52 root@ansible ~]#ansible -m ping "*"
[13:51:10 root@ansible ~]#ansible -m ping "web*"
[13:51:23 root@ansible ~]#ansible -m ping "192.168.10.*"
[13:51:30 root@ansible ~]#ansible -m ping "192.168.10.181 192.168.10.182"

或关系

[13:53:39 root@ansible ~]#ansible "web1:web2" -m ping
[13:53:45 root@ansible ~]#ansible "192.168.10.181:192.168.10.182" -m ping

逻辑与

#属于web1组由属于web组的主机
[13:55:16 root@ansible ~]#ansible "web1:&web" -m ping

逻辑非

#在web组,但不在web1组的主机
#这里必须使用单引号
[13:57:03 root@ansible ~]#ansible 'web:!web1' -m ping

综合逻辑

[13:58:37 root@ansible ~]#ansible 'web1:web2:&web:!web1' -m ping

正则表达式

[14:00:00 root@ansible ~]#ansible "~web(1|2)" -m ping
[14:00:00 root@ansible ~]#ansible "~192\.168\.10\.18(1|2)" -m ping

查看匹配到的主机

[14:00:47 root@ansible ~]#ansible "~192\.168\.10\.18(1|2)" --list-hosts
  hosts (2):
    192.168.10.182
    192.168.10.181

2.3.2.2 ansible的执行状态

  1. 加载自己的配置文件,默认/etc/ansible/ansible.cfg
  2. 加载自己对应的模块文件,如:command
  3. 通过过ansible将模块或命令生成对应的临时py文件,并将该文件传输至远程服务器的对应执行用户 $HOME/.ansible/tmp/ansible-tmp-数字/XXX.PY文件
  4. 给文件+x执行权限
  5. 执行并返回结果
  6. 删除临时py文件,退出

2.3.2.3 ansible的执行状态

[14:06:26 root@ansible ~]#grep -A 15 'colors' /etc/ansible/ansible.cfg
[colors]
#highlight = white
#verbose = blue
#warn = bright purple
#error = red
#debug = dark gray
#deprecate = purple
#skip = cyan
#unreachable = red
#ok = green
#changed = yellow
#diff_add = green
#diff_remove = red
#diff_lines = cyan
  • 绿色:执行成功并且不需要做出改变的操作
  • 黄色:执行成功并且对目标主机做变更
  • 红色:执行失败

2.3.2.4 ansible使用范例

#以wang用户执行ping存活检测
[14:09:05 root@ansible ~]#ansible all -m ping -u wang -k
#以wang sudo至root执行ping存活检测
[14:09:20 root@ansible ~]#ansible all -m ping -u wang -k -b
#以wang sudo至mage用户执行ping存活检测
[14:11:29 root@ansible ~]#ansible all -m ping -u wang -k -b --become-user=mage
#以wang sudo至root用户执行ls 
[14:29:17 root@ansible ~]#ansible all -m command -u wang -a 'ls /root' -b --become-user=root -k -K

2.3.3 ansible-console

此工具可交互执行命令,支持tab,ansible 2.0+新增

提示符格式:

执行用户@当前操作的主机组 (当前组的主机数量)[f:并发数]$
[14:30:08 root@ansible ~]#ansible-console 
root@all (2)[f:5]$

常用子命令

  • 设置并发数: forks n 例如: forks 10
  • 切换组: cd 主机组 例如: cd web
  • 列出当前组主机列表: list
  • 列出所有的内置命令: ?或help

2.3.4 ansible-playbook

此工具用于执行编写好的 playbook 任务

范例:

[14:36:03 root@ansible hello]#cat ansible-playbook-hello.yaml
---
- hosts: web
  remote_user: root
  gather_facts: on
  
  tasks:
    - name: hello world
      command: /usr/bin/wall hello world
#执行
[14:37:00 root@ansible hello]#ansible-playbook hello.yaml

2.3.5 ansible-vault

此工具可以用于加密解密yml文件

格式

ansible-vault [create|decrypt|edit|encrypt|rekey|view]

范例:

#加密
[14:37:00 root@ansible hello]#ansible-vault encrypt hello.yaml
#解密
[14:38:55 root@ansible hello]#ansible-vault decrypt hello.yaml
#查看加密文件
[14:39:27 root@ansible hello]#ansible-vault view hello.yaml
#编辑加密文件
[14:39:55 root@ansible hello]#ansible-vault edit hello.yaml
#修改口令
[14:40:48 root@ansible hello]#ansible-vault rekey hello.yaml
#创建新文件
[14:41:50 root@ansible hello]#ansible-vault create new.yaml

2.3.6 ansible-galaxy

此工具会连接 https://galaxy.ansible.com 下载相应的roles

范例:

#列出所有已安装的galaxy
[14:42:44 root@ansible hello]#ansible-galaxy list
#安装galaxy
[14:44:51 root@ansible hello]#ansible-galaxy install geerlingguy.mysql
[14:44:51 root@ansible hello]#ansible-galaxy install geerlingguy.redis
#删除galaxy
[14:45:44 root@ansible hello]#ansible-galaxy remove geerlingguy.redis

2.4 Ansible常用模块

2015年底270多个模块,2016年达到540个,2018年01月12日有1378个模块,2018年07月15日1852 个模块,2019年05月25日(ansible 2.7.10)时2080个模块,2020年03月02日有3387个模块

虽然模块众多,但最常用的模块也就2,30个而已,针对特定业务只用10几个模块

常用模块帮助文档参考:

https://docs.ansible.com/ansible/2.9/modules/modules_by_category.html

2.4.1 Command模块

功能:在远程主机执行命令,此为默认模块,可忽略-m选项

注意:此命令不支持 $VARNAME < > | ; & 等,可以用shell模块实现

注意:此模块不具有幂等性

范例:

[14:49:58 root@ansible ~]#ansible web -m command -a 'chdir=/etc cat os-release'
[14:52:32 root@ansible ~]#ansible web -m command -a 'chdir=/root ls -la'

chdir #为执行命令的目录,也就是工作目录

2.4.2 Shell模块

功能:和command相似,用shell执行命令,支持各种符号,比如:*,$, >

注意:此模块不具有幂等性

范例:

[15:03:21 root@ansible ~]#ansible web -m shell -a 'chdir=/tmp pwd'
192.168.10.181 | SUCCESS | rc=0 >>
/tmp
192.168.10.182 | SUCCESS | rc=0 >>
/tmp
[15:03:56 root@ansible ~]#ansible web -m shell -a 'chdir=/tmp mkdir zhangzhuo'
[15:04:21 root@ansible ~]#ansible web -m shell -a 'chdir=/tmp echo $PATH>zhangzhuo/1.txt'
[15:05:58 root@ansible ~]#ansible web -m shell -a 'chdir=/tmp cat zhangzhuo/1.txt'

chdir #为执行命令的目录,也就是工作目录
connection #

注意:调用bash执行命令 类似 cat /tmp/test.md | awk -F'|' '{print $1,$2}' &> /tmp/example.txt 这些复杂命令,即使使用shell也可能会失败,解决办法:写到脚本时,copy到远程,执行,再把需要的结果拉回执行命令的机器

范例:将shell模块代替command,设为模块

[15:07:18 root@ansible ~]#cat /etc/ansible/ansible.cfg | grep module
module_name = shell
#测试
[15:08:11 root@ansible ~]#ansible all -a 'chdir=/etc ls'

2.4.3 Script模块

功能:在远程主机上运行ansible服务器上的脚本(无需执行权限)

注意:此模块不具有幂等性

范例:

[15:09:34 root@ansible ~]#cat 1.sh 
#!/bin/bash
echo zhangzhuo >1.txt
cat 1.txt
#测试
[15:09:38 root@ansible ~]#ansible all -m script -a 1.sh 
192.168.10.181 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.10.181 closed.\r\n", 
    "stdout": "zhangzhuo\r\n", 
    "stdout_lines": [
        "zhangzhuo"
    ]
}
192.168.10.182 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.10.182 closed.\r\n", 
    "stdout": "zhangzhuo\r\n", 
    "stdout_lines": [
        "zhangzhuo"
    ]
}

重要参数

chdir   #脚本执行目录

2.4.4 Copy模块

功能:从ansible服务器主控端复制文件到远程主机

#如目标存在,默认覆盖,此处指定先备份
[15:10:20 root@ansible ~]#ansible all -m copy -a 'src=/root/1.txt dest=/root/1.txt owner=zhang mode=600 backup=yes'

#指定内容,直接生成目标文件 
[15:14:18 root@ansible ~]#ansible all -m copy -a 'content="test line1\ntest line2" dest=/root/1.txt'

#复制/etc目录自身,注意/etc/后面没有/
[15:15:24 root@ansible ~]#ansible all -m copy -a 'src=/etc dest=/root/backup'

#复制/etc/下的文件,不包括/etc/目录自身,注意/etc/后面有/
[15:31:16 root@ansible ~]#ansible all -m copy -a 'src=/etc/ dest=/root/backup'

参数介绍

src  #复制目标文件或目录位置
dest #复制到目的的位置
content #生成文件
owner  #复制到目的地的文件所有者与所有组
mode   #复制到目的地的文件权限
backup #文件存在是否备份

2.4.5 Fetch模块

功能:从远程主机提取文件至ansible的主控端,copy相反,目前不支持目录

范例:

[15:32:22 root@ansible ~]#ansible all -m fetch -a 'src=/etc/fstab dest=/root/os'
[15:32:59 root@ansible ~]#tree os
os
├── 192.168.10.181
│   └── etc
│       └── fstab
└── 192.168.10.182
    └── etc
        └── fstab

2.4.6 File模块

功能:设置文件属性,创建软链接等

范例:

#创建空文件
[15:33:03 root@ansible ~]#ansible all -m file -a 'path=/root/1.txt state=touch'
[15:35:00 root@ansible ~]#ansible all -m file -a 'path=/root/2.txt state=absent'
[15:37:19 root@ansible ~]#ansible all -m file -a 'path=/root/2.txt state=touch owner=zhang mode=755'

#创建目录
[15:38:09 root@ansible ~]#ansible all -m file -a 'path=/root/zhang state=directory'

#创建软连接
[15:38:13 root@ansible ~]#ansible all -m file -a 'src=/root/zhang path=/root/zhang1 state=link'

#递归修改目录属性
[15:41:26 root@ansible ~]#ansible all -m file -a 'path=/root/zhang state=directory owner=zhang group=zhang recurse=yes'

参数选项

path  #目标文件或目录位置
state #文件的类型 touch:创建普通文件 directory:目录 link:软连接 
owner #所属用户
group #所属组
mode  #文件权限
recurse #递归操作

2.4.7 unarchive 模块

功能:解包解压缩 实现有两种用法:

  1. 将ansible主机上的压缩包传到远程主机后解压缩至特定目录,设置copy=yes
  2. 将远程主机上的某个压缩包解压缩到指定路径下,设置copy=no

常见参数

copy #默认为yes,当copy=yes,拷贝的文件是从ansible主机复制到远程主机上,如果设置为copy=no,会在远程主机上寻找src源文件

remote_src #和copy功能一样且互斥,yes表示在远程主机,不在ansible主机,no表示文件在ansible主机上

src #源路径,可以是ansible主机上的路径,也可以是远程主机(被管理端或者第三方主机)上的路径,如果是远程主机上的路径,则需要设置copy=no

dest #远程主机上的目标路径
mode #设置解压缩后的文件权限
remote_src #压缩包是否从远程下载

范例

#压缩包在本机
[15:49:15 root@ansible ~]#ansible all -m unarchive -a 'src=/root/etc.tar.gz dest=/root owner=zhang group=bin'

#压缩包在对方
[15:52:39 root@ansible ~]#ansible all -m unarchive -a 'src=/root/etc.tar.gz dest=/root owner=zhang group=bin copy=no mode=777'

#可以从远程服务器下载
[15:56:20 root@ansible ~]#ansible all -m unarchive -a 'src=http://nginx.org/download/nginx-1.18.0.tar.gz dest=/root remote_src=yes'

2.4.8 Archive模块

功能:打包压缩保存在被管理节点

范例

[15:59:10 root@ansible ~]#ansible all -m archive -a 'path=/var/log dest=/root/log.tar.gz format=gz'
[15:59:27 root@ubuntu18-04 ~]#ls
log.tar.gz

2.4.9 Hostname模块

功能:管理主机名

范例

[15:59:24 root@ansible ~]#ansible web1 -m hostname -a 'name=web1.zhangzhuo.org'
[16:00:50 root@web1 ~]#ansible web2 -m hostname -a 'name=web2.zhangzhuo.org'

2.4.10 Cron模块

功能:计划任务

支持时间:minute,hour,day,month,weekday

范例

[16:05:01 root@web1 ~]#cat hostname.sh 
#!/bin/bash
echo "`date` `hostname`" > /root/log
#创建任务
[16:05:07 root@web1 ~]#ansible all -m cron -a 'hour=2 minute=30 weekday=1-5 name="log" job=/root/hostname.sh'
[16:06:56 root@web1 ~]#ansible all -m cron -a 'minute=*/1 weekday=1-5 name="log" job=/root/hostname.sh'

#禁用计划任务
[16:17:07 root@web1 ~]#ansible all -m cron -a 'minute=*/1 weekday=1-5 name="log" job=/root/hostname.sh disabled=yes'

#启用计划任务
[16:17:30 root@web1 ~]#ansible all -m cron -a 'minute=*/1 weekday=1-5 name="log" job=/root/hostname.sh disabled=no'

#删除任务
[16:17:56 root@web1 ~]#ansible all -m cron -a 'name=log state=absent'

2.4.11 Yum和Apt模块

功能:

  • yum 管理软件包,只支持RHEL,CentOS,fedora,不支持Ubuntu其它版本
  • apt 模块管理 Debian 相关版本的软件包

范例

#安装
[16:20:36 root@web1 ~]#ansible all -m apt -a 'name=apache2 state=present'
#卸载
[16:22:36 root@web1 ~]#ansible all -m apt -a 'name=apache2 state=absent'
#多个包使用,隔开

2.4.12 Service模块

功能:管理服务

范例

#启动服务并且设置开机自启
[16:25:39 root@web1 ~]#ansible web1 -m service -a 'name=apache2 state=started enabled=yes'

#停止服务
[16:26:58 root@web1 ~]#ansible web2 -m service -a 'name=apache2 state=stopped'

#重启
[16:27:54 root@web1 ~]#ansible web2 -m service -a 'name=apache2 state=restarted'

2.4.13 User模块

功能:管理用户

范例

#创建用户
[16:30:24 root@web1 ~]#ansible web2 -m user -a 'name=cy comment="test cy" uid=2020 home=/home/cy group=root'

[16:35:09 root@web1 ~]#ansible web2 -m user -a 'name=nginx comment="nginx" uid=88 group=nginx group=root shell=/sbin/nologin system=yes create_home=no home=/data/nginx non_unique=yes'

#删除用户,remove=yes表示删除用户及家目录等数据
[16:36:46 root@web1 ~]#ansible web2 -m user -a 'name=cy state=absent remove=yes'

参数说明

name  #用户名称
comment #用户说明
uid  #用户uid
group #用户主组
groups #用户附加组
shell  #用户默认使用那个shell
system  #是否是系统用户
create_home #是否创建家目录
home #家目录位置
remove #删除用户时,把用户相关目录也删除

2.4.14 Group 模块

功能:管理组

范例

#创建组
[16:36:54 root@web1 ~]#ansible web2 -m group -a 'name=nginx gid=88 system=yes'
#删除组
[16:38:52 root@web1 ~]#ansible web2 -m group -a 'name=nginx state=absent'

2.4.15 lineinfile模块

ansible在使用sed进行替换时,经常会遇到需要转义的问题,而且ansible在遇到特殊符号进行替换时, 存在问题,无法正常进行替换 。其实在ansible自身提供了两个模块:lineinfile模块和replace模块,可以方便的进行替换

一般在ansible当中去修改某个文件的单行进行替换的时候需要使用lineinfile模块

regexp参数 :使用正则表达式匹配对应的行,当替换文本时,如果有多行文本都能被匹配,则只有最后面被匹配到的那行文本才会被替换,当删除文本时,如果有多行文本都能被匹配,这么这些行都会被删除。

如果想进行多行匹配进行替换需要使用replace模块

范例

#替换内容,只替换匹配到的最后一行
[16:44:47 root@web1 ~]#ansible web2 -m lineinfile -a 'path=/root/passwd regexp="root" line="zhangzhuo"'
#替换的是整行内容
[16:47:07 root@web2 ~]#diff passwd passwd-1 
1c1
< zhangzhuo
---
> root:x:0:0:root:/root:/bin/bash

#删除行内容,匹配到的行全部删除
[16:46:39 root@web1 ~]#ansible web2 -m lineinfile -a 'dest=/root/fstab state=absent regexp="^#"'

2.4.16 replace模块

该模块有点类似于sed命令,主要也是基于正则进行匹配和替换,建议使用

范例

[16:51:32 root@web1 ~]#ansible web2 -m replace -a 'path=/root/passwd regexp="^bin(.*)" replace="zhangzhuo-cy\1"'
[16:54:23 root@web1 ~]#ansible web2 -m replace -a 'path=/root/fstab regexp="^(\/swap\.img.*)" replace="#\1"'

2.4.17 setup模块

功能: setup 模块来收集主机的系统信息,这些 facts 信息可以直接以变量的形式使用,但是如果主机较多,会影响执行速度,可以使用 gather_facts: no 来禁止 Ansible 收集 facts 信息

范例

#列出所有信息
[16:56:52 root@web1 ~]#ansible web1 -m setup
#列出特定的信息
[16:56:52 root@web1 ~]#ansible web1 -m setup -a "filter=ansible_nodename"

取IP地址

[17:00:17 root@web1 ~]#ansible all -m setup -a 'filter=ansible_all_ipv4_addresses'
192.168.10.181 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.10.181"
        ]
    }, 
    "changed": false
}
192.168.10.182 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.10.182"
        ]
    }, 
    "changed": false
}

2.4.18 debug模块

此模块可以输出信息

范例

[17:08:39 root@web1 ansible]#cat debug/debug.yaml 
---
- hosts: all
  tasks:
    - name: output
      debug: 
      var: 变量名称     #s
#默认没有指定msg,默认输出"Hello world!"  
[17:08:41 root@web1 ansible]#ansible-playbook debug/debug.yaml 

PLAY [all] *************************************************************************

TASK [Gathering Facts] *************************************************************
ok: [192.168.10.181]
ok: [192.168.10.182]

TASK [output] **********************************************************************
ok: [192.168.10.182] => {
    "msg": "Hello world!"
}
ok: [192.168.10.181] => {
    "msg": "Hello world!"
}

PLAY RECAP *************************************************************************
192.168.10.181             : ok=2    changed=0    unreachable=0    failed=0   
192.168.10.182             : ok=2    changed=0    unreachable=0    failed=0

利用debug模块输出变量

[17:15:50 root@web1 ansible]#cat debug/debug.yaml 
---
- hosts: all
  tasks:
    - name: hello word
      debug: 
    - name: 主机名称与IP
      debug:
        msg: Host "{{ ansible_nodename }}" is "{{ ansible_default_ipv4.address }}"
#运行
[17:28:24 root@web1 ansible]#ansible-playbook debug/debug.yaml 

PLAY [all] *************************************************************************

TASK [Gathering Facts] *************************************************************
ok: [192.168.10.181]
ok: [192.168.10.182]

TASK [hello word] ******************************************************************
ok: [192.168.10.182] => {
    "msg": "Hello world!"
}
ok: [192.168.10.181] => {
    "msg": "Hello world!"
}

TASK [主机名称与IP] *********************************************************************
ok: [192.168.10.182] => {
    "msg": "Host \"web2.zhangzhuo.org\" is \"192.168.10.182\""
}
ok: [192.168.10.181] => {
    "msg": "Host \"web1.zhangzhuo.org\" is \"192.168.10.181\""
}

PLAY RECAP *************************************************************************
192.168.10.181             : ok=3    changed=0    unreachable=0    failed=0   
192.168.10.182             : ok=3    changed=0    unreachable=0    failed=0

三、Playbook

3.1 playbook介绍

image-20210706172945049

  • playbook 剧本是由一个或多个"play"组成的列表
  • play的主要功能在于将预定义的一组主机,装扮成事先通过ansible中的task定义好的角色。Task 实际是调用ansible的一个module,将多个play组织在一个playbook中,即可以让它们联合起 来,按事先编排的机制执行预定义的动作
  • Playbook 文件是采用YAML语言编写的

3.2 playbook核心组件

一个playbook 中由列表组成,其中所用到的常见组件类型如下

  • Hosts 执行的远程主机列表
  • Tasks 任务集,由多个task的元素组成的列表实现,每个task是一个字典,一个完整的代码块功能需最 少元素需包括 name 和 task,一个name只能包括一个task
  • Variables 内置变量或自定义变量在playbook中调用
  • Templates 模板,可替换模板文件中的变量并实现一些简单逻辑的文件
  • Handlers 和 notify 结合使用,由特定条件触发的操作,满足条件方才执行,否则不执行
  • tags 标签 指定某条任务执行,用于选择运行playbook中的部分代码。ansible具有幂等性,因此 会自动跳过没有变化的部分,即便如此,有些代码为测试其确实没有发生变化的时间依然会非常地 长。此时,如果确信其没有变化,就可以通过tags跳过此些代码片断

3.2.1 hosts组件

Hosts:playbook中的每一个play的目的都是为了让特定主机以某个指定的用户身份执行任务。hosts 用于指定要执行指定任务的主机,须事先定义在主机清单中

#示例
- hosts: web1:web2
- hosts: all
- hosts: web:!web1

3.2.2 remote_user组件

remote_user: 可用于Host和task中。也可以通过指定其通过sudo的方式在远程主机上执行任务,其可用于play全局或某任务;此外,甚至可以在sudo时使用sudo_user指定sudo时切换的用户

---
- hosts: web1:web2
  remote_user: root

  tasks:
    - name: test connection
      ping:
      remote_user: zhang

3.2.3 task列表和action组件

play的主体部分是task list,task list中有一个或多个task,各个task 按次序逐个在hosts中指定的所有主机上执行,即在所有主机上完成第一个task后,再开始第二个task

task的目的是使用指定的参数执行模块,而在模块参数中可以使用变量。模块执行是幂等的,这意味着 多次执行是安全的,因为其结果均一致

每个task都应该有其name,用于playbook的执行结果输出,建议其内容能清晰地描述任务执行步骤。 如果未提供name,则action的结果将用于输出

范例

---
- hosts: all
  remote_user: root
  gather_facts: no    #不收集系统信息,提高执行效率

  tasks:
    - name: test connection
      ping:
    - name: run shell
      shell: wall "zhangzhuo"

#安装apache2
---
- hosts: all
  remote_user: root
  gather_facts: no  

  tasks:
    - name: test connection
      ping:
    - name: run shell
      shell: wall "zhangzhuo"
    - name: install apache2
      apt: name=apache2
    - name: stop apache2
      service: name=apache2 state=stopped enabled=no

3.2.4 其他组件

某任务的状态在运行后为changed时,可通过"notify"通知给相应的handlers任务可以通过"tags"打标签,可在ansible-playbook命令上使用-t指定进行调用

3.3 playbook命令

格式

ansible-playbook <filename.yml> ... [options]

常见选项

--syntax-check      #语法检查,相当于bash -n 
-C --check          #只检测可能会发生的改变,但不真正执行操作,dry run 
--list-hosts        #列出运行任务的主机
--list-tags         #列出tag
--list-tasks        #列出task
--limit 主机列表     #只针对主机列表中的特定主机执行
-i INVENTORY        #指定主机清单文件
-v -vv  -vvv        #显示过程

范例

#检测,不真正执行
[17:48:39 root@web1 ansible]#ansible-playbook test/test.yaml --check
#只针对特定的主机执行
[17:53:07 root@web1 ansible]#ansible-playbook test/test.yaml --limit web
#指定其他主机清单文件
[17:54:37 root@web1 ansible]#ansible-playbook test/test.yaml -i hosts/hosts

3.4 Playbook示例

3.4.1 利用playbook二进制安装mysql 5.7

---
- hosts: all
  remote_user: root
  gather_facts: no

  tasks:
    - name: "安装mysql所需组件"
      apt: name=libaio-dev
    - name: "创建mysql组"
      group: name=mysql gid=306
    - name: "创建mysql用户"
      user: name=mysql uid=306 group=mysql shell=/sbin/nologin system=yes create_home=no home=/data/mysql
    - name: "拷贝mysql二进制压缩文件"
      unarchive: src=mysql-5.7.31-linux-glibc2.12-x86_64.tar.gz dest=/usr/local/ owner=mysql group=mysql
    - name: "创建mysql二进制文件软连接"
      file: src=/usr/local/mysql-5.7.31-linux-glibc2.12-x86_64 dest=/usr/local/mysql state=link owner=mysql group=mysql
    - name: "创建mysql数据目录"
      file: path=/data/mysql owner=mysql group=mysql state=directory
    - name: "创建mysql日志文件"
      file: path=/var/log/mysql.log owner=mysql group=mysql state=touch
    - name: "准备mysql配置文件"
      copy: src=my.cnf dest=/etc/ backup=yes
    - name: "准备mysql环境变量"
      copy: content='export PATH=/usr/local/mysql/bin:$PATH' dest=/etc/profile.d/mysql.sh
    - name: "生成数据库初始化文件"
      script: mysql_db.sh 
    - name: "生成service服务文件"
      copy: src=mysql.service dest=/etc/systemd/system/
    - name: "启动mysql服务"
      service: name=mysql state=restarted enabled=yes

3.5 Playbook中使用handlers和notify

Handlers本质是task list ,类似于MySQL中的触发器触发的行为,其中的task与前述的task并没有本质上的不同,主要用于当关注的资源发生变化时,才会采取一定的操作。而Notify对应的action可用于在每个play的最后被触发,这样可避免多次有改变发生时每次都执行指定的操作,仅在所有的变化发生完成后一次性地执行指定操作。在notify中列出的操作称为handler,也即notify中调用handler中定义的操作

注意

  • 如果多个task通知了相同的handlers, 此handlers仅会在所有tasks结束后运行一 次
  • 只有notify对应的task发生改变了才会通知handlers, 没有改变则不会触发handlers

示例

#重复执行时只有nginx.conf文件变化才会执行nginx重启
---
- hosts: all
  remote_user: root
  gather_facts: no
  force_handlers: yes
  tasks:
    - name: install nginx
      apt: name=nginx
    - name: install configure file
      copy: src=file/nginx.conf dest=/etc/nginx/
      notify:    
        - restart nginx
        - wall
    - name: ensure nginx is runnging
      service: name=nginx state=started enabled=yes
  handlers:
    - name: restart nginx
      service: name=nginx state=restarted
    - name: wall
      command: wall "hello nginx"

3.6 Playbook中使用tags组件

在playbook文件中,可以利用tags组件,为特定 task 指定标签,当在执行playbook时,可以只执行特 定tags的task,而非整个playbook文件

可以一个task对应多个tag,也可以多个task对应一个tag

[20:10:12 root@web1 handlers]#cat handlers.yaml 
---
- hosts: all
  remote_user: root
  gather_facts: no
  force_handlers: yes
  tasks:
    - name: install nginx
      apt: name=nginx
    - name: install configure file
      copy: src=file/nginx.conf dest=/etc/nginx/
      notify:
        - restart nginx
        - wall
      tags:
        - conf
        - file
    - name: ensure nginx is runnging
      service: name=nginx state=started enabled=yes
  handlers:
    - name: restart nginx
      service: name=nginx state=restarted
    - name: wall
      command: wall "hello nginx"
#验证
[20:10:29 root@web1 handlers]#ansible-playbook -t conf handlers.yaml
[20:11:13 root@web1 handlers]#ansible-playbook handlers.yaml --list-tags

playbook: handlers.yaml

  play #1 (all): all	TAGS: []
      TASK TAGS: [conf, file]

3.7 Playbook中使用变量

变量名:仅能由字母、数字和下划线组成,且只能以字母开头

变量定义

variable=value

变量调用方式

通过 {{ variable_name }} 调用变量,且变量名前后建议加空格,有时用"{{ variable_name }}"才生 效

变量来源

  1. ansible的setup facts远程主机的所有变量都可以直接调用
  2. 通过命令行指定变量,优先级最高
[20:21:23 root@web1 ansible]#ansible-playbook -e zhang=cy test/test.yaml
  1. 在playbook文件中定义
vars:
 var1: value1
 var2: value2
  1. 在独立的变量YAML文件中定义
- hosts: all
 vars_files:
   - vars.yml
  1. 在/etc/ansible/hosts中定义
主机(普通)变量:主机组中主机单独定义,优先级高于公共变量
组(公共)变量:针对主机组中所有主机定义统一变量
  1. 在role中定义

变量优先级

-e 选项定义变量 --->playbook中vars_files --> playbook中vars变量定义 --> 主机清单中主机变量---> 主机清单组变量

3.7.1 使用setup模块中变量

本模块自动在playbook调用,不要用ansible命令调用

常见变量


案例:使用setup变量

[20:26:53 root@web1 ansible]#cat test/test.yaml
---
- hosts: all
  remote_user: root
  gather_facts: yes

  tasks:
    - name: create log file
      file: name=/root/{{ ansible_nodename }}.log state=touch owner=zhang group=zhang

#执行结果
[20:26:55 root@web1 ansible]#ansible-playbook test/test.yaml 
[20:27:27 root@web1 ansible]#ls /root/
web1.zhangzhuo.org.log

3.7.2 在playbook命令行中定义

范例:

[20:29:45 root@web1 test]#cat test.yaml 
---
- hosts: all
  remote_user: root
  gather_facts: yes

  tasks:
    - name: install {{ pkname }}
      apt: name={{ pkname }}
[20:29:48 root@web1 test]#ansible-playbook -e pkname=sshpass test.yaml
TASK [install sshpass] *************************************************************
ok: [192.168.10.181]
changed: [192.168.10.182]

范例:变量放入文件

[20:31:45 root@web1 test]#cat vars 
pkname: redis
#运行
[20:31:47 root@web1 test]#ansible-playbook -e '@vars' test.yaml

3.7.3 在playbook文件中定义变量

范例

---
- hosts: all
  remote_user: root
  vars:
    username: user1
    groupname: group1
  tasks:
    - name: create group
      group: name={{ groupname }}
    - name: create user
      user: name={{ username }} group={{ groupname }}

变量的互相调用

---
- hosts: all
  vars:
    suffix: "txt"
    file: "{{ ansible_nodename }}.{{ suffix }}"
  tasks:
    - name: test var
      file: path="/root/{{file}}" state=touch

3.7.4 使用变量文件

可以在一个独立的playbook文件中定义变量,在另一个playbook文件中引用变量文件中的变量,比 playbook中定义的变量优化级高

[14:10:11 root@web1 test]#cat vars.yml 
package_name: sshpass

[14:12:14 root@web1 test]#cat var5.yaml 
---
- hosts: all 
  remote_user: root
  vars_files:
    - vars.yml
  tasks:
    - name: install {{ package_name }}
      apt: name={{ package_name }}

3.7.5 主机清单文件中定义变量

3.7.5.1 主机变量

在inventory 主机清单文件中为指定的主机定义变量以便于在playbook中使用

范例

[14:18:05 root@web1 test]#cat ../hosts/hosts
[all]
192.168.10.181 file_name=zhangzhuo1
192.168.10.182 file_name=zhangzhuo2

---
- hosts: all 
  remote_user: root
  vars_files:
    - vars.yml
  tasks:
    - name: touch {{ file_name }}
      file: path=/root/{{ file_name }} state=touch

#执行后结果
[14:20:31 root@web1 test]#ansible-playbook var5.yaml -i ../hosts/hosts 

[14:21:38 root@web1 test]#ansible all -m shell -a 'ls /root'
192.168.10.181 | SUCCESS | rc=0 >>
zhangzhuo1

192.168.10.182 | SUCCESS | rc=0 >>
zhangzhuo2

3.7.5.2 组(公共)变量

在inventory 主机清单文件中赋予给指定组内所有主机上的在playbook中可用的变量,如果和主机变是同名,优先级低于主机变量

范例

[14:25:04 root@web1 test]#cat ../hosts/hosts
[web]
192.168.10.181
192.168.10.182
[web:vars]
file_name=cy
mode=777
user=bin
group=bin

[14:27:45 root@web1 test]#cat var6.yaml 
---
- hosts: web
  remote_user: root
  tasks:
    - name: create {{ file_name }}
      file: path=/root/{{ file_name }} mode={{ mode }} group={{ group }} owner={{ user }}

#执行
[14:27:54 root@web1 test]#ansible-playbook var6.yaml -i ../hosts/hosts

3.7.6 register 注册变量

在playbook中可以使用register将捕获命令的输出保存在临时变量中,然后使用debug模块进行显示输出

范例: 利用debug 模块输出变量

---
- hosts: all
  
  tasks:
    - name: get variable
      shell: hostname
      register: name
    - name: print variable
      debug:
        msg: "{{ name }}"   # 输出register注册的name变量的全部信息
#        msg: {{ name.cmd }}  # 引用方式一,显示命令
#        msg: {{ name.rc }}   # 引用方式一,显示命令
#        msg: {{ name['stdout_lines'] }} # 引用方式二,显示命令的执行结果


#说明
#第一个 task 中,使用了 register 注册变量名为 name ;当 shell 模块执行完毕后,会将数据放到该变量中。
#第二给 task 中,使用了 debug 模块,并从变量name中获取数据。

使用register变量创建文件

[14:39:16 root@web1 test]#cat var7.yaml 
---
- hosts: all
  
  tasks:
    - name: get variable
      shell: hostname
      register: name
    - name: touch file is {{ name.stdout }}  
      file: path=/root/{{ name.stdout }} state=touch

3.8 tempalate模板

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

3.8.1 jinja2语言

官方网站

http://jinja.pocoo.org/

https://jinja.palletsprojects.com/en/2.11.x/

jinja2 语言支持多种数据类型和操作

字面量,如: 字符串:使用单引号或双引号,数字:整数,浮点数
列表:[item1, item2, ...]
元组:(item1, item2, ...)
字典:{key1:value1, key2:value2, ...}
布尔型:true/false
算术运算:+, -, *, /, //, %, **
比较操作:==, !=, >, >=, <, <=
逻辑运算:and,or,not 
流表达式:For,If,When

字面量

表达式最简单的形式就是字面量。字面量表示诸如字符串和数值的 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

3.8.2 template

template功能:可以根据和参考模块文件,动态生成相类似的配置文件

template文件必须存放于templates目录下,且命名为 .j2 结尾

yaml/yml 文件需和templates目录平级,目录结构如下示例:

[16:31:15 root@web1 nginx]#tree 
.
├── nginx.retry
├── nginx.yaml
└── templates
    ├── index.html.j2
    └── nginx.conf.j2

范例:利用template同步nginx配置文件

#准备template/nginx.conf.j2文件
[14:52:16 root@web1 nginx]#cat nginx.yaml 
---
- hosts: all
  remote_user: root
  tasks:
    - name: install nginx
      apt: name=nginx
    - name: teplate config to remote hosts
      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
    - name: restart nginx
      service: name=nginx state=started enabled=yes
#nginx.conf.j2文件
[16:32:09 root@web1 nginx]#cat templates/nginx.conf.j2 
user {{ nginx_user }};
worker_processes {{ ansible_processor_vcpus+2 }};
pid /run/nginx.pid;
error_log /var/log/nginx/error.log error;
worker_priority 0;
worker_rlimit_nofile 655360;

events {
    worker_connections 1024;
    use epoll;
    accept_mutex on;
    multi_accept on;
}

http {
	include /etc/nginx/mime.types;
	default_type application/octet-stream;
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 0;
	gzip on;
    access_log /var/log/nginx/access.log;
    server {
      listen 80;
      server_name localhost;
      location / {
        root /data/html;
        index index.html;
      }
    }
}
#index.html.j2文件
[16:33:53 root@web1 nginx]#cat templates/index.html.j2 
<h1>{{ ansible_nodename }}</h1>

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

template中也可以使用流程控制 for 循环和 if 条件判断,实现动态生成文件功能

3.8.3.1 for循环

范例:for循环

---
- hosts: all
  remote_user: root
  vars:
    nginx_user: nginx
    ip:
      - 192.168.10.181
      - 192.168.10.182
      - 192.168.10.183
    name:
      - hostname: "{{ ansible_nodename }}"
        root: root
        name: zhangzhuo
  tasks:
    - name: create group {{ nginx_user }}
      group: name={{ nginx_user }} state=present gid=80 system=yes
    - name: create user {{ nginx_user }}
      user: name={{ nginx_user }} state=present create_home=no group=nginx uid=80 system=yes home=/data/html shell=/sbin/nologin
    - name: mkdir nginx is html
      file: path=/data/html group=nginx owner=nginx state=directory
    - name: install nginx
      apt: name=nginx
    - name: teplate config to remote hosts
      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf group=nginx owner=nginx
    - name: teplate index
      template: src=index.html.j2 dest=/data/html/index.html group=nginx owner=nginx
    - name: restart nginx
      service: name=nginx state=restarted enabled=yes


[16:42:32 root@web1 nginx]#cat templates/index.html.j2 
{% for index_name in nginx_user %}
<h1>{{ index_name }}</h1>
{% endfor %}
{% for node in ip %}
<h1>{{ node }}</h1>
{% endfor %}
#生成的文件
[16:43:06 root@web1 nginx]#cat  /data/html/index.html 
[16:42:20 root@ubuntu18-04 ~]#cat /data/html/index.html 
[16:56:55 root@web1 nginx]#cat templates/index.html.j2 
{% for index_name in nginx_user %}
<h1>{{ index_name }}</h1>
{% endfor %}
{% for node in ip %}
<h1>{{ node }}</h1>
{% endfor %}
{% for nide in name %}
<h1>{{ nide.hostname }}</h1>
<h1>{{ nide.root }}</h1>
<h1>{{ nide.name }}</h1>
{% endfor %}

循环变量的说明

vars:
    nginx_user: nginx   #这种变量一次循环一个字符
    ip:  #这种变量一次循序一个列表元素
      - 192.168.10.181 
      - 192.168.10.182
      - 192.168.10.183
    name:    #这样定义变量可以控制输入选择
      - hostname: "{{ ansible_nodename }}"
        root: root
        name: zhangzhuo

for循环说明

{% for index_name in nginx_user %}
<h1>{{ index_name }}</h1>
{% else %}   #如果变量为空执行
<h1>is null</h1>
{% endfor %}

3.8.3.2 if判断

在模版文件中还可以使用 if条件判断,决定是否生成相关的配置信息

范例

[17:12:30 root@web1 nginx]#cat templates/index.html.j2 
{% for index_name in nginx_user %}
<h1>{{ index_name }}</h1>
{% endfor %}
{% for node in ip %}
<h1>{{ node }}</h1>
{% endfor %}
{% for nide in name %}
<h1>{{ nide.hostname }}{{ nide.root }}{{ nide.name }}</h1>
{% endfor %}
{% if zhangzhuo == 'cy' %}
<h1>is true</h1>
{% elif zhangzhuo == 'nide' %}
<h1>is nide</h1>
{% else %}
<h1>is flase</h1>
{% endif %}

判断说明

{% if zhangzhuo == 'cy' %}   #判断成立执行
<h1>is true</h1>
{% elif zhangzhuo == 'nide' %} #判断成立执行
<h1>is nide</h1>
{% else %}   #所有判断不成立执行
<h1>is flase</h1>
{% endif %}  #结束

3.9 playbook使用 when

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

范例:判断正确执行

---
- hosts: all
  remote_user: root
  vars:
    nginx_user: nginx
    zhangzhuo: 123
    ip:
      - 192.168.10.181
      - 192.168.10.182
      - 192.168.10.183
    name:
      - hostname: "{{ ansible_nodename }}"
        root: root
        name: zhangzhuo
  tasks:
    - name: echo {{ ansible_nodename }}
      shell: echo {{ ansible_nodename }} >>/data/html/index.html
      when: ansible_nodename  == "web1.zhangzhuo.org"  #判断成功执行

范例:上个task执行成功执行这个tags

---
- hosts: all
  remote_user: root
  vars:
    nginx_user: nginx
    zhangzhuo: 123
    ip:
      - 192.168.10.181
      - 192.168.10.182
      - 192.168.10.183
    name:
      - hostname: "{{ ansible_nodename }}"
        root: root
        name: zhangzhuo
  tasks:
    - name: echo {{ ansible_nodename }}
      shell: echo {{ ansible_nodename }} >>/data/html/index.html
      when: ansible_nodename  == "web1.zhangzhuo.org"
      register: echo_html  #获取状态代码
    - name: echo nide
      shell: echo nide >>/data/html/index.html
      when: echo_html.rc == 0   #如果echo_html的tags执行命令结果成功,即echo_html.rc等于0,则执行,否则跳过

3.10 playbook 使用迭代 with_items(loop)

迭代:当有需要重复性执行的任务时,可以使用迭代机制

对迭代项的引用,固定内置变量名为"item"

要在task中使用with_items给定要迭代的元素列表

注意: ansible2.5版本后,可以用loop代替with_items

列表元素格式

  • 字符串
  • 字典

范例

[19:56:03 root@web1 ansible]#cat test/with_items.yaml
---
- hosts: all
  remote_user: root

  tasks:
    - name: touch files
      file: path=/root/{{ item }} state=touch
      with_items:
        - test1
        - test2
        - test3
        - test4
#与下面语句功能一样
---
- hosts: all
  remote_user: root
  tasks:
    - name: touch files1
      file: path=/root/test1 state=touch
    - name: touch files2
      file: path=/root/test2 state=touch
    - name: touch files3
      file: path=/root/test3 state=touch
    - name: touch files4
      file: path=/root/test4 state=touch

迭代嵌套子变量:在迭代中,还可以嵌套子变量,关联多个变量在一起使用

---
- hosts: all
  remote_user: root

  tasks:
    - name: touch files
      file: path=/root/{{ item.name }} state=touch owner={{ item.user }} group={{ item.group }}
      with_items:
        - { name: 'test1',user: 'bin',group: 'root' }
        - { name: 'test2',user: 'bin',group: 'root' }
        - { name: 'test3',user: 'bin',group: 'root' }
        - { name: 'test4',user: 'bin',group: 'root' }

3.11 管理节点过多导致的超时时间问题解决方法

默认情况下,Ansible将尝试并行管理playbook中所有的机器。对于滚动更新用例,可以使用serial关键 字定义Ansible一次应管理多少主机,还可以将serial关键字指定为百分比,表示每次并行执行的主机数占总数的比例

---
- hosts: all
  remote_user: root
  serial: 1    #每次只同时处理2个主机,将所有task执行完成后,再选下2个主机再执行所有task,直至所有主机处理完成
  serial: "20%"  #每次只同时处理20%的主机

  tasks:
    - name: touch files
      file: path=/root/{{ item.name }} state=touch owner={{ item.user }} group={{ item.group }}
      with_items:
        - { name: 'test1',user: 'bin',group: 'root' }
        - { name: 'test2',user: 'bin',group: 'root' }
        - { name: 'test3',user: 'bin',group: 'root' }
        - { name: 'test4',user: 'bin',group: 'root' }

3.12 忽略错误ignore_errors

如果一个task出错,默认将不会继续执行后续的其它task

利用 ignore_errors: yes 可以忽略此task的错误,继续向下执行playbook其它task

[20:14:19 root@web1 ansible]#cat test/ignore_errors.yaml 
---
- hosts: all
  remote_user: root
  serial: 1
  gather_facts: no
  tasks:
    - name: error
      command: /bin/false
      ignore_errors: yes
    - name: continue
      shell: wall zhangzhuo

3.13 关闭 changed 状态

当确定某个task不会对被控制端做修改时,可以通过 changed_when: false 关闭changed状态

---
- hosts: all
  remote_user: root
  serial: 1
  gather_facts: no
  tasks:
    - name: error
      command: /bin/false
      ignore_errors: yes
      changed_when: false   #关闭changed状态  
    - name: continue
      shell: wall zhangzhuo

3.14 利用changed_when检查task返回结果

changed_when 检查task返回结果,决定是否继续向下执行

---
- hosts: all
  remote_user: root
  gather_facts: no
  tasks:
    - name: error
      command: /bin/echo
      register: check_nginx_config
      changed_when:
        - (check_nginx_config.stdout.find('AAA'))
    - name: continue
      shell: wall zhangzhuo

3.15 yaml文件的相互调用

利用include 或 include_tasks 可以调用其它的yaml文件

[20:37:00 root@web1 test]#cat test.yaml 
---
- hosts: all
  remote_user: root
  gather_facts: yes
  tasks:
    - name: create files
      file: path=/root/zhangzhuo state=touch
    - name: excute b.yml
      include: b.yml
      #include_tasks: b.yml #另一种写法
[20:37:05 root@web1 test]#cat b.yml 
    - name: touch files
      file: path=/root/{{ item.name }} state=touch owner={{ item.user }} group={{ item.group }}
      with_items:
        - { name: 'test1',user: 'bin',group: 'root' }
        - { name: 'test2',user: 'bin',group: 'root' }
        - { name: 'test3',user: 'bin',group: 'root' }
        - { name: 'test4',user: 'bin',group: 'root' }

3.16 使用connection本地执行tasks

使用connection可以在本机执行tasks

[20:20:42 root@zhangzhuo ~]#cat 1.yaml 
---
- hosts: all
  connection: local   #写到这里表现tasks中所有的任务都在本机执行
  tasks:
    - name: node
      shell: hostname
      connection: local   #写到其中的一个tasks中表示只有这个tasks在本机执行
      register: hostname
    - name: print variable
      shell: echo {{ hostname.stdout }} >test
    - name: print variable
      debug:
        msg: "{{ hostname }}"

四、roles角色

角色是ansible自1.2版本引入的新特性,用于层次性、结构化地组织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

4.1 ansible Roles目录编排

roles目录结构如下所示

image-20210707203955861

每个角色,以特定的层级目录结构进行组织

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的优先级低

4.2 创建role

创建role的步骤

1 创建以roles命名的目录
2 在roles目录中分别创建以各角色名称命名的目录,如mysql等
3 在每个角色命名的目录中分别创建files、handlers、tasks、templates和vars等目录;用不到的目录可以创建为空目录,也可以不创建
4 在每个角色相关的子目录中创建相应的文件,如 tasks/main.yml,templates/nginx.conf.j2
5 在playbook文件中,调用需要的角色

针对大型项目使用Roles进行编排

范例:roles的目录结构

[20:48:37 root@web1 roles]#tree 
.
├── nginx-role.yaml
└── roles
    ├── files
    │   └── nginx.conf
    ├── tasks
    │   ├── groupadd.yaml
    │   ├── install.yaml
    │   ├── main.yaml
    │   ├── restart.yaml
    │   └── useradd.yaml
    └── vars
        └── main.yaml

4.3 playbook调用角色

调用角色方法1:

---
- hosts: all
  remote_user: root
  roles:
    - mysql
    - nginx

调用角色方法2:

键role用于指定角色名称,后续的k/v用于传递变量给角色

---
- hosts: all
 remote_user: root
 roles:
   - mysql
   - { role: nginx, username: nginx }

调用角色方法3:

还可基于条件测试实现角色调用

---
- hosts: all
 remote_user: root
 roles:
   - { role: nginx, username: nginx, when: ansible_distribution_major_version == '7' }

4.4 roles中tags使用

[root@ansible ~]#vi app-role.yml
---
- 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' ] }

[root@ansible ~]#ansible-playbook --tags="nginx,mysql" app-role.yml

4.5 示例

4.5.1 实现docker角色

#创建角色相关的目录
[20:54:44 root@web1 ~]#mkdir -pv roles/docker/{tasks,handlers,files}

#创建角色相关的文件
[20:55:27 root@web1 ansible]#cd roles/docker/


#main.yml 是task的入口文件
[14:20:19 root@ansible docker]#cat tasks/main.yml 
- include: docker_install.yaml   #docker安装
- include: docker_service.yaml   #生成dicker的service文件
- include: swap_off.yaml         #关闭swap交换分区
- include: docker_etc.yaml       #生成docker的etc文件
- include: docker_start.yaml     #启动docker

#各tasks内容
[14:20:24 root@ansible docker]#cat tasks/docker_install.yaml 
- name: install docker
  unarchive: src=docker-19.03.15.tgz dest=/tmp/
- name: cpoy docker is bin
  shell: cp -rf /tmp/docker/* /usr/bin/
- name: remove docker-bin
  shell: rm -rf /tmp/docker
  
[14:33:26 root@ansible docker]#cat tasks/docker_service.yaml 
- name: add containerd_service
  template: src=containerd.service.j2 dest=/etc/systemd/system/containerd.service
- name: add docker_service
  template: src=docker.service.j2 dest=/etc/systemd/system/docker.service 
- name: add docker socket
  template: src=docker.socket.j2 dest=/etc/systemd/system/docker.socket
  
[14:33:48 root@ansible docker]#cat tasks/swap_off.yaml 
- name: swap off is fstab
  lineinfile: path=/etc/fstab regexp="swap" state=absent
- name: swap is off
  shell: swapoff -a
  
[14:34:06 root@ansible docker]#cat tasks/docker_etc.yaml 
- name: mkdir /etc/docker
  file: path=/etc/docker state=directory
- name: docker etc is file
  template: src=daemon.json.j2 dest=/etc/docker/daemon.json
  
[14:34:17 root@ansible docker]#cat tasks/docker_start.yaml 
- name: start containerd
  service: name=containerd state=restarted enabled=yes
- name: start docker.socket
  service: name=docker.socket state=restarted enabled=yes
- name: start docker
  service: name=docker state=restarted enabled=yes

#files目录下准备docker二进制文件
[14:34:28 root@ansible docker]#ls files/
docker-19.03.15.tgz

#template目录准备service文件与etc配置文件
[14:36:20 root@ansible docker]#ls templates/
containerd.service.j2  daemon.json.j2  docker.service.j2  docker.socket.j2

#在playbook中调用角色
[14:37:49 root@ansible roles]#cat role_docker.yml 
- hosts: all
  remote_user: root
  roles:
    - docker
    
#最终的目录结构
[14:37:47 root@ansible roles]#tree 
.
├── docker
│   ├── files
│   │   └── docker-19.03.15.tgz
│   ├── handlers
│   ├── tasks
│   │   ├── docker_etc.yaml
│   │   ├── docker_install.yaml
│   │   ├── docker_service.yaml
│   │   ├── docker_start.yaml
│   │   ├── main.yml
│   │   └── swap_off.yaml
│   └── templates
│       ├── containerd.service.j2
│       ├── daemon.json.j2
│       ├── docker.service.j2
│       └── docker.socket.j2
└── role_docker.yml

4.5.2 实现zabbix-agent角色

role目录结构

[17:57:10 root@ansible zabbix-agent]#tree 
.
├── role_zabbix-agent.yml
└── zabbix-agent
    ├── files
    │   ├── echo.sh
    │   └── zabbix-4.0.30.tar.gz
    ├── tasks
    │   ├── main.yaml
    │   ├── zabbix_conf.yaml
    │   ├── zabbix_install.yaml
    │   └── zabbix_service.yaml
    ├── templates
    │   ├── zabbix_agentd.conf.j2
    │   ├── zabbix-agent-install.sh.j2
    │   ├── zabbix-agent.service.j2
    │   └── zabbix_UserParameter.conf.j2
    └── vars
        └── main.yaml

file目录文件

[17:58:09 root@ansible zabbix-agent]#ls zabbix-agent/files/
echo.sh  zabbix-4.0.30.tar.gz
[17:58:15 root@ansible zabbix-agent]#cat zabbix-agent/files/echo.sh 
#!/bin/bash
echo $1$2

tasks目录文件

[17:58:26 root@ansible zabbix-agent]#cat  zabbix-agent/tasks/main.yaml 
- include: zabbix_install.yaml
- include: zabbix_conf.yaml
- include: zabbix_service.yaml

[17:59:05 root@ansible zabbix-agent]#cat zabbix-agent/tasks/zabbix_install.yaml 
- name: install zabbix-agent
  unarchive: src=zabbix-4.0.30.tar.gz dest=/tmp/
- name: copy zabbix-agent is install sh
  template: src=zabbix-agent-install.sh.j2 dest=/tmp/zabbix-4.0.30/zabbix-agent-install.sh
- name: make install zabbix-agent
  shell: chdir=/tmp/zabbix-4.0.30 bash zabbix-agent-install.sh 

[17:59:17 root@ansible zabbix-agent]#cat zabbix-agent/tasks/zabbix_conf.yaml 
- name: mkdir logs
  file: path={{ install_dir }}/logs state=directory
- name: mkdir pid
  file: path={{ install_dir }}/pid state=directory
- name: mkdir conf
  file: path={{ install_dir }}/etc/zabbix_agentd.conf.d state=directory
- name: mkdir shell
  file: path={{ install_dir }}/shell state=directory
- name: copy is shell
  copy: src=echo.sh dest={{ install_dir }}/shell/ mode=755
- name: touch file is conf
  template: src=zabbix_agentd.conf.j2 dest={{ install_dir }}/etc/zabbix_agentd.conf
- name: touch UserParameter is conf
  template: src=zabbix_UserParameter.conf.j2 dest={{ install_dir }}/etc/zabbix_agentd.conf.d/zabbix_UserParameter.conf
- name: chown is zabbix
  file: path={{ install_dir }} owner=zabbix group=zabbix recurse=yes

[17:59:26 root@ansible zabbix-agent]#cat zabbix-agent/tasks/zabbix_service.yaml 
- name: touch zabbix-agent is service
  template: src=zabbix-agent.service.j2 dest=/etc/systemd/system/zabbix-agent.service
- name: start zabbix-agent 
  service: name=zabbix-agent state=restarted enabled=yes

vars目录文件

[17:59:50 root@ansible zabbix-agent]#cat zabbix-agent/vars/main.yaml 
install_dir: "/apps/zabbix-agent"
zabbix_server_ip: '192.168.10.181'
#name:监控项名称
#shell:获取监控数据脚本名称
#参数
Parameter:
  - name: echo[*]
    shell: echo.sh
    cmd: '"$1" "$2"'
  - name: echo1
    shell: echo
    cmd: 1

templates目录文件

[18:00:32 root@ansible zabbix-agent]#cat zabbix-agent/templates/zabbix-agent.service.j2 
[Unit]
Description=Zabbix Agent
After=syslog.target
After=network.target
[Service]
Environment="CONFFILE={{ install_dir }}/etc/zabbix_agentd.conf"
#EnvironmentFile=-/etc/default/zabbix-agent
Type=forking
Restart=on-failure
PIDFile={{ install_dir }}/pid/zabbix_agentd.pid
KillMode=control-group
ExecStart={{ install_dir }}/sbin/zabbix_agentd -c $CONFFILE
ExecStop=/bin/kill -SIGTERM $MAINPID
RestartSec=10s
User=zabbix
Group=zabbix
[Install]
WantedBy=multi-user.target

[18:00:58 root@ansible zabbix-agent]#cat zabbix-agent/templates/zabbix_agentd.conf.j2 
PidFile={{ install_dir }}/pid/zabbix_agentd.pid
LogType=file
LogFile={{ install_dir }}/logs/zabbix_agentd.log
LogFileSize=1
DebugLevel=3
# SourceIP=
EnableRemoteCommands=1
LogRemoteCommands=1
Server={{ zabbix_server_ip }}
ListenPort=10050
ListenIP=0.0.0.0
StartAgents=5
ServerActive={{ zabbix_server_ip }}
Hostname={{ ansible_nodename }}
RefreshActiveChecks=120
BufferSend=60
BufferSize=100
MaxLinesPerSecond=20
Timeout=30
AllowRoot=0
User=zabbix
Include={{ install_dir }}/etc/zabbix_agentd.conf.d/*.conf
UnsafeUserParameters=1

[18:01:13 root@ansible zabbix-agent]#cat zabbix-agent/templates/zabbix-agent-install.sh.j2 
install(){
version=`grep -Eo "(centos|ubuntu)" /etc/os-release | head -n1`
    if [ $version = centos ];then
        yum install gcc libxml2-devel libevent-devel net-snmp net-snmp-devel curl curl-devel -y || exit 1
    elif [ ${version} = ubuntu ];then
        apt-get install ssl-cert ttf-dejavu-core libmysqlclient-dev libxml2-dev libxml2  libsnmp-dev libevent-dev openjdk-8-jdk curl libcurl4-openssl-dev -y || exit 1
    else
        exit 1
    fi
}
install_agent(){
    id zabbix &>/dev/null || useradd -r -s /sbin/nologin zabbix
    ./configure --prefix={{ install_dir }} --enable-agent  --enable-ipv6 --with-net-snmp --with-libcurl --with-libxml2 || exit 2
    make install
}
main(){
  install
  install_agent
}
main

[18:01:47 root@ansible zabbix-agent]#cat zabbix-agent/templates/zabbix_UserParameter.conf.j2 
{% for i in Parameter %}
UserParameter={{ i.name }},{{install_dir}}/shell/{{ i.shell }} {{ i.cmd }}
{% endfor %}

标题:运维自运化之ANSIBLE
作者:Carey
地址:HTTPS://zhangzhuo.ltd/articles/2022/05/03/1651591259496.html

生而为人

取消