Ansible简介
Ansible是一款简单的运维自动化工具,只需要使用ssh协议连接就可以来进行
系统管理,自动化执行命令,部署等任务。

Ansible的特点
1、ansible不需要单独安装客户端,也不需要启动任何服务
2、ansible是python中的一套完整的自动化执行任务模块
3、ansible playbook采用yaml配置,对于自动化任务执行过一目了然

Ansible组成结构
Ansible
是Ansible的命令工具,核心执行工具:一次性或临时执行的操作都是通过该命令
执行。
Ansible Playbook
任务剧本(又称任务集),编排定义Ansible任务集的配置文件,由Ansible顺序
依次执行,yaml格式。
Inventory
Ansible管理主机的清单,默认是/etc/ansible/hosts文件。
Modules
Ansible执行命令的功能模块,Ansibles2.3版本为止,共有1039个模块。还可
以自定义模块。
Plugins
插件,模块功能的补充,常有连接类型插件,循环插件,变量插件,过滤插件,插
件功能用的较少。
API
提供给第三方程序调用的应用程序编程接口。

Ansible结构图

ansible写定时任务 ansible定时任务模块_ansible写定时任务


安装Ansible

设置epel源

[root@localhost ~]#  wget -O /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
[root@localhost ~]#  yum make fast && yum clean all

使用yum安装ansible

[root@localhost ~]# yum -y install ansible

做ssh免密认证,将公钥发送给远程主机

