Ansible 运维自动化(一) Ansible只需要在一台普通的服务器上运行即可,不需要在被管控的服务器上安装客户端。因为它是基于SSH的,Linux服务器离不开SSH,所以Ansible不需要为配置工作添加额外的支持。 你可以通过命令行来使用Ansible,运行Ansible的服务器这里俗称“管理节点”;通过Ansible进行管理的服务器俗称“受控节点”。

Ansible优点:
1) 轻量级,不需要去客户端安装agent,更新时,只需要在操作机上进行一次更新即可,采用SSH协议。
2) 批量任务执行可以写成脚本,而且不用分发到远程就可以执行。
3) 使用python编写的,维护更简单。
4) 支持sudo普通用户命令。

1. 安装ansible

CentOS直接使用yum安装即可,安装之前先安装epel源码。

 rpm -Uvh http://mirrors.ustc.edu.cn/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm 

 yum -y install 

2. 配置ansible

ansible默认的配置文件:

 ll /etc/ansible/    
 total 20    
 -rw-r--r-- 1 root root 8347 Jul  8 11:14 ansible.cfg  
 -rw-r--r-- 1 root root  106 Jul  8 16:45 hosts  
 drwxr-xr-x 2 root root 4096 Jul  8 11:13 roles   

ansible.cfg ansible的配置文件

hosts 定义主机,支持IP和域名,支持分组。有静态和动态之分。动态hosts后续介绍

简单的hosts:

 [test]
 172.20.9.141 ansible_ssh_user=root ansible_ssh_pass=xxxxx
 [test2]  
 172.20.9.145  ansible_ssh_user=root ansible_ssh_pass=xxxxx ansible_ssh_port=22222
 [local] 
 127.0.0.1  ansible_ssh_user=root ansible_ssh_pass=xxxxx
 [test3]
 172.16.10.125:55536  ansible_ssh_user=root ansible_ssh_pass=xxxxx
 [test4]
 172.16.10.126:55536 ansible_ssh_user=root ansible_ssh_pass=xxxxx

test 组信息
172.20.9.141 这个组里的ip
ansible_ssh_user=root ansible ssh使用root用户
ansible_ssh_pass 密码
ansible_ssh_port=22222 远程端口
免密钥配置:
做ssh密钥认证 将你ssh用户的密钥拷到组里的机器即可
这里不做演示了

3. ansible 常用模块演示

常用参数介绍

-u 以什么用户在远程主机执行命令。默认是root
-i 用来指定inventory文件即主机清单文件 默认是hosts
-m 模块 指定用哪个模块运行 默认用command模块
-a 指定模块的参数,每个模块都有相应的模块参数
-f 10指定并发数,并发量大的时候提高该值 可以修改配置文件
-k 提示输入密码

 ansible -i /etc/ansible/hosts test -u root -m command -a 'ls -l /home' -k 

 172.20.9.141 | success | rc=0 >>
 total 28
 drwxr-xr-x. 6 git       git        4096 Jul 18 21:33 git
 drwxr-xr-x. 2 gitlab_ci gitlab_ci  4096 Jul 18 18:10 gitlab_ci
 drwx------. 2 root      root      16384 Jul 18 02:13 lost+found
 drwx------. 5 www       www        4096 Jul 18 06:44 www

 ansible test -a 'ls -l /home'   这是上一条命令的简写

ansible-doc -l 查看所有自带的模块

3.1 file 模块

设置文件的属性
file模块包含如下选项:
force:需要在两种情况下强制创建软链接,一种是源文件不存在但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no
group:定义文件/目录的属组
mode:定义文件/目录的权限
owner:定义文件/目录的属主
path:必选项,定义文件/目录的路径
recurse:递归的设置文件的属性,只对目录有效
src:要被链接的源文件的路径,只应用于state=link的情况
dest:被链接到的路径,只应用于state=link的情况
state:
directory:如果目录不存在,创建目录
file:即使文件不存在,也不会被创建
link:创建软链接
hard:创建硬链接
touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
absent:删除目录、文件或者取消链接文件
示例:

 ansible test -m file -a 'src=/etc/fstab dest=/tmp/fstab state=link'        
 172.20.9.141 | success >> {    
     "changed": true,    
     "dest": "/tmp/fstab",    
     "gid": 0,    
     "group": "root",   
     "mode": "0777",    
     "owner": "root", 
     "size": 10,   
     "src": "/etc/fstab",    
     "state": "link",    
     "uid": 0  
 }



 ansible test -m file -a 'path=/tmp/abc state=directory' 
 172.20.9.141 | success >> {
     "changed": true, 
     "gid": 0, 
     "group": "root", 
     "mode": "0755", 
     "owner": "root", 
     "path": "/tmp/abc", 
     "size": 4096, 
     "state": "directory", 
     "uid": 0
 }

3.2 copy模块

复制文件到远程主机
copy模块包含如下选项:
backup:在覆盖之前将原文件备份,备份文件包含时间信息。有两个选项:yes|no
content:用于替代”src”,可以直接设定指定文件的值
dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录
directory_mode:递归的设定目录的权限,默认为系统默认权限
force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes
others:所有的file模块里的选项都可以在这里使用
src:要复制到远程主机的文件在本地的地址,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用”/“来结尾,则只复制目录里的内容,如果没有使用”/“来结尾,则包含目录在内的整个内容全部复制,类似于rsync。
validate :The validation command to run before copying into place. The path to the file to validate is passed in via ‘%s’ which must be present as in the visudo example below.
示例:

 ansible test -m copy -a "src=/root/is143 dest=/tmp/is143 owner=root group=root mode=0644"                                         
 172.20.9.141 | success >> {  
     "changed": true,    
     "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",   
     "dest": "/tmp/is143",   
     "gid": 0, 
     "group": "root", 
     "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
     "mode": "0644", 
     "owner": "root", 
     "size": 0, 
     "src": "/root/.ansible/tmp/ansible-tmp-1445325647.87-130157182838705/source", 
     "state": "file", 
     "uid": 0
 }

