1.安装ansible软件包

[root@centos8 ~]yum -y install ansible

2、修改配置文件

###目的:是取消每次连接远程主机时出现(yes/no)
[root@centos8 ~]#vim /etc/ssh/ssh_config
#修改下面一行
StrictHostKeyChecking no
或者
[root@centos8 ~]#vim /etc/ansible/ansible.cfg 
取消该行的注释
host_key_checking = False


3、 相关工具大多数是通过ssh协议,实现对远程主机的配置管理、应用部署、任务执行等功

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

[root@centos8 ~]#cat ssh_key.sh 
#!/bin/bash
PASS=admin
#设置网段最后的地址,4-255之间,越小扫描越快
END=254

IP=`ip a s ens160 | awk -F'[ /]+' 'NR==3{print $3}'`
NET=${IP%.*}.

rm -f /root/.ssh/id_rsa
[ -e ./SCANIP.log ] && rm -f SCANIP.log
for((i=3;i<="$END";i++));do
ping -c 1 -w 1  ${NET}$i &> /dev/null  && echo "${NET}$i" >> SCANIP.log &
done
wait

ssh-keygen -P "" -f /root/.ssh/id_rsa
rpm -q sshpass || yum -y install sshpass
sshpass -p $PASS ssh-copy-id -o StrictHostKeyChecking=no $IP 

AliveIP=(`cat SCANIP.log`)
for n in ${AliveIP[*]};do
sshpass -p $PASS scp -o StrictHostKeyChecking=no -r /root/.ssh root@${n}:
done

#把.ssh/known_hosts拷贝到所有主机,使它们第一次互相访问时不需要输入回车
for n in ${AliveIP[*]};do
scp /root/.ssh/known_hosts ${n}:.ssh/
done


ansible常用的模块和命令

ansible-doc:此工具相当于man帮助命令,可以查询每个模块的用法
##列出所有模块
[root@centos8 ~]#ansible-doc -l
##查看指定模块的用法
[root@centos8 ~]#ansible-doc -s  command
- chdir
        Change into this directory before running the command.
        [Default: (null)]
        type: path
        version_added: 0.6

- cmd
        The command to run.
        [Default: (null)]
        type: str

- creates
        A filename or (since 2.0) glob pattern. If it already exists,
        this step *won't* be run.
        [Default: (null)]
        type: path

- free_form
        The command module takes a free form command to run.
        There is no actual parameter named 'free form'.
        [Default: (null)]


ansible常用命令

格式:

ansible 主机名(主机名清单中的组名) -m (模块) -a 
--version #显示版本
##-m module #指定模块,默认为command
##--list-hosts #显示主机列表,可简写 --list
注意:ansible -all/组名 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时的口令
-f FORKS, --forks FORKS #指定并发同时执行ansible任务的主机数
注意:标注#号都是常用命令

修改默认的模块

[root@centos8 ~]#vim /etc/ansible/ansible.cfg 
修改该行
#module_name = command

ansible命令的执行过程

1、加载自己的配置文件

2、加载自己对应的模块文件

 3、通过ansible将模块或命令生成对应的临时py文件,并将该文件传输至远程服务器的对应执行用户
$HOME/.ansible/tmp/ansible-tmp-数字/XXX.PY文件
4、给ansible的文件+x执行权限  
5、执行并返回结果
6、删除临时py文件,退出

常用的颜色判断

绿色:执行成功并且不需要做改变的操作

黄色:执行成功并且对目标主机做变更

红色:执行失败

常用模块

1、command:在远程主机执行命令,此为默认模块,可忽略-m选项
不支持重定向(<>)不支持管道符(|)等,可以用shell模块实现这行功能
##command模块
[root@centos8 ~]#ansible 172.17.8.18 -a 'echo hello > /data/f1.txt '
172.17.8.18 | CHANGED | rc=0 >>
hello > /data/f1.txt
##shell模块(升级版的command)
[root@centos8 ~]#ansible 172.17.8.18 -m shell -a 'echo hello > /data/f1.txt '
172.17.8.18 | CHANGED | rc=0 >>

[root@centos8 ~]#ansible 172.17.8.18 -m shell -a 'cat /data/f1.txt '
172.17.8.18 | CHANGED | rc=0 >>
hello

此模块不具有等幂性(无论命令执行多少次,结果都没有发生改变)

