今日内容概述
1.运维自动化工具
2.什么是Ansible?
3.Ansible的功能及其优点
4.Ansible构成
-4.1 组成
-4.2 Ansible执行的流程
5.Ansible使用
6.Ansible模块
今日内容详细

1.运维自动化工具

1.Ansible优点是更轻量,但是是串行的,在大规模集群下,性能较低
2.saltstack的优点是处理大规模批量操作时效率会更高,因为它是并行的(C/S架构)salt-master和salt-minion
# 在处理大规模批量操作是我们可以使用Ansible把saltstack的客户端服务端部署好,再使用saltstack
Ansible支持跨平台

2.什么是Ansible?

Ansible是一个自动化统一配置管理工具,自动化主要体现在Ansible集成了丰富模块以及功能组件,可以通过一个命令完成一系列的操作,进而能减少重复性的工作和维护成本,可以提高工作效率

3.Ansible的功能及其优点

1.远程执行
批量执行远程命令,可以对多台主机进行远程操作
2.配置管理
批量配置软件服务,可以进行自动化方式配置,服务的统一配置管理和启停
3.事件驱动
通过Ansible模块,对服务进行不同的事件驱动
4.管理共有云
通过API接口的方式管理公有云,不过这方面做的不如saltstack
saltstack本身可以通过saltcloud管理各大云厂商的云平台
5.二次开发
因为是python开发的,所以便于二次开发
6.任务编排
可以通过playbook的方式来统一管理服务,并且可以使用一条命令,实现一套架构的部署
7.跨平台,跨系统
几乎不受平台和系统的限制

4.Ansible构成

4.1 组成

1.连接插件connection plugins用于连接主机 用来连接被管理端
2.核心模块core modules连接主机实现操作,它依赖于具体的模块来做具体的事情
3.自定义模块custom modules根据自己的需求编写具体的模块
4.插件plugins完成模块功能的补充
5.剧本playbookansible的配置文件,将多个任务定义在剧本中,由Ansible自动执行
6.主机清单inventor定义Ansible需要操作主机的范围
ps: 
最重要的一点是 Ansible 是模块化的,它所有的操作都依赖于模块

4.2 Ansible执行的流程

1.Ansible读取playbook剧本,剧本中会记录对哪些主机执行哪些任务   # web 安装nginx
2.首先Ansible通过主机清单找到要执行的主机,然后调用具体的模块    # web 是谁
3.其次Ansible会通过连接插件连接对应的主机并推送对应的任务列表    # 使用yum模块安装nginx
4.最后被管理的主机会将Ansible发送过来的任务解析为本地Shell命令执行   # 受控端执行 yum install -y nginx

5.Ansible使用

1.安装
下载yum源
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum install -y ansible
2.测试
ansible --version
ansible 2.9.24
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Nov 16 2020, 22:23:17) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
3.配置Ansible
# 配置主配置文件
vim /etc/ansible/ansible.cfg
需要修改的文件
host_key_checking = False	# 跳过检查主机指纹
log_path = /var/log/ansible.log	# ansible日志
# hosts配置文件(配置Ansible可以操作的主机的信息)
/etc/ansible/hosts
ansible主机配置
vim /etc/ansible/hosts
[web01]
172.16.1.7 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='512501'
[web02]
172.16.1.8 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='512501'
[web03]
172.16.1.9 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='512501'
[web:children]
web01
web02
web03
# 主机清单的配置方式
1.纯IP
[web]
172.16.1.7
2.纯主机名
[web]
web01
3.IP和主机名
[web]
172.16.1.7
web02
4.组合形式
[web01]
172.16.1.7 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='512501'
[web02]
172.16.1.8 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='512501'
[web03]
172.16.1.9 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='512501'
[web:children]	# 定义的整合组,包含多个组
web01
web02
web03
# 查看整合组下面的主机组
ansible web --list-host
  hosts (3):
    172.16.1.7
    172.16.1.8
    172.16.1.9
# 执行结果返回的颜色
绿色: 代表被管理端主机没有被修改
黄色: 代表被管理端主机发现变更
红色: 代表出现了故障,注意查看提示

6.Ansible模块

常用模块
command             # 执行shell命令(不支持管道等特殊字符)
shell               # 执行shell命令
scripts             # 执行shell脚本
yum_repository      # 配置yum仓库
yum                 # 安装软件
copy                # 变更配置文件
file                # 建立目录或文件
service             # 启动与停止服务
systemd             # 启动与停止服务
mount               # 挂载设备
cron                # 定时任务
get_url             # 下载软件
firewalld           # 防火墙
selinux             # selinux
setup               # 获取主机信息