如果文件内容未修改 再次执行命令不会更新文件,因为比对md5值 如果要是文件内容更新 再吃运行命令才会更新文件

3.3 command模块

creates:一个文件名,当该文件存在,则该命令不执行
free_form:要执行的linux指令
chdir:在执行指令之前,先切换到该指定的目录
removes:一个文件名,当该文件不存在,则该选项不执行
executable:切换shell来执行指令,该执行路径必须是一个绝对路径

示例:

 ansible test -a 'pwd chdir=/etc'
 172.20.9.141 | success | rc=0 >>
 /etc

3.4 shell模块

和command 类似 支持管道

 [root@centos143 ~]# ansible test -m shell -a "chdir=/etc find ./ -name "hosts" -type f |awk -F'/' '{print $2}' "
 172.20.9.141 | success | rc=0 >>
 ./hosts
 ./ansible/hosts

 [root@centos143 ~]# ansible test  -a "chdir=/etc find ./ -name "hosts" -type f |awk -F'/' '{print $2}' "        
 172.20.9.141 | FAILED | rc=1 >>
 find: paths must precede expression: |awk
 Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

3.5 service模块

用于管理服务
该模块包含如下选项:
arguments:给命令行提供一些选项
enabled:是否开机启动 yes|no
name:必选项,服务名称
pattern:定义一个模式,如果通过status指令来查看服务的状态时,没有响应,就会通过ps指令在进程中根据该模式进行查找,如果匹配到,则认为该服务依然在运行
runlevel:运行级别
sleep:如果执行了restarted,在则stop和start之间沉睡几秒钟
state:对当前服务执行启动,停止、重启、重新加载等操作(started,stopped,restarted,reloaded)
示例:

 ansible test -m service -a "name=sshd state=started enabled=yes runlevel=3,5"
 172.20.9.141 | success >> {
     "changed": true, 
     "enabled": true, 
     "name": "sshd", 
     "state": "started"
 }



 ansible test -m service -a "name=network state=restarted args=eth0"
 172.20.9.141 | success >> {
     "changed": true, 
     "name": "network", 
     "state": "started"
 }

3.6 synchronize模块

使用rsync同步文件
archive
checksum
delete #yes
dest 目标目录
src 源目录
dest_port
compress=yes 开启压缩,默认为开启
existing_only: skip createing new files on receiver
links
owner
mode:(push, pull) 推送模式为拉取模式和推送模式
recursive
rsync_path
times:Preserve modification times
示例:

3.7 get_url模块

下载模块

 ansible test -m  get_url -a "dest=/tmp url=http://nginx.org/download/nginx-1.9.5.tar.gz"
 172.20.9.141 | success >> {
     "changed": true, 
     "checksum": "669f1653f539358ad1d1b8281041f962597ec637", 
     "dest": "/tmp/nginx-1.9.5.tar.gz", 
     "gid": 0, 
     "group": "root", 
     "md5sum": "2562320f1535e3e31d165e337ae94f21", 
     "mode": "0644", 
     "msg": "OK (884023 bytes)", 
     "owner": "root", 
     "sha256sum": "", 
     "size": 884023, 
     "src": "/tmp/tmpe6NYWN", 
     "state": "file", 
     "uid": 0, 
     "url": "http://nginx.org/download/nginx-1.9.5.tar.gz"
 }

3.8 script模块

远程机器执行 ansible本地脚本

 172.20.9.141 | success >> {
     "changed": true, 
     "rc": 0, 
     "stderr": "OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: auto-mux: Trying existing master
Control socket connect(/root/.ansible/cp/ansible-ssh-172.20.9.141-22-root): Connection refused
debug1: Connecting to 172.20.9.141 [172.20.9.141] port 22.
debug1: fd 3 clearing O_NONBLOCK
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: identity file /root/.ssh/identity type -1
debug1: identity file /root/.ssh/identity-cert type -1
debug1: identity file /root/.ssh/id_rsa type 1
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: identity file /root/.ssh/id_dsa type -1
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3
debug1: match: OpenSSH_5.3 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.3
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 zlib@openssh.com
debug1: kex: client->server aes128-ctr hmac-md5 zlib@openssh.com
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host '172.20.9.141' is known and matches the RSA host key.
debug1: Found key in /root/.ssh/known_hosts:2
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: password
debug1: Enabling compression at level 6.
debug1: Authentication succeeded (password).
debug1: setting up multiplex master socket
ControlSocket /root/.ansible/cp/ansible-ssh-172.20.9.141-22-root already exists, disabling multiplexing
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending env LANG = zh_CN.UTF-8
debug1: Sending command: LANG=C LC_CTYPE=C /root/.ansible/tmp/ansible-tmp-1445328794.5-82306162559014/h.sh 
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: client_input_channel_req: channel 0 rtype eow@openssh.com reply 0
debug1: channel 0: free: client-session, nchannels 1
debug1: fd 1 clearing O_NONBLOCK
debug1: fd 2 clearing O_NONBLOCK
Connection to 172.20.9.141 closed.
Transferred: sent 1832, received 2048 bytes, in 0.0 seconds
Bytes per second: sent 176371.2, received 197166.1
debug1: Exit status 0
debug1: compress outgoing: raw data 530, compressed 368, factor 0.69
debug1: compress incoming: raw data 114, compressed 92, factor 0.81
", 
     "stdout": "141.com
"
 }

还有其他常用模块本人不在一一介绍
ansible-doc 模块 -h 可查看模块帮助信息