[root@localhost ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:kXsra0jhZFJgPjdVgeCRCh/EcgwmlD2n7lB6H6oaFqc root@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
|o.==+.oo.oo.     |
| +o==ooo..       |
|   =*++ o        |
|   o+o+. o       |
| .+. = .S .      |
| o+o .o  . .     |
|.E+ o.... .      |
|.. o .. .o       |
|o..    ..        |
+----[SHA256]-----+

[root@localhost ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.100.9  ##要发送的主机
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.43.199's password:   ##主机密码

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@192.168.100.9'"
and check to make sure that only the key(s) you wanted were added.

基于秘钥连接
编写主机定义清单

[root@localhost ~]# vim /etc/ansible/hosts
[web]
192.168.100.9 

[db]
192.168.100.10

Inventory内置参数

ansible写定时任务 ansible定时任务模块_Ansible_02


Ansible Ad-hoc模式常用模块

Ansible Ad-hoc 常用模块

命令相关模块

command模块:ansible默认的模块,执行命令,注意:shell中的"<“,”>“,”|“,”;“,”&“,”$"等特殊字符不能在command模块中使用,如果需要则用shell模块

查看模块参数

[root@localhost ~]# ansible-doc -s command

案例1
在远程服务器上面执行ls命令,默认是在当前用户的家目录/root

[root@localhost ~]# ansible web -a 'ls'

chdir先切换工作目录,在执行后面的命令,一般在编译的情况下使用

[root@localhost ~]# ansible web -a 'chdir=/tmp pwd'

creates如果creates的文件存在,则不执行后面的操作

[root@localhost ~]# ansible web -a 'creates=/tmp ls /etc/passwd'

removes和creates相反,如果removes的文件存在,才执行后面的操作

[root@localhost ~]# ansible web -a 'removes=/tmp ls /etc/passwd'
192.168.43.199 | CHANGED | rc=0 >>
/etc/passwd

shell模块
专门用来执行shell命令的模块,和command模块一样,参数基本一样都有chdir,creates,removes等参数
查看模块参数

[root@localhost ~]# ansible-doc -s shell
[root@localhost ~]# ansible web -m shell -a 'mkdir /tmp/test'
[root@localhost ~]# ansible web -m shell -a 'ls /tmp'

script模块
用于在被管理机器上面执行shell脚本的模块,脚本无需再被管理机器上面存在
查看模块参数

[root@localhost ~]# ansible-doc -s script

编写shell脚本

[root@localhost ~]# vim ansible_test.sh
echo "hostnam"

在所有被管理机器上执行改脚本

[root@localhost ~]# ansible web -m script -a '/root/ansible_test.sh'

文件相关的模块
file
用于对文件的处理,创建,删除,权限控制等
查看模块参数

[root@localhost ~]# ansible-doc -s file
path        #要管理的文件路径
recurse     #递归
state:
directory   #创建目录,如果目标不存在则创建目录及其子目录
touch       #创建文件,如果文件存在,则修改文件属性
absent      #删除文件和目录
mode        #设置文件或目录权限
owner       #设置文件或目录属主信息
group       #设置文件或目录属组信息
link        #创建软连接,需要和src配合使用
hard        #创建硬连接,需要和src配合使用

创建目录

[root@localhost ~]# ansible web -m file -a 'path=/tmp/test state=directory'

创建文件

[root@localhost ~]# ansible web -m file -a 'path=/tmp/test state=touch'

建立软连接(src表示源文件,path表示目标文件)

[root@localhost ~]# ansible web -m file -a 'src=/tmp/test1 path=/tmp/test3 state=link'

删除文件

[root@localhost ~]# ansible web -m file -a 'path=/tmp/test state=absent'

创建文件时同时设置权限等信息

[root@localhost ~]# ansible web -m file -a 'path=/tmp/test state=directory mode=755 owner=root group=root'

copy模块
用于管理端复制文件到远程主机,并可以设置权限,属组,属主等
查看模块参数

[root@localhost ~]# ansible-doc -s copy
src        #需要copy的文件的源路径
dest       #需要copy的文件的目标路径
backup     #对copy的文件进行备份
content    #直接在远程主机被管理文件中添加内容,会覆盖源文件内容
mode       #对copy到远端的文件设置权限
owner      #对copy到远端的文件设置属主
group      #对copy到远端文件设置属组

复制文件到远程主机并改名

[root@localhost ~]# ansible web -m copy -a 'src=/root/ansible_test.sh dest=/tmp/a.sh'

复制文件到远程主机,并备份远程文件,安装时间信息备份文件(当更新文件内容后,重新copy时用到)

[root@localhost ~]# ansible web -m copy -a 'dest=/tmp/a.sh src=/root/ansible_test.sh backup=yes'

直接在远程主机a.sh中添加内容

[root@localhost ~]# ansible web -m copy -a 'content="/bin/bash\n echo 'uptime' dest=/root/a.sh"'

复制文件到远程主机,并设置权限及属主属组

[root@localhost ~]# ansible web -m copy -a 'dest=/tmp/passwd src=/etc/passwd mode=700 owner=root group=root'

fetch模块
用于被管理机上面拉取文件,拉取下来的内容会保留目录结构,一般情况用在收集被管理机器的日志文件等
查看模块参数

[root@localhost ~]# ansible-doc -s fetch
src  #指定需要从远端机器拉取的文件路径
dest #指定从远端机器拉取下来的文件存放路径

从被管理机器上拉取cron日志文件,默认会已管理节点地址创建一个目录,并存放在内

[root@localhost ~]# ansible web -m fetch -a 'dest=/tmp src=/var/log/cron'

用户相关的模块
user模块
用于对系统用户的管理,用户的创建、删除、家目录、属组等设置
查看模块参数

[root@localhost ~]# ansible-doc -s user
name   #指定用户的名字
home   #指定用户的家目录
uid    #指定用户的uid
group  #指定用户的用户组
groups #指定用户的附加组
password #指定用户的密码
shell   #指定用户的登录shell
create_home #是否创建用户家目录,默认是yes
remove  #删除用户时,指定是否删除家目录
state:
      absent #删除用户

创建用户名指定家目录,指定uid及组

[root@localhost ~]# ansible web -m user -a 'name=nginx home=/opt/nginx uid=1002 group=root'

创建用户,不创建家目录,并且不能登录

[root@localhost ~]# ansible web -m user -a 'name=mysql shell=/bin/nologin uid=1003 create_home=no'

删除用户

[root@localhost ~]# ansible web -m user -a 'name=nginx state=absent'

删除用户并删除家目录

[root@localhost ~]# ansible web -m user -a 'name=nginx state=absent remove=yes'

group模块
用于创建组,当前创建用户时如果需要指定组,组不存在的话就可以通过group先创建组
查看模块参数

[root@localhost ~]# ansible-doc -s group
name  #指定组的名字
gid   #指定组的gid
state:
     absent    #删除组
     present   #创建组(默认的状态)
[root@localhost ~]# ansible web -m group -a 'name=www'

创建组并指定gid

[root@localhost ~]# ansible web -m group -a 'name=www gid=1005'

删除组

[root@localhost ~]# ansible web -m group -a 'name=www state=absent'

yum_repository
file参数:此参数用于设置仓库的配置文件名称,即设置”.repo”配置文件的
文件名前缀,在不使用此参数的情况下,默认以name参数的仓库ID作为”.repo”
配置文件的文件名前缀,同一个”.repo”配置文件中可以存在多个yum源。

enabled参数:此参数用于设置是否激活对应的yum源,此参数默认值为yes,
表示启用对应的yum源,设置为no表示不启用对应的yum源。

gpgcheck参数:此参数用于设置是否开启rpm包验证功能,默认值为no,表
示不启用包验证,设置为yes表示开启包验证功能。

gpgcakey参数:当gpgcheck参数设置为yes时,需要使用此参数指定验证包
所需的公钥。

state参数:默认值为present,当值设置为absent时,表示删除对应的yum
源。

在web主机上设置ID为aliEpel的yum源,仓库配置文件路径为/etc/yum.repos.d/yum.repo

[root@localhost ~]# ansible all -m yum_repository -a 'name=local description="local" baserul=file:///mnt enabled=1 gpgcheck=no file=yum'

立即挂载

[root@localhost ~]# absible all -m mount -a 'src=/dev/cdrom path=/mnt fstype=iso9660 state=mounted'

永久挂载

[root@localhost ~]# absible all -m mount -a 'src=/dev/cdrom path=/mnt fstype=iso9660 state=present'

软件包相关的模块
yum
用于对软件包的管理,下载,安装,卸载,升级等操作

[root@localhost ~]# ansible-doc -s yum
name          #指定要操作的软件包名字
download_dir  #指定下载软件包的存放路径,需要配合download_only一起使用
download_only #只下载软件包,而不进行安装,和yum-downloadonly一样
list:
installed     #列出所有已安装的软件包
updates       #列出所有可以更新的软件包
repos         #列出所有的yum仓库
state:
installed,present  #安装软件包(两者任选其一都可以)
removed,absent  #卸载软件包
latest       #安装最新软件包

列出所有已安装的软件包

[root@localhost ~]# ansible web -m yum -a 'list=installed'

列出所有可更新的软件包

[root@localhost ~]# ansible web -m yum -a 'list=updates'

列出所有的yum仓库

[root@localhost ~]# ansible web -m yum -a 'list=repos'

安装软件包

[root@localhost ~]# ansible web -m yum -a 'name=httpd state=installed'

卸载软件包

[root@localhost ~]# ansible web -m yum -a 'name=httpd state=removed'

安装包组,类似yum groupinstall ‘Development Tools’

[root@localhost ~]# ansible web -m yum -a 'name="@Development Tools" state=installed'

Service systemd
服务模块,用于对服务进行管理,服务的启动、关闭、开机自启等

#查看模块参数
[root@ansible ]ansible-doc -s service
name     #指定需要管理的服务名
enabled  #指定是否开机自启动
state:   #指定服务状态
started  #启动服务
stopped  #停止服务
restarted #重启服务
reloaded  #重载服务

启动服务,并设置开机自启动

[root@localhost ~]# ansible web -m systemd -a 'name=httpd state=started enabled=yes'

关闭服务

[root@localhost ~]# ansible web -m systemd -a 'name=httpd state=stopped'

计划任务相关模块
cron 用于指定计划任务,和crontab-e一样
#查看模块参数

[root@localhost ~]#ansible-doc -s cron
job           #指定需要执行的任务
minute     #分钟
hour        #小时
day         #天
month     #月
weekday #周
name     #对计划任务进行描述
state:
absent   #删除计划任务

创建一个任务计划,并描述是干嘛用的

[root@localhost ~]# ansible web -m cron -a "name='任务计划' minute=* hour=* day=* month=* wekday=* job='/bin/bash /root/test.sh'"

[root@localhost ~]# ansible web -m shell -a 'crontab -l'

删除任务计划

[root@localhost ~]# ansible web -m cron -a "name='任务计划' job='/bin/sh /root/test.sh' state=absent"

系统信息相关的模块
setup
用于获取系统信息的一个模块
查看模块参数

[root@localhost ~]# ansible-doc -s setup

查看系统所有信息

[root@localhost ~]# ansible web -m setup

常用的模块信息

#常见的过滤选项
ansible_all_ipv4_addresses            仅显示ipv4的信息。
ansible_devices                       仅显示磁盘设备信息。
ansible_distribution                  显示是什么系统,例:centos,suse等。
ansible_distribution_major_version    显示是系统主版本。
ansible_distribution_version          仅显示系统版本。
ansible_machine                       显示系统类型,例:32位,还是64位。
ansible_eth0                          仅显示eth0的信息。
ansible_hostname                      仅显示主机名。
ansible_kernel                        仅显示内核版本。
ansible_lvm                           显示lvm相关信息。
ansible_memtotal_mb                   显示系统总内存。
ansible_memfree_mb                    显示可用系统内存。
ansible_memory_mb                     详细显示内存情况。
ansible_swaptotal_mb                  显示总的swap内存。
ansible_swapfree_mb                   显示swap内存的可用内存。
ansible_mounts                        显示系统磁盘挂载情况。
ansible_processor                     显示cpu个数(具体显示每个cpu的型号)。
ansible_processor_vcpus               显示cpu个数(只显示总的个数)。

filter对系统信息进行过滤

[root@localhost ~]# ansible web -m setup -a 'filter=ansible_all_ipv4_addresses'

find模块

**查看find参数**
[root@localhost ~]# ansible-doc -s find

paths参数 :必须参数,指定在哪个目录中查找文件,可以指定多个路径,路径间用逗号隔开,此参数有别名,使用别名 path 或者别名 name 可以代替 paths。

recurse参数 : 默认情况下,只会在指定的目录中查找文件,也就是说,如果目录中还包含目录,ansible 并不会递归的进入子目录查找对应文件,如果想要递归的查找文件,需要使用 recurse 参数,当 recurse 参数设置为 yes 时,表示在指定目录中递归的查找文件。

hidden参数 :默认情况下,隐藏文件会被忽略,当 hidden 参数的值设置为 yes 时,才会查找隐藏文件。

file_type参数 : 默认情况下,ansible 只会根据条件查找”文件”,并不会查找”目录”或”软链接”等文件类型,如果想要指定查找的文件类型,可以通过 file_type 指定文件类型,可指定的文件类型有 any、directory、file、link 四种。

patterns参数 : 使用此参数指定需要查找的文件名称,支持使用 shell(比如通配符)或者正则表达式去匹配文件名称,默认情况下,使用 shell 匹配对应的文件名,如果想要使用 python 的正则去匹配文件名,需要将 use_regex 参数的值设置为 yes。

use_regex参数:默认情况下,find 模块不会使用正则表达式去解析 patterns 参数中对应的内容,当 use_regex 设置为 yes 时,表示使用 python 正则解析 patterns 参数中的表达式,否则,使用 glob 通配符解析 patterns 参数中的表达式。

contains参数:使用此参数可以根据文章内容查找文件,此参数的值为一个正则表达式,find 模块会根据对应的正则表达式匹配文件内容。

age参数 :使用此参数可以根据时间范围查找文件,默认以文件的 mtime 为准与指定的时间进行对比,比如,如果想要查找 mtime 在3天之前的文件,那么可以设置 age=3d,如果想要查找 mtime 在3天以内的文件,可以设置 age=-3d,这里所说的3天是按照当前时间往前推3天,可以使用的单位有秒(s)、分(m)、时(h)、天(d)、星期(w)。

age_stamp参数 :文件的时间属性中有三个时间种类,atime、ctime、mtime,当我们根据时间范围查找文件时,可以指定以哪个时间种类为准,当根据时间查找文件时,默认以 mtime 为准。

size参数 :使用此参数可以根据文件大小查找文件,比如,如果想要查找大于3M的文件,那么可以设置 size=3m,如果想要查找小于50k的文件,可以设置 size=-50k,可以使用的单位有 t、g、m、k、b。

get_checksum参数 :当有符合查找条件的文件被找到时,会同时返回对应文件的 sha1校验码,如果要查找的文件比较大,那么生成校验码的时间会比较长。

示例
在 ansible-demo3 主机的 /testdir目录中查找文件内容中包含 abc 字符串的文件,隐藏文件会被忽略,不会进行递归查找。

ansible ansible-demo3 -m find -a 'paths=/testdir contains=".*abc.*" '

在 ansible-demo3 主机的 /testdir 目录以及其子目录中查找文件内容中包含 abc 字符串的文件,隐藏文件会被忽略。

ansible ansible-demo3 -m find -a 'paths=/testdir contains=".*abc.*" recurse=yes '

在 ansible-demo3 主机的 /testdir 目录中查找以 .sh 结尾的文件,包括隐藏文件,但是不包括目录或其他文件类型,不会进行递归查找。

ansible ansible-demo3 -m find -a 'paths=/testdir patterns="*.sh" hidden=yes'

在 ansible-demo3 主机的 /testdir 目录中查找以 .sh 结尾的文件,包括隐藏文件,包括所有文件类型,比如文件、目录、或者软链接,但是不会进行递归查找。

ansible ansible-demo3 -m find -a 'paths=/testdir patterns="*.sh" file_type=any hidden=yes'

在 ansible-demo3 主机的 /testdir 目录中查找以 .sh 结尾的文件,只不过 patterns 对应的表达式为正则表达式,查找范围包括隐藏文件,包括所有文件类型,但是不会进行递归查找,不会对 /testdir 目录的子目录进行查找

ansible ansible-demo3 -m find -a 'paths=/testdir patterns=".*\.sh" use_regex=yes file_type=any hidden=yes'

在 ansible-demo3 主机的 /testdir 目录中以及其子目录中查找 mtime 在1天以内的文件,不包含隐藏文件,不包含目录或软链接文件等文件类型。

ansible ansible-demo3 -m find -a "path=/testdir age=-1d recurse=yes"

在 ansible-demo3 主机的 /testdir 目录中以及其子目录中查找大于 2g 的文件,不包含隐藏文件,不包含目录或软链接文件等文件类型。

ansible ansible-demo3 -m find -a "paths=/testdir size=2g recurse=yes"

在 ansible-demo3 主机的 /testdir 目录中以及其子目录中查找以 .sh 结尾的文件,并且返回符合条件文件的 sha1 校验码,包括隐藏文件。

ansible ansible-demo3 -m find -a "paths=/testdir patterns=*.sh get_checksum=yes hidden=yes recurse=yes"