今天给大家介绍另外一款自动化运维工具:Ansible

Ansible自动化工具只需要在一台机器上安装,其他机器不需要安装任何东西,这就是ansible比puppet, saltstck方便的地方。ansible的特点有哪些呢?下面为你逐个介绍:

特点:

(1)、轻量级,无需在客户端安装agent,更新时,只需在操作机上进行一次更新即可;

(2)、批量任务执行可以写成脚本,而且不用分发到远程就可以执行;

(3)、使用python编写,维护更简单;

(4)、基于SSH工作;

(5)、支持文件同步并且对修改之前的文件进行备份,支持回滚;

        好了,下面我们开始安装ansible:首先得准备好安装环境

我这里准备了两台机器: 

    server1: 192.168.1.231  

    server2: 192.168.1.232

一、安装准备

#在server1上部署 

#关闭防火墙iptables 

service iptables stop 

chkconfig iptables off 


#并且修改SELINUX=disabled 

sed -i's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config


#使用yum安装python等软件 

 yum install PyYAML.x86_64 python-paramiko.noarch python-jinja2.x86_64 python-devel –y


二、下载安装包

#下载ansible和setuptools安装包 

wget ​​https://pypi.python.org/packages/source/a/ansible/ansible-1.7.2.tar.gz​​​ 

wget ​​https://pypi.python.org/packages/source/s/setuptools/setuptools-7.0.tar.gz​​​

三、解压安装软件

#解压安装setuptools 

tar zfxv setuptools-7.0.tar.gz 

cd setuptools-7.0 

python setup.py install

cd .. 


#解压安装ansible 

tar fzvx ansible-1.7.2.tar.gz  

cd ansible-1.7.2 

python setup.py build  

python setup.py install

mkdir /etc/ansible

cp examples/ansible.cfg /etc/ansible/

cp examples/hosts /etc/ansible/

cd ..


四、修改配置文件

#配置ansible,我这里默认是不需要修改的 

vi /etc/ansible/ansible.cfg 

hostfile      = /etc/ansible/hosts

library        = /usr/share/ansible

remote_tmp    = $HOME/.ansible/tmp

pattern        = * 

forks          = 5 

poll_interval  = 15 

sudo_user      = ansible 

#ask_sudo_pass = True 

#ask_pass      = True 

transport      = smart 

remote_port    = 22 

module_lang    = C 


#修改/etc/ansible/hosts文件 

#local_Server 

[localhost] 

127.0.0.1 

#client 

[client] 

192.168.1.232  #server2的IP

五、SSH通信设置

#ssh互信 

[root@ansibleserver ~]#ssh-keygen –b 1024 -t rsa 

#不断的回车即可 

The key's randomart image is: 

+--[ RSA 2048]----+ 

|    o  o.        | 

|    +=o .      | 

|    .=+* o      | 

|      o* OE.    | 

|      .S.=      | 

|      +..      | 

|      . +        | 

|      .        | 

|                | 

+-----------------+

#然后进入.ssh/目录下 

[root@ansibleserver ~]#cd .ssh/ 

cat *.pub > authorized_keys 

chmod –R 700 . 


#再通过scp命令将authorized_keys拷贝到客户端192.168.1.232 

scp authorized_keys root@192.168.1.232:/root/.ssh/authorized_keys


#执行scp出现的错误以及解决方法: 

scp: /root/.ssh/authorized_keys: No such file or directory 

#解决方法:在客户端也直接生成一个ssh-keygen –b 124 –t rsa文件即可,这样的做法主要是生成.ssh/的目录,服务端才能够将公钥拷贝过去

#测试互信是否成功 

[root@ansibleserver ~]# ssh 192.168.1.232 

Last login: Tue Mar 17 22:56:26 2015 from 192.168.1.231 

#无需密码,直接登录成功!说明互信已经成功了! 

[root@localhost ~]# ifconfig  

eth1      Link encap:Ethernet  HWaddr 08:00:27:41:28:38  

          inetaddr:192.168.1.232 Bcast:192.168.1.255 Mask:255.255.255.0

六、模块测试

模块命令

-i 设备列表路径,可以指定一些动态路径 

-f 并发任务数 

-private-key 私钥路径 

-m 模块名称 

-M 模块夹的路径 

-a 参数 

-k 登陆密码 

-K sudo密码 

-t 输出结果保存路径 

-B 后台运行超时时间 

-P 调查后台程序时间 

-u 执行用户 

-U sudo用户 

-l 限制设备范围 

-s 是此用户sudo无需输入密码


ping模块