# Ansible帮助
1.查看所有模块
ansible-doc -l
2.查看指定模块的用法
比如:ansible-doc yum
3.查看模块的参数
比如:ansible-doc -s yum

command模块(Ansible默认模块)

command模块可以帮助我们在远程主机上执行命令,但无法识别比如重定向,管道符这些符号。比如”<”, “>”, “|”, “;” 和 “&” 这些符号,如果我们需要这些功能,可以使用后面我们要学习的shell模块
参数:
chdir : 执行命令前,切换到该目录
creates	: 当该文件存在时,则不执行该步骤
removves : 当该文件存在时,则执行该步骤
案例:
[root@localhost ~]# ansible web01 -m command -a "chdir=/opt ls"
172.16.1.101 | CHANGED | rc=0 >>
phpMyAdmin-5.1.1-all-languages
[root@localhost ~]# ansible web01 -m command -a "chdir=/opt creates=/opt/phpMyAdmin-5.1.1-all-languages ls"
172.16.1.101 | SUCCESS | rc=0 >>
skipped, since /opt/phpMyAdmin-5.1.1-all-languages exists
[root@localhost ~]# ansible web01 -m command -a "chdir=/opt creates=/opt/phpMyAdmin-5.1.1-all-languages   mkdir test"
172.16.1.101 | SUCCESS | rc=0 >>
skipped, since /opt/phpMyAdmin-5.1.1-all-languages exists
缺点:
不支持特殊字符

shell模块

shell模块可以帮助我们在远程主机上执行命令,而且可以支持特殊字符,因为shell模块在远程主机上执行命令时,会经过远程主机上的/bin/bash解释器
参数:
chdir : 执行命令前,切换到该目录
creates	: 当该文件存在时,则不执行该步骤
removves : 当该文件存在时,则执行该步骤
executable : 默认情况下远程主机中的默认shell是bash,如果需要指定其他的shell执行命令,则可以使用此参数指定某种类型的shell去执行对应的命令,指定shell文件时,需要使用绝对路径
案例:
[root@localhost ~]# ansible web01 -m shell -a "chdir=/opt   ls"
172.16.1.26 | CHANGED | rc=0 >>
phpMyAdmin-5.1.1-all-languages
test
[root@master ~]# ansible web -m shell -a "executable=/bin/sh   ps -ef | awk '{print \$1}'"

script模块

script模块可以帮助我们在远程主机上执行在Ansible主机上管理的脚本
参数:
chdir : 执行命令前,切换到该目录
creates	: 当该文件存在时,则不执行该步骤
removves : 当该文件存在时,则执行该步骤
案例:
ansible web01 -m script -a "chdir=/opt ./1.sh"
172.16.1.7 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 172.16.1.101 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 172.16.1.101 closed."
    ], 
    "stdout": "total 4\r\ndrwxr-xr-x.  4 root  root    56 Aug 26 23:37 .\r\ndr-xr-xr-x. 17 root  root   224 Aug 21 19:09 ..\r\ndrwxrwxrwx. 13 nginx nginx 4096 Aug 22 20:17 phpMyAdmin-5.1.1-all-languages\r\ndrwxr-xr-x.  2 root  root     6 Aug 26 23:37 test\r\n", 
    "stdout_lines": [
        "total 4", 
        "drwxr-xr-x.  4 root  root    56 Aug 28 13:47 .", 
        "dr-xr-xr-x. 17 root  root   224 Aug 21 19:09 ..", 
        "drwxrwxrwx. 13 nginx nginx 4096 Aug 22 20:17 phpMyAdmin-5.1.1-all-languages", 
        "drwxr-xr-x.  2 root  root     6 Aug 28 13:47 test"
    ]
}

yum模块

yum模块可以帮助我们在远程主机上通过yum源管理安装软件包
参数:
# name:必要参数,用于指定需要管理的软件包,比如 nginx
    state参数 :用于指定软件包的状态 ,默认值为present
    present:表示确保软件包已经安装
    installed 与 present 等效
    latest 表示安装 yum 源中最新的版本
    absent 和 removed 等效,表示删除对应的软件包
# disable_gpg_check参数:用于禁用对 rpm 包的公钥 gpg 验证。默认值为 no,表示不禁用验证,设置为 yes 表示禁用验证,即不验证包,直接安装
# enablerepo参数:用于指定安装软件包时临时启用的 yum 源
# disablerepo参数:用于指定安装软件包时临时禁用的 yum 源
案例:
ansible ansible-demo3 -m yum -a 'name=nginx disable_gpg_check=yes'
ansible ansible-demo3 -m yum -a 'name=nginx state=present disable_gpg_check=yes'
ansible ansible-demo3 -m yum -a 'name=nginx state=installed disable_gpg_check=yes'