(1)chdir:执行命令前请切换到该路径下
##相当于执行cat /etc/centos-release
[root@centos8 ~]#ansible all -a 'chdir=/etc   cat centos-release '
172.17.8.7 | CHANGED | rc=0 >>
CentOS Linux release 7.2.1511 (Core) 
172.17.8.28 | CHANGED | rc=0 >>
CentOS Linux release 8.0.1905 (Core) 
172.17.8.38 | CHANGED | rc=0 >>
CentOS Linux release 8.0.1905 (Core) 
172.17.8.18 | CHANGED | rc=0 >>
CentOS Linux release 8.0.1905 (Core) 
(2)creates
##如果/data/f1.txt文件存在就执行cat /etc/centos-release
[root@centos8 ~]#ansible 172.17.8.7 -a 'chdir=/etc creates=/data/f1.txt  cat centos-release ' 
172.17.8.7 | SUCCESS | rc=0 >>
skipped, since /data/f1.txt exists
##如果/data/f2.txt文件不存在就执行cat /etc/centos-release
[root@centos8 ~]#ansible 172.17.8.7 -a 'chdir=/etc creates=/data/f2.txt  cat centos-release ' 
172.17.8.7 | CHANGED | rc=0 >>
CentOS Linux release 7.2.1511 (Core) 

(3)removes(和creates类似)
[root@centos8 ~]#ansible 172.17.8.7 -a 'chdir=/etc removes=/data/f3.txt  cat centos-release '
172.17.8.7 | SUCCESS | rc=0 >>
skipped, since /data/f3.txt does not exist
[root@centos8 ~]#ansible all -a 'chdir=/etc removes=/data/f1.txt  cat centos-release '
172.17.8.7 | CHANGED | rc=0 >>
CentOS Linux release 7.2.1511 (Core)


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

3、script模块:在远程主机上运行ansible服务器上的脚本(无需执行权限)

[root@centos8 ~]#ansible websrvs -m script -a /data/test.sh

4、copy 模块:从ansible服务器主控制端复制文件到远程主机
注意:src=file如果是没有指明路径,则为当前目录或当前目录下的files目录下的file文件

#如目标存在,默认覆盖,此处指定先备份
[root@centos8 ~]#
ansible websrvs -m copy -a "src=/root/test1.sh dest=/tmp/test2.sh owner=wang
mode=600 backup=yes"
#指定内容,直接生成目标文件
[root@centos8 ~]#
ansible websrvs -m copy -a "content='test line1\ntest line2\n'
dest=/tmp/test.txt"
#复制/data目录自身,注意/data/后面没有/
[root@centos8 ~]#touch /data/f{1..4}.log
[root@centos8 ~]# ansible 172.17.8.18 -m copy -a "src=/data/  dest=/tmp"
[root@centos8 tmp]#ls
data  
#复制/data/下的文件,不包括/data/目录自身,注意/data/后面有/
[root@centos8 ~]#
ansible websrvs -m copy -a "src=/data/ dest=/backup"
[root@centos8 tmp]#ls
f1.log  f2.log  f4.log  vmware-root_796-2991202916
etc   f1.txt  f3.log  source

5、 Get_url 模块 : 用于将文件从http、https或ftp下载到被管理机节点上
url: 下载文件的URL,支持HTTP,HTTPS或FTP协议
dest: 下载到目标路径(绝对路径),如果目标是一个目录,就用服务器上面文件的名称,如果目标设置了名
称就用目标设置的名称
owner:指定属主
group:指定属组
mode:指定权限
force: 如果yes,dest不是目录,将每次下载文件,如果内容改变,替换文件。如果否,则只有在目标不存
在时才会下载该文件
checksum: 对目标文件在下载后计算摘要,以确保其完整性

[root@ansible ~]#ansible websrvs -m get_url -a
'url=http://nginx.org/download/nginx-1.18.0.tar.gz
dest=/usr/local/src/nginx.tar.gz
checksum="md5:b2d33d24d89b8b1f87ff5d251aa27eb8"

6、 Fetch 模块 : 从远程主机提取文件至ansible的主控端,copy相反,目前不支持目录