#使用ansible的ping模块测试client是否能够通信! 

#注意:all 代表所有client的意思 

[root@ansibleserver ~]# ansible all -m ping 

192.168.1.232 | success >> { 

    "changed": false,  

    "ping":"pong"

127.0.0.1 | success >> { 

    "changed": false,  

    "ping":"pong"


#查看时间 

[root@ansibleserver ~]# ansible all -m command -a "date" 

192.168.1.232 | success | rc=0 >> 

Tue Mar 17 23:06:43 EDT 2015 

127.0.0.1 | success | rc=0 >> 

Tue Mar 17 23:06:44 EDT 2015


安装软件测试

[root@ansibleserver ~]# ansible all -m command -a "yum install unzip -y" 

192.168.1.232 | success | rc=0 >> 

Loaded plugins: fastestmirror 

Setting up Install Process 

Determining fastest mirrors 

………… 

Installed: 

  unzip.x86_64 0:6.0-1.el6                                                      

Complete!


copy模块

#拷贝文件到远程主机 

相关选项如下: 

backup:在覆盖之前,将源文件备份,备份文件包含时间信息。有两个选项:yes|no 

content:用于替代“src”,可以直接设定指定文件的值 

dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录 

directory_mode:递归设定目录的权限,默认为系统默认权限 

force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes

others:所有的file模块里的选项都可以在这里使用 

src:被复制到远程主机的本地文件,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用“/”来结尾,则只复制目录里的内容,如果没有使用“/”来结尾,则包含目录在内的整个内容全部复制,类似于rsync。

实例:拷贝本地的/root/script目录所有内容到192.168.1.232的/tmp目录下 

注意:因为script后面没有加/ ,所以拷贝的是整个目录 

ansible 192.168.1.232 -m copy -a "src=/root/script dest=/tmp/owner=root group=root mode=0644"

#拷贝成功的返回信息 

192.168.1.232 | success >> { 

  "changed": true,  

  "dest": "/tmp/",  

  "src": "/root/script"


#切换到192.168.1.232机器中查看 

[root@localhost ~]# ls /tmp/script/ 

a.txt  b.txt 

#拷贝script目录的文件实例: 

注意:这里的script后面是加了/ ,所以只拷贝script目录下的文件 

[root@ansibleserver script]# ansible 192.168.1.232 -m copy -a"src=/root/script/ dest=/tmp/script/ owner=root group=root mode=0644" 

192.168.1.232 | success >> { 

    "changed": true,  

    "dest":"/tmp/script/",  

    "src":"/root/script"

}

在192.168.1.232的script目录下查看内容 

[root@localhost script]# ll 

total 0 

-rw-r--r-- 1 root root 0 Mar 17 23:38 a.txt 

-rw-r--r-- 1 root root 0 Mar 17 23:38 b.txt 

-rw-r--r-- 1 root root 0 Mar 1723:38 c.txt 

-rw-r--r-- 1 root root 0 Mar 1723:38 d.txt 

#backup参数:有yes|no两个选项 

ansible 192.168.1.232 -m copy -a "src=/root/script/ dest=/tmp/script/owner=root group=root mode=0644 backup=yes"

提示:例如,src和dest同时有个a.txt文件,如果在src修改了a.txt  再执行copy的时候,dest就会生成一个备份 


[root@localhost script]# ll 

total 4 

-rw-r--r-- 1 root root 12 Mar 18 03:09 a.txt 

-rw-r--r-- 1 root root  0 Mar 18 03:08 a.txt.2015-03-18@03:09~  

#因为a.txt被修改过了,所以生成了一个备份 


[root@localhost script]# cat a.txt  #这里被修改过,然后copy过来的 

hello world 

[root@localhost script]# cat a.txt.2015-03-18\@03\:09~ #备份的a.txt默认没有内容

file模块

#使用file模块,更改文件的用户和权限 

[root@ansibleserver ~]# ansible 192.168.1.232 -m file -a "dest=/tmp/a.txtmode=600" 

#查看更改情况 

[root@localhost tmp]# ll 

total 8 

-rw-------  1 root root    0 Mar 17 23:38 a.txt 


#创建目录,类似mkdir –p 

[root@ansibleserver ~]# ansible 192.168.1.232 -m file -a"dest=/tmp/to/c mode=755 owner=root group=root state=directory" 


#查看创建情况 

[root@localhost c]# pwd 

/tmp/to/c

#删除文件或者目录 

[root@ansibleserver ~]# ansible 192.168.1.232 -m file -a"dest=/tmp/a.txt state=absent" 

192.168.1.232 | success >> { 

    "changed": true,  

    "path":"/tmp/a.txt",  

    "state":"absent"


#查看删除情况 

[root@localhost tmp]# ll 

total 8 

-rw-r--r--  1 root root    0 Mar 17 23:38 b.txt 

drwxr-xr-x  2 root root 4096 Mar 1723:38 script 

drwxr-xr-x  3 root root 4096 Mar 1723:53 to 

-rw-------. 1 root root    0 Dec 2819:45 yum.log

cron模块

#注意:cron是为远程主机定义任务计划的 

#批量定义远程主机上的定时任务 

#首先我们在本地的/etc/ansible/目录下定义一个cron.yml文件 

- hosts: 192.168.1.232  #远程主机IP 

  remote_user: root    #指定执行的用户 

  tasks:                #任务 

    - name: cron      #任务名称 

      cron: name='cp file' minute=1job='/usr/bin/tmp/script/test.sh'

提示:name 为注释名称,minute为执行任务的时间间隔,job为执行的脚本 


#定义好之后,我们执行下ansible-playbook命令 

[root@ansibleserver ansible]# ansible-playbook cron.yml 

PLAY RECAP******************************************************************** 

192.168.1.232              :ok=2    changed=1    unreachable=0    failed=0 

#出现ok=2 change=1,代表已经在远程机子上做好定时任务了 


#在远程主机上查看: 

[root@ansible-client script]# crontab -l 

#Ansible: cp file 

1 * * * * /usr/bin/tmp/script/test.sh

实例2: 

目的:在指定节点上定义一个计划任务,每隔3分钟到主控端更新一次时间 

命令:ansible all-m cron -a 'name="custom job" minute=*/3 hour=* day=* month=*weekday=* job="/usr/sbin/ntpdate 172.16.254.139"'

synchronize模块

#先声明下,使用rsync 模块,远程主机系统必须安装rsync 包,否则无法使用这个模块 

#先给远程机装个rsync吧 

[root@ansibleserver ~]# ansible 192.168.1.232 -m yum -a 'name=rsyncstate=latest' 

#再次验证下rsync是否安装成功 

[root@ansibleserver ~]# ansible 192.168.1.232 -a "which rsync" 

192.168.1.232 | success | rc=0 >> 

/usr/bin/rsync

#看来没问题了!

#看下使用的参数 

[root@ansibleserver ~]# ansible-doc -s synchronize 

- name: Uses rsync to make synchronizing file paths in your playbooks quickand easy. 

action: synchronize 

archive                # 是否采用归档模式同步,即以源文件相同属性同步到目标地址 

checksum              # 是否效验 

compress              # 是否压缩 

copy_links            # 同步的时候是否复制连接 

delete                # 删除源中没有而目标存在的文件 

dest=                  # 目标地址 

dest_port              # 目标接受的端口 

dirs                  # 以非递归的方式传输目录 

existing_only          # Skipcreating new files on receiver. 

group                  # Preservegroup 

links                  # Copysymlinks as symlinks. 

mode                  # 模式,rsync 同步的方式 PUSH\PULL 

recursive              # 是否递归 yes/no 

rsync_opts            # 使用rsync 的参数 

rsync_path            # 服务的路径(源码编译时需指定) 

rsync_timeout          # Specify a--timeout for the rsync command in seconds. 

set_remote_user        # put user@for the remote paths. If you have a custom ssh config to define the remote userfor 

src=\'#\'" /pre><PRE class="brush":bash;toolbar:false>实例:将ansible端/tmp/目录下的script同步到232机子的/tmp/目录下面 

[root@ansibleserver ~]# ansible 192.168.1.232 -m synchronize -a 'src=/tmp/scriptdest=/tmp/'  

192.168.1.232 | success >> { 

    "changed": true,  

    "cmd": "rsync--delay-updates -FF --compress --archive --rsh 'ssh  -o StrictHostKeyChecking=no'--out-format='<<CHANGED>>%i %n%L' \"/tmp/script\"\"root@192.168.1.232:/tmp/\"",  

    "msg":"cd+++++++++ script/\n<f+++++++++ script/a.txt\n",  

    "rc": 0,  

    "stdout_lines": [ 

        "cd+++++++++script/",  

        "<f+++++++++script/a.txt"

    ] 

#注意:要想ansible端于远程端的文件保持一致,最好用delete=yes参数 

因为,有时候在ansible的目录下删除了某个文件,若不加delete=yes参数的话,远程端的目录下仍然保留有旧的文件!

#启动client的httpd服务 

[root@ansibleserver ~]# ansible 192.168.1.232 -m service -a"name=httpd state=started" 

192.168.1.232 | success >> { 

    "changed": true,  

    "name":"httpd",  

    "state":"started"

#注意:state的状态有:started  restarted  stoped 

#client端查看情况 

[root@localhost ~]# netstat -lntup|grep httpd 

tcp        0      0 :::80                      :::*                        LISTEN      1565/httpd

#收集主机的所有系统信息 

[root@ansibleserver ~]# ansible 192.168.1.232 -m setup 

#收集系统信息并以主机名为文件名分别保存在/tmp/facts目录 

[root@ansibleserver facts]# ansible 192.168.1.232 -m setup --tree/tmp/facts 

[root@ansibleserver facts]# ll 

total 12 

-rw-r--r-- 1 root root 8656 Mar 18 00:25 192.168.1.232 

#收集系统内存相关信息 

[root@ansibleserver ~]# ansible 192.168.1.232 -m setup -a'filter=ansible_*_mb' 

192.168.1.232 | success >> { 

    "ansible_facts": { 

      "ansible_memfree_mb": 299,  

      "ansible_memtotal_mb": 490,  

      "ansible_swapfree_mb": 2047,  

      "ansible_swaptotal_mb": 2047 

    },  

    "changed": false

#收集网卡信息 

[root@ansibleserver ~]# ansible 192.168.1.232 -m setup -a'filter=ansible_eth[0-2]'

对于需反复执行的、较为复杂的任务,我们可以通过定义 Playbook 来搞定。Playbook 是 Ansible 真正强大的地方,它允许使用变量、条件、循环、以及模板,也能通过角色及包含指令来重用既有内容。下面我们来看看一些具体的实例。

#首先在/etc/ansible目录下建立一个php.yaml的文件 

[root@ansibleserver ansible]# vim php.yaml 

- hosts: 192.168.1.232  #主机名,如果是全部主机,可以用all 

  remote_user: root    #指定执行操作的用户 

  tasks:                #任务 

    - name: php installing  #起个任务的名字 

      yum: name=php state=present #利用yum模块,安装软件的包名为php 

参数:present为安装  absent为卸载 

提示:注意对齐的格式,不然会出错 


#用ansible-playbook 参数调用php.yaml 

[root@ansibleserver ansible]# ansible-playbook php.yaml  

PLAY [192.168.1.232]**********************************************************  

GATHERING FACTS***************************************************************  

ok: [192.168.1.232] 

TASK: [php installing]********************************************************  

changed: [192.168.1.232] 

PLAY RECAP ******************************************************************** 

192.168.1.232            : ok=2    changed=1    unreachable=0    failed=0 

#看到结果,ok=2  changed=1 说明客户机(232)上的php安装成功了!

#建立一个cron.yaml文件,然后每月10号来运行/root/dd.sql脚本 

#cron定时任务参数 

# Ensure a job that runs at 2 and 5 exists. 

# Creates an entry like "* 5,2 * * ls -alh > /dev/null" 

- cron: name="check dirs" hour="5,2" job="ls -alh> /dev/null"

# Ensure an old job is no longer present. Removes any job that is prefixed 

# by "#Ansible: an old job" from the crontab 

- cron: name="an old job" state=absent 


# Creates an entry like "@reboot /some/job.sh" 

- cron: name="a job for reboot" special_time=rebootjob="/some/job.sh"


# Creates a cron file under /etc/cron.d 

- cron: name="yum autoupdate" weekday="2" minute=0hour=12 

        user="root"job="YUMINTERACTIVE=0 /usr/sbin/yum-autoupdate"

      cron_file=ansible_yum-autoupdate 

# Removes a cron file from under /etc/cron.d 

- cron:cron_file=ansible_yum-autoupdate state=absent

#关于ansible的介绍就到此,有不足之处,希望大家多多指教!

Ansible和Docker的作用和用法  ​​http://www.linuxidc.com/Linux/2014-11/109783.htm​

Ansible批量搭建LAMP环境 ​​http://www.linuxidc.com/Linux/2014-10/108264.htm​

Ansible :一个配置管理和IT自动化工具  ​​http://www.linuxidc.com/Linux/2014-11/109365.htm​

Linux下安装部署Ansible ​​http://www.linuxidc.com/Linux/2015-02/112774.htm​

Ansible 的详细介绍:​​请点这里​

Ansible 的下载地址:​​请点这里​

本文永久更新链接地址:​​http://www.linuxidc.com/Linux/2015-04/115646.htm​