ansible ansible-demo3 -m yum -a 'name=nginx state=latest disable_gpg_check=yes'

ansible ansible-demo3 -m yum -a 'name=nginx state=absent'
ansible ansible-demo3 -m yum -a 'name=nginx state=removed'

ansible ansible-demo3 -m yum -a 'name=telnet disable_gpg_check=yes enablerepo=epel'

ansible ansible-demo3 -m yum -a 'name=telnet disable_gpg_check=yes disablerepo=ngins-statle'

yum_repository 模块

yum_repository模块可以帮助我们管理远程主机上的yum源(yum仓库)
参数:
name            # yum源中 [] 里面的内容,用于指定要操作的唯一的仓库ID,也就是”.repo”配置文件中每个仓库对应的”中括号”内的仓库ID
description     # yum源中 name 部分的内容
baseurl         # yum源中 yum 仓库的地址
gpgcheck        # yum源中 gpgcheck,是否检查启用包验证功能
enabled         # yum源中的 enabled,是否开启yum源
file            # yum源的文件名字
stat		   # 默认值为 present,当值设置为 absent 时,表示删除对应的 yum 源
案例:
[root@master ~]# ansible ansible-demo3 -m yum_repository -a 'name=aliEpel description="alibaba EPEL" baseurl=https://mirrors.aliyun.com/epel/$releasever\Server/$basearch/'
ansible-demo3 | SUCCESS => {
    "changed": true, 
    "repo": "aliEpel", 
    "state": "present"
}
ansible db -m yum_repository -a "name=local baseurl=https://mirrors.aliyun.com/pypi/simple/ description=简介 file=local enabled=no gpgcheck=no state=absent"

copy模块

copy 模块的作用就是拷贝文件(拷贝到远程主机)
参数:
src         # 文件的源地址
dest        # 目标地址或文件
owner       # 文da件属主
group       # 文件属组
mode        # 文件的权限
backup      # 替换的文件是否备份
content     # 直接将内容写入文件
follow      # 处理软连接
案例:
root@master ~]# ansible db -m copy -a "src=nginx_upstream_check_module-master.zip dest=/opt"

[root@master ~]# ansible db -m copy -a "content=Holle_World dest=/opt/index.html"

[root@master ~]# ansible db -m copy -a "src=nginx_upstream_check_module-master.zip dest=/opt  backup=yes owner=nginx group=mysql mode=600"

[root@master~]# ansible ansible-demo3 -m copy -a "src=/testdir/copytest dest=/testdir/ mode=0640"
ansible-demo3 | SUCCESS => {
    "changed": true, 
    "checksum": "a8d207d098d939cb0dc9df1f3a2b986d6d4499b2", 
    "dest": "/testdir/copytest", 
    "gid": 1000, 
    "group": "ding", 
    "mode": "0640", 
    "owner": "ding", 
    "path": "/testdir/copytest", 
    "secontext": "system_u:object_r:default_t:s0", 
    "size": 12, 
    "state": "file", 
    "uid": 1000
}

fetch模块

此模块可以将远程主机的文件拉取到本地主机的某一个目录下
参数:
dest:指定拉取文件到本地以后,文件存放的位置
src:指定从受管主机中拉取哪个文件
案例:
ansible web01 -m fetch -a 'src=/opt/test/test dest=/opt/'

file模块

file 模块可以帮助我们完成一些对文件的基本操作。比如,创建文件或目录、删除文件或目录、修改文件权限等
参数:
force:强制创建,需要在两种情况下强制创建软连接,一种是源文件不存在但之后会建立的情况,另一种是目标软连接已存在,需要先取消之前的软连接,然后在创建软连接,两种选项yes|no
group: 定义文件目录属性
mode:定义文件目录的权限
owner:定义文件目录的属性
path:必选项,定义文件目录的路径
recurse: 递归的设置文件的属性,只对目录有效
src:要被软连接的源文件的路径,只适用于state=link的情况dest:被连接到的路径,,只适用于state=link的情况
state:状态
  - directory:如果目录不存在,创建目录
  - file:即使文件不存在,也不会被创建
  - link:创建软连接
  - hard:创建硬链接
  - touch:如果文件不存在时候,则则会创建一个新文件,如存在文件目录,则更新最后修改时间
  - absent:删除目录文件或者取消连接文件