[root@centos8 ~]#
ansible websrvs -m fetch -a 'src=/root/test.sh dest=/data/scripts'
[root@ansible ~]#ansible all -m fetch -a 'src=/etc/redhat-release
dest=/data/os'
[root@centos8 ~]#tree /data/os/
/data/os/
├── 10.0.0.6
│ └── etc
│ └── redhat-release
├── 10.0.0.7
│ └── etc
│ └── redhat-release
└── 10.0.0.8
└── etc
└── redhat-release
6 directories, 3 files

7、 File 模块 : 设置文件属性,创建软链接等

##创建空文件
[root@centos8 ~]# ansible 172.17.8.18 -m copy -a "src=/data  dest=/tmp"
[root@centos8 ~]#ansible 172.17.8.18 -a "ls -ld /data/test.txt"
172.17.8.18 | CHANGED | rc=0 >>
-rw-r--r--. 1 root root 0 Dec  3 21:08 /data/test.txt
##删除文件
[root@centos8 ~]#ansible 172.17.8.18 -m file -a "path=/data/test.txt state=absent"
ansible all -m file -a "path=/root/test.sh owner=wang mode=755"
#创建目录
ansible all -m file -a "path=/data/mysql state=directory owner=mysql
group=mysql"
#创建软链接
ansible all -m file -a 'src=/data/testfile path|dest|name=/data/testfile-link
state=link'
#创建目录
ansible all -m file -a 'path=/data/testdir state=directory'
#递归修改目录属性,但不递归至子目录
ansible all -m file -a "path=/data/mysql state=directory owner=mysql
group=mysql"
#递归修改目录及子目录的属性
ansible all -m file -a "path=/data/mysql state=directory owner=mysql group=mysql
recurse=yes

8、stat模块:检查文件系统的状态(非常重要)
选项
path:文件/对象的完整路径(必须)
常用的返回值判断
exists: 判断是否存在
isuid: 调用用户的ID与所有者ID是否匹配