案例:
# 创建目录
[root@master ~]# ansible db -m file -a "path=/opt/test state=directory"

# 创建软连接
[root@master ~]# ansible db -m file -a "src=/opt/test dest=/opt/ttt state=link "
[root@master ~]# ansible db -m file -a "path=/opt/1.txt state=touch"
[root@master ~]# ansible db -m file -a "path=/opt/1.txt state=absent"
[root@master ~]# ansible db -m file -a "path=/opt/ttt state=absent"
root@master ~]# ansible db -m file -a "path=/opt/1.txt state=touch group=nginx owner=mysql mode=600"

# 强制创建软链接
[root@master ~]# ansible db -m file -a "src=/opt/2.txt dest=/opt/txt state=link force=yes"

# 递归设置权限
[root@master ~]# ansible db -m file -a "path=/opt/test group=mysql owner=nginx mode=700 recurse=yes"
文件做软连接 ansible -i ansiblepy.py test22 -m file -a "src=/root/aa dest=/root/ansTest/ttt state=link"
创建文件  ansible -i ansiblepy.py test22 -m file -a "path=/root/kk directory=touch"
创建目录 ansible -i ansiblepy.py test22 -m file -a "path=/root/kkk state=directory"
删除目录文件或者软连接(state=absent | directory)   ansible -i ansiblepy.py test22 -m file -a "path=/root/kk state=absent"

get_url模块

用于将文件或软件从http、https或ftp下载到本地节点上或被管理机节点上
参数:
dest : 下载到哪里(绝对路径),如果目标是一个目录,就用服务器上面文件的名称,如果目标设置了名称就用目标设置的名称。
owner:指定属主
group:指定属组
mode:指定权限、
force : 如果yes,dest不是目录,将每次下载文件,如果内容改变,替换文件。如果no,则只有在目标不存在时才会下载该文件。
sha256sum : 如果将SHA-256校验和传递给此参数,目标文件的摘要将在下载后计算,以确保其完整性
url : HTTP,HTTPS或FTP URL(http | https | ftp)
url_password : 用于HTTP基本认证的密码。 如果未指定url_username参数,则不会使用url_password参数。
url_username : 用于HTTP基本认证的用户名。 对于允许空密码的站点,此参数可以不使用`url_password`
validate_certs :如果“no”,SSL证书将不会被验证, 这只能使用自签名证书在个人控制的网站上使用
案例:
# 下载promertheus
[root@master ~]# ansible db -m get_url -a "dest=/opt/ owner=mysql group=nginx mode=600 url=http://106.13.81.75/prometheus-2.25.0.linux-amd64.tar.gz"

# 增加sha256sum验证
[root@master ~]# ansible db -m get_url -a "dest=/opt/ owner=mysql group=nginx mode=600 url=http://106.13.81.75/prometheus-2.25.0.linux-amd64.tar.gz sha256sum=d163e41c56197425405e836222721ace8def3f120689fe352725fe5e3ba1a69d"

service模块

service 模块可以帮助我们管理远程主机上的服务。比如启动或停止远程主机中的 nginx 服务
参数:
name参数:此参数用于指定需要操作的服务名称,比如 nginx
- state参数:此参数用于指定服务的状态,比如,我们想要启动远程主机中的 nginx,则可以将 state 的值设置为 started;如果想要停止远程主机中的服务,则可以将 state 的值设置为 stopped。此参数的可用值有 started、stopped、restarted、reloaded。
enabled参数:此参数用于指定是否将服务设置为开机启动项,设置为 yes 表示将对应服务设置为开机启动,设置为 no 表示不会开机启动
案例:
[root@master ~]# ansible db -m service -a "name=nginx state=started enabled=yes"

[root@ansible-manager ~]# ansible ansible-demo3 -m service -a "name=nginx state=started"
ansible-demo3 | SUCCESS => {
    "changed": true, 
    "name": "nginx", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestampMonotonic": "0", 
      ......
        "WatchdogUSec": "0"
    }
}

systemd模块

systemd 模块用于控制远程主机的systemd服务,需要远程主机支持systemd,用法与service模块基本相同
参数:
name: nginx         # 服务名字
state:
    started         # 启动服务
    stopped         # 停止服务
    restarted       # 重启服务
    reloaded        # 重载服务