root@ansible ~]#ansible 127.0.0.1 -m stat -a 'path=/etc/passwd'
127.0.0.1 | SUCCESS => {
"changed": false,
"stat": {
"atime": 1614601466.7493012,
"attr_flags": "",
"attributes": [],
"block_size": 4096,
"blocks": 8,
"charset": "us-ascii",
"checksum": "8f7a9a996d24de98bf1eab4a047f8e89e9c708cf",
"ctime": 1614334259.4498665,

**9、unarchive模块:解包解压缩
实现有两种用法:

1、将ansible主机上的压缩包传到远程主机后解压缩至特定目录,设置copy=yes,此为默认值,可省略
2、将远程主机上的某个压缩包解压缩到指定路径下,设置copy  
copy:默认为yes,当copy=yes,拷贝的文件是从ansible主机复制到远程主机上,如果设置为copy=no,
会在远程主机上寻找src源文件
remote_src:和copy功能一样且互斥,yes表示在远程主机,不在ansible主机,no表示文件在ansible
主机上
src:源路径,可以是ansible主机上的路径,也可以是远程主机(被管理端或者第三方主机)上的路径,如果
是远程主机上的路径,则需要设置copy=no
dest:远程主机上的目标路径
mode:设置解压缩后的文件权限**
[root@centos8 ~]#ansible all -m unarchive -a 'src=/data/foo.tgz dest=/var/lib/foo owner=wang
group=bin'
[root@centos8 ~]#ansible all -m unarchive -a 'src=/tmp/foo.zip dest=/data copy=no mode=0777'
[root@centos8 ~]#ansible all -m unarchive -a 'src=https://example.com/example.zip dest=/data
copy=no'
[root@centos8 ~]#ansible websrvs -m unarchive -a
'src=https://releases.ansible.com/ansible/ansible-2.1.6.0-0.1.rc1.tar.gz
dest=/data/ owner=root remote_src=yes'
[root@centos8 ~]#ansible websrvs -m unarchive -a 'src=http://nginx.org/download/nginx-
1.18.0.tar.gz dest=/usr/local/src/ copy=no'

10、archive:打包压缩保存在被管理节点

[root@centos8 ~]#ansible websrvs -m archive -a 'path=/var/log/ dest=/data/log.tar.bz2 format=bz2
owner=wang mode=0600'

11、hostname模块:管理主机名

[root@centos8 ~]ansible node1 -m hostname -a "name=websrv"
[root@centos8 ~]ansible 10.0.0.18 -m hostname -a 'name=node18.magedu.com'

12、cron模块:计划任务
支持时间: * 分别对应 minute,hour,day,month,weekday

#备份数据库脚本
[root@centos8 ~]#cat /root/mysql_backup.sh
#!/bin/bash
mysqldump -A -F --single-transaction --master-data=2 -q -uroot |gzip >
/data/mysql_`date +%F_%T`.sql.gz
#创建任务
ansible 10.0.0.8 -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql"
job=/root/mysql_backup.sh'
ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate ntp.aliyun.com
&>/dev/null' name=Synctime"
#禁用计划任务
ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1
&>/dev/null' name=Synctime disabled=yes"
#启用计划任务
ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1
&>/dev/null' name=Synctime disabled=no"
#删除任务
ansible websrvs -m cron -a "name='backup mysql' state=absent"
ansible websrvs -m cron -a 'state=absent name=Synctime

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

###安装httpd包
[root@centos8 ~]#ansible websrvs -m yum -a 'name=httpd state=present' 
###启用epel源进行安装
[root@centos8 ~]#ansible websrvs -m yum -a 'name=nginx state=present enablerepo=epel'
###升级除了kernel和foo开头以外的包
[root@centos8 ~]#ansible websrvs -m yum -a 'name=* state=lastest exclude=kernel*,foo*'
###删除httpd包
[root@centos8 ~]#ansible websrvs -m yum -a 'name=httpd state=absent'
[root@ansible ~]#ansible websrvs -m yum -a 'name=sl,cowsay'
###从第三方下载安装包
[root@ansible ~]#ansible websrvs -m yum -a
"name=https://mirror.tuna.tsinghua.edu.cn/zabbix/zabbix/5.2/rhel/7/x86_64/zabbixagent-5.2.5-1.el7.x86_64.rpm"
###同时安装/删除多个安装包
[root@centos8 ~]#ansible 10.0.0.100 -m apt -a
'name=bb,sl,cowsay,cmatrix,oneko,hollywood,boxes,libaa-bin,x11-apps'
[root@centos8 ~]#ansible websrvs -m apt -a 'name=rsync,psmisc state=absent‘
###查看包
[root@ansible ~]#ansible localhost -m yum -a "list=tree"

14、user模块:管理用户(passwd,user,home等)
选项:comment:诠释

##创建用户
[root@centos8 ~]#ansible all -m user -a 'name=user1 comment="test user" uid=2048 home=/app/user1
group=root'
[root@centos8 ~]#ansible all -m user -a 'name=nginx comment=nginx uid=88 group=nginx
groups="root,daemon" shell=/sbin/nologin system=yes create_home=no
home=/data/nginx non_unique=yes'
#remove=yes表示删除用户及家目录等数据,默认remove=no
[root@centos8 ~]#ansible all -m user -a 'name=nginx state=absent remove=yes'

15、group模块:管理组

#创建组
[root@centos8 ~]ansible websrvs -m group -a 'name=nginx gid=88 system=yes'
#删除组
[root@centos8 ~]ansible websrvs -m group -a 'name=nginx state=absent

16、Lineinfile 模块: 相当于sed,可以修改文件内容
如果想进行多行匹配进行替换需要使用replace模块

[root@centos8 ~]#ansible websrvs -m lineinfile -a "path=/etc/httpd/conf/httpd.conf
regexp='^Listen' line='Listen 80'"
[root@centos8 ~]#ansible all -m lineinfile -a "path=/etc/selinux/config regexp='^SELINUX='
line='SELINUX=disabled'"
[root@centos8 ~]#ansible all -m lineinfile -a 'dest=/etc/fstab state=absent regexp="^#"'

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

[root@centos8 ~]#ansible all -m replace -a "path=/etc/fstab regexp='^(UUID.*)' replace='#\1'"
[root@centos8 ~]#ansible all -m replace -a "path=/etc/fstab regexp='^#(UUID.*)' replace='\1'"

18、 reboot 模块
19、 3.4.24 debug 模块 : 此模块可以用于输出信息,并且通过 msg 定制输出的信息内容
注意: msg后面的变量有时需要加 " " 引起来

[root@centos8 ~]#ansible 10.0.0.18 -m debug
10.0.0.18 | SUCCESS => {
"msg": "Hello world!"
}
 [root@ansible ansible]#cat debug.yml
 hosts: websrvs
tasks:
- name: output Hello world
debug:
默认没有指定msg,默认输出"Hello world!"