enabled: yes        # 开机自启
案例:
[root@centos7 ~]# ansible test -m systemd -a "name=httpd state=started"
192.168.31.66 | SUCCESS => {
    "changed": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
。。。

[root@centos7 ~]# ansible test -m systemd -a "name=httpd state=stopped"
192.168.31.66 | SUCCESS => {
    "changed": true, 
    "name": "httpd", 
    "state": "stopped", 
    "status": {
。。。

[root@centos7 ~]# ansible test -m systemd -a "name=httpd state=restarted"
192.168.31.66 | SUCCESS => {
    "changed": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
。。。

[root@centos7 ~]# ansible test -m systemd -a "name=httpd state=reloaded"
192.168.31.66 | SUCCESS => {
    "changed": true, 
    "name": "httpd", 
    "state": "started",

mount模块

没什么好说的,挂载
参数:
src : 挂载路径(NFS)
path : 挂载的路径(挂载主机的路径)
fstype : 挂载的类型
opts:挂载权限
state : 状态
  - present    	# 开机挂载,仅将挂载配置写入/etc/fstab
  - mounted    # 挂载设备,并将配置写入/etc/fstab
  - unmounted  # 卸载设备,不会清除/etc/fstab写入的配置
  - absent      # 卸载设备,会清理/etc/fstab写入的配置(会删除目录,但是目录必须为空)
  案例:
  # 挂载192.168.174.8:/data目录到test组中的主机
# ansible test -m mount -a "src=192.168.174.8:/data path=/data fstype=nfs opts=defaults state=mounted"

# 卸载,会直接删除/data目录,挂载的时候也不需要创建目标的/data目录
# ansible test -m mount -a "src=192.168.174.8:/data path=/data fstype=nfs opts=defaults state=absent"

unarchive 解压模块

解压复制远程主机上的压缩文件
参数:
copy:默认为yes,当copy=yes,那么拷贝的文件是从ansible主机复制到远程主机上的,如果设置为copy=no,那么会在远程主机上寻找src源文件
src:源路径,可以是ansible主机上的路径,也可以是远程主机上的路径,如果是远程主机上的路径,则需要设置copy=no
dest:远程主机上的目标路径
mode:设置解压缩后的文件权限
案例:
ansible db -m unarchive -a "src=node_exporter-1.1.2.linux-amd64.tar.gz dest=/opt/ mode=600 "
ansible db -m unarchive -a "src=/opt/prometheus-2.25.0.linux-amd64.tar.gz copy=no  dest=/opt/ mode=600 "
# 在远程主机上解压文件并设置权限
ansible all -m unarchive -a 'src=/srv/tomcat8/apache-tomcat-8.0.29.tar.gz dest=/usr/local copy=no mode=0755'
# 解压ansible管理机上的压缩文件到远程主机并设置权限
ansible all -m unarchive -a "src=/tmp/install/zabbix-3.0.4.tar.gz dest=/tmp/ mode=0755 copy=yes"

cron模块

cron 模块可以帮助我们管理远程主机中的计划任务,功能相当于 crontab 命令
参数:
name        # 定时任务的备注
minute      # 分钟
hour        # 小时
day         # 日
month       # 月
weekday     # 周
job         # 指定的定时任务内容
state
    present # 新建定时任务
    absent  # 删除定时任务
disabled
    yes     # 注释定时任务
    no      # 取消注释
案例:
[root@master ~]# ansible db -m cron -a "minute=5 hour=3 day=3 month=5 user=root job='echo Hello' name=job_test state=present "

[root@master ~]# ansible db -m cron -a "minute=5 hour=3 day=3 month=5 user=root job='echo World' name=job_test state=present backup=yes"
[root@master ~]# ansible db -m cron -a "minute=5 hour=*/2 day=3 month=5 user=root job='echo World' name=job_test state=present backup=yes"

[root@master ~]# ansible db -m cron -a "special_time=reboot user=root job='echo World' name=job_test state=present backup=yes"

[root@ansible-manager ~]# ansible ansible-demo3 -m cron -a " name='special time test' state=absent backup=yes "
ansible-demo3 | SUCCESS => {
    "backup_file": "/tmp/crontabiaObgL", 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "crontab test", 
        "crontab day test"
    ]
}
[root@ansible-manager ~]# ansible ansible-demo3 -m cron -a " name='special time test' special_time=reboot job='echo test' "
ansible-demo3 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "crontab test", 
        "crontab day test", 
        "special time test"
    ]
}

selinux模块

配置 SELINUX 的策略, 需要重启机器
参数:
state :状态
	- enforcing : 启用
	- permissive : 临时关闭
	- disabled : 禁用
ansible all -m selinux -a 'state=disabled'
192.168.174.7 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "configfile": "/etc/selinux/config", 
    "msg": "", 
    "policy": "targeted", 
    "reboot_required": false, 
    "state": "disabled"
}