自动化运维

自动化运维介绍

saltstack安装

https://www.jianshu.com/p/624b9cf51c64

1.两台机器都做一下host,都安装saltstack yum源 https://repo.saltstack.com/#rhel

[root@centos-02 ~]# hostname
centos-02
[root@centos-02 ~]# vim /etc/hosts
[root@centos-02 ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.133.88 centos-02
192.168.133.66 centos-03
[root@centos-02 ~]# 
[root@centos-03 ~]# hostname
centos-03
[root@centos-03 ~]# vim /etc/hosts
[root@centos-03 ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.133.88 centos-02
192.168.133.66 centos-03

[root@centos-03 ~]# 
[root@centos-02 ~]# sudo yum install https://repo.saltstack.com/yum/redhat/salt-repo-latest-2.el7.noarch.rpm
[root@centos-03 ~]# sudo yum install https://repo.saltstack.com/yum/redhat/salt-repo-latest-2.el7.noarch.rpm

2.查看下yum源安装的包

[root@centos-02 ~]# yum list |grep salt

3.服务器安装两个包,客户端安装一个包

[root@centos-02 ~]# yum install -y salt-master salt-minion
[root@centos-03 ~]# yum install -y salt-minion

1.查看已安装的包

[root@centos-02 ~]# rpm -qa |grep salt
salt-master-2018.3.0-1.el7.noarch
salt-repo-latest-2.el7.noarch
salt-2018.3.0-1.el7.noarch
salt-minion-2018.3.0-1.el7.noarch
[root@centos-02 ~]# 

2.如果将那台机器作为控制中心就安装saltmaster,如果不是控制中心只安装一个saltminion就可以了

3.修改配置文件,将master前面的注释去掉,修改为自己的主机名 

[root@centos-02 ~]# vim /etc/salt/minion
[[root@centos-02 ~]# cat /etc/salt/minion|grep 'master: centos-02'
master: centos-02
[root@centos-02 ~]# 
[root@centos-03 ~]# vim /etc/salt/minion
[root@centos-03 ~]# cat /etc/salt/minion|grep 'centos-02'
master: centos-02
[root@centos-03 ~]# 

4.启动minion,minion是不监听端口的

[root@centos-03 ~]# systemctl start salt-minion
[root@centos-03 ~]# ps aux|grep salt
root       3523 32.5  2.1 313608 21292 ?        Ss   22:43   0:04 /usr/bin/python /usr/bin/salt-minion
root       3533 51.3  2.7 455036 27640 ?        Dl   22:43   0:03 /usr/bin/python /usr/bin/salt-minion
root       3541  0.3  2.0 410996 20064 ?        S    22:43   0:00 /usr/bin/python /usr/bin/salt-minion
root       3543  0.0  0.0 112664   932 pts/0    R+   22:43   0:00 grep --color=auto salt
[root@centos-03 ~]# netstat -lntp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1365/sshd           
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      2155/master         
tcp        0      0 0.0.0.0:10050           0.0.0.0:*               LISTEN      1212/zabbix_agentd  
tcp        0      0 192.168.133.66:27017    0.0.0.0:*               LISTEN      2276/mongod         
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      2276/mongod         
tcp6       0      0 :::3306                 :::*                    LISTEN      1591/mysqld         
tcp6       0      0 :::22                   :::*                    LISTEN      1365/sshd           
tcp6       0      0 ::1:25                  :::*                    LISTEN      2155/master         
tcp6       0      0 :::10050                :::*                    LISTEN      1212/zabbix_agentd  
[root@centos-03 ~]# 

5.启动marster(如果启动失败解决方案:sudo pip install --upgrade psutil

[root@centos-02 ~]# systemctl start salt-minion
[root@centos-02 ~]# 
[root@centos-02 ~]# systemctl start salt-master
[root@centos-02 ~]# ps aux|grep salt
root       3838  6.5  4.1 396068 41556 ?        Ss   23:15   0:03 /usr/bin/python /usr/bin/salt-master
root       3847  0.0  2.0 314108 20896 ?        S    23:15   0:00 /usr/bin/python /usr/bin/salt-master
root       3852  0.3  3.5 476912 35224 ?        Sl   23:15   0:00 /usr/bin/python /usr/bin/salt-master
root       3855  0.0  3.4 394984 34744 ?        S    23:15   0:00 /usr/bin/python /usr/bin/salt-master
root       3856  4.8  3.9 405652 39740 ?        S    23:15   0:02 /usr/bin/python /usr/bin/salt-master
root       3857  2.2  3.5 396068 35488 ?        S    23:15   0:01 /usr/bin/python /usr/bin/salt-master
root       3858  0.2  3.5 576316 35972 ?        Sl   23:15   0:00 /usr/bin/python /usr/bin/salt-master
root       3865 13.5  4.1 402888 41708 ?        S    23:15   0:06 /usr/bin/python /usr/bin/salt-master
root       3866  1.3  3.5 469800 35764 ?        Sl   23:15   0:00 /usr/bin/python /usr/bin/salt-master
root       3868 12.5  4.1 401372 41268 ?        R    23:15   0:05 /usr/bin/python /usr/bin/salt-master
root       3869 12.1  4.1 401380 41448 ?        R    23:15   0:05 /usr/bin/python /usr/bin/salt-master
root       3870 12.3  4.1 401376 41460 ?        R    23:15   0:05 /usr/bin/python /usr/bin/salt-master
root       3872 12.6  4.1 401508 41544 ?        R    23:15   0:05 /usr/bin/python /usr/bin/salt-master
root       3895  3.0  0.0 112664   936 pts/0    R+   23:16   0:00 grep --color=auto salt
root       3896  0.0  4.0 401760 40456 ?        R    23:16   0:00 /usr/bin/python /usr/bin/salt-master
[root@centos-02 ~]# netstat -lntp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1041/sshd           
tcp        0      0 0.0.0.0:4505            0.0.0.0:*               LISTEN      3852/python         
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1867/master         
tcp        0      0 0.0.0.0:4506            0.0.0.0:*               LISTEN      3858/python         
tcp        0      0 0.0.0.0:10051           0.0.0.0:*               LISTEN      1406/zabbix_server  
tcp        0      0 192.168.133.88:27017    0.0.0.0:*               LISTEN      2147/mongod         
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      2147/mongod         
tcp6       0      0 :::3306                 :::*                    LISTEN      1394/mysqld         
tcp6       0      0 :::80                   :::*                    LISTEN      743/httpd           
tcp6       0      0 :::22                   :::*                    LISTEN      1041/sshd           
tcp6       0      0 ::1:25                  :::*                    LISTEN      1867/master         
tcp6       0      0 :::10051                :::*                    LISTEN      1406/zabbix_server  
[root@centos-02 ~]# 

saltstack配置认证

1.认证指定主机03服务器,现在已经接受了03服务器的公钥

[root@centos-02 ~]# salt-key -a centos-03
The following keys are going to be accepted:
Unaccepted Keys:
centos-03
Proceed? [n/Y] 
Key for minion centos-03 accepted.
[root@centos-02 ~]# salt-key 
Accepted Keys:
centos-03
Denied Keys:
Unaccepted Keys:
centos-02
Rejected Keys:
[root@centos-02 ~]# 

2.在minions目录生成了centos-03文件并且文件内容和03服务器上的公钥内容是一样的。

[root@centos-02 ~]# 
[root@centos-02 ~]# ls /etc/salt/pki/master/minions
centos-03
[root@centos-02 ~]# cat /etc/salt/pki/master/minions/centos-03 
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnKfs8F87Zu10FZritvJs
nbjsogW1Wtz5a3b6hRWGyQfMQEO/FYTQ0X/nL2Dvb5UVHol7SBTqmigFYU3oyXg+
86oGQD2EVQDDP2e+Zx20WhusMTLNr2XEDs+D6cK/42SFXkRVACh9KZONJM1sc9gt
5JJqMRJKS/9u79Pk2wStRFZ+PaxPdCSMuuIX7fL4E2uQHpqPTjNO13+H288wQQSv
iN+enII4TLovcm2oURihVdfeZFmcMglKrgAMDK8ikXTkIeaf1ovZEfjTHO44ug9X
Qet/wPLdXoeMA//niWTFvvfUGzY2kZLM8UiI2VCikG6Rmh1HtZUdqD3Z9ZClM4Mj
UwIDAQAB
-----END PUBLIC KEY-----[root@centos-02 ~]# 
[root@centos-03 ~]# cat /etc/salt/pki/minion/minion.pub 
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnKfs8F87Zu10FZritvJs
nbjsogW1Wtz5a3b6hRWGyQfMQEO/FYTQ0X/nL2Dvb5UVHol7SBTqmigFYU3oyXg+
86oGQD2EVQDDP2e+Zx20WhusMTLNr2XEDs+D6cK/42SFXkRVACh9KZONJM1sc9gt
5JJqMRJKS/9u79Pk2wStRFZ+PaxPdCSMuuIX7fL4E2uQHpqPTjNO13+H288wQQSv
iN+enII4TLovcm2oURihVdfeZFmcMglKrgAMDK8ikXTkIeaf1ovZEfjTHO44ug9X
Qet/wPLdXoeMA//niWTFvvfUGzY2kZLM8UiI2VCikG6Rmh1HtZUdqD3Z9ZClM4Mj
UwIDAQAB
-----END PUBLIC KEY-----[root@centos-03 ~]# 

3.再给02本机做一个access

[root@centos-02 ~]# salt-key -A
The following keys are going to be accepted:
Unaccepted Keys:
centos-02
Proceed? [n/Y] Y
Key for minion centos-02 accepted.
[root@centos-02 ~]# salt-key 
Accepted Keys:
centos-02
centos-03
Denied Keys:
Unaccepted Keys:
Rejected Keys:
[root@centos-02 ~]# 

1.删掉所有的认证主机后发现minions目录下面也没内容了

[root@centos-02 ~]# salt-key -D
The following keys are going to be deleted:
Accepted Keys:
centos-02
centos-03
Proceed? [N/y] Y
Key for minion centos-02 deleted.
Key for minion centos-03 deleted.
[root@centos-02 ~]# ls /etc/salt/pki/master/minions
[root@centos-02 ~]# 

2.认证所有主机

[root@centos-02 ~]# ls /etc/salt/pki/master/minions
[root@centos-02 ~]# salt-key -A -y
The key glob '*' does not match any unaccepted keys.
[root@centos-02 ~]# salt-key
Accepted Keys:
Denied Keys:
Unaccepted Keys:
Rejected Keys:
[root@centos-02 ~]# systemctl restart salt-minion (重启让master端识别秘钥端)
[root@centos-03 ~]# systemctl restart salt-minion (重启让master端识别秘钥端)
[root@centos-03 ~]#
[root@centos-02 ~]# salt-key
Accepted Keys:
Denied Keys:
Unaccepted Keys:
centos-02
Rejected Keys:
[root@centos-02 ~]# salt-key -A -y
The following keys are going to be accepted:
Unaccepted Keys:
centos-02
centos-03
Key for minion centos-02 accepted.
Key for minion centos-03 accepted.
[root@centos-02 ~]# 

saltstack远程执行命令

1.ping一下看看通不通

[root@centos-02 ~]# salt '*' test.ping
centos-03:
    True
centos-02:
    True
[root@centos-02 ~]# 

2.执行系统命令hostname

[root@centos-02 ~]# salt '*' cmd.run "hostname"
centos-03:
    centos-03
centos-02:
    centos-02
[root@centos-02 ~]# 

3.*号可以换成主机名

[root@centos-02 ~]# salt 'centos-03' cmd.run "hostname"
centos-03:
    centos-03
[root@centos-02 ~]# 

4.支持正则表达式

[root@centos-02 ~]# salt 'centos-*' cmd.run "hostname"
centos-03:
    centos-03
centos-02:
    centos-02
[root@centos-02 ~]# salt 'centos-0[23]' cmd.run "hostname"
centos-03:
    centos-03
centos-02:
    centos-02
[root@centos-02 ~]# 

5.-L已列表形式

[root@centos-02 ~]# salt -L 'centos-02,centos-03' test.ping
centos-03:
    True
centos-02:
    True
[root@centos-02 ~]#

6.-E执行正则

[root@centos-02 ~]# salt -E 'centos-[0-9]+' test.ping
centos-03:
    True
centos-02:
    True
[root@centos-02 ~]# 

grains

1.查看信息

[root@centos-02 ~]# salt 'centos-03' grains.ls^C
[root@centos-02 ~]# salt 'centos-03' grains.items

1.自定义信息

[root@centos-03 ~]# vim /etc/salt/grains
[root@centos-03 ~]# cat !$
cat /etc/salt/grains
role:nginx
env:test
[root@centos-03 ~]# systemctl restart salt-minion
[root@centos-03 ~]# 
[root@centos-02 ~]# salt '*' grains.item role env
centos-03:
    ----------
    env:
    role:
centos-02:
    ----------
    env:
    role:
[root@centos-02 ~]# 
[root@centos-02 ~]# salt -G role:nginx cmd.run 'hostname'

pillar  

 1.配置pillar,编辑配置文件去掉pillar_roots和后面两行下面的#号

[root@centos-02 ~]# vim /etc/salt/master
[root@centos-02 ~]# cat /etc/salt/master|grep pillar_roots
pillar_roots:
[root@centos-02 ~]# 

 

[root@centos-02 ~]# systemctl restart salt-master
[root@centos-02 ~]# ls /srv/pillar
ls: cannot access /srv/pillar: No such file or directory
[root@centos-02 ~]# mkdir /srv/pillar
[root@centos-02 ~]# cd /srv/pillar/
[root@centos-02 pillar]# vim test.sls
[root@centos-02 pillar]# cat test.sls 
conf: /etc/123.conf
[root@centos-02 pillar]# vi top.sls
[root@centos-02 pillar]# cat top.sls 
base:
  'centos-02':
    - test
[root@centos-02 pillar]# ls
test.sls  top.sls
[root@centos-02 pillar]# 

  

2.添加多个test,不用重启服务,因为改过master配置文件了它会自动找到的,只有修改/etc/salt/master文件才需要重启服务

[root@centos-02 pillar]# vi top.sls
[root@centos-02 pillar]# cat top.sls 
base:
  'centos-02':
    - test
    - test2
[root@centos-02 pillar]# ls
test.sls  top.sls
[root@centos-02 pillar]# cp test.sls test2.sls
[root@centos-02 pillar]# vim test2.sls 
[root@centos-02 pillar]# cat test2.sls 
dir: /data/123
[root@centos-02 pillar]# 

3.测试,刷新下

[root@centos-02 pillar]# salt '*' saltutil.refresh_pillar
centos-02:
    True
centos-03:
    True
[root@centos-02 pillar]# salt '*' pillar.item conf
centos-03:
    ----------
    conf:
centos-02:
    ----------
    conf:
        /etc/123.conf
[root@centos-02 pillar]# salt '*' pillar.item conf dir
centos-03:
    ----------
    conf:
    dir:
centos-02:
    ----------
    conf:
        /etc/123.conf
    dir:
        /data/123
[root@centos-02 pillar]# 
[root@centos-02 pillar]# cat top.sls 
base:
  'centos-02':
    - test
    - test2
[root@centos-02 pillar]# vim top.sls 
[root@centos-02 pillar]# cat top.sls 
base:
  'centos-02':
    - test
  'centos-03':	
    - test2
[root@centos-02 pillar]# salt '*' saltutil.refresh_pillar
centos-03:
    True
centos-02:
    True
[root@centos-02 pillar]# salt '*' pillar.item conf dir
centos-03:
    ----------
    conf:
    dir:
centos-02:
    ----------
    conf:
    dir:
[root@centos-02 pillar]# 

安装配置httpd

1.配置配置文件,找到file_roots打开注释及下面两行的注释,这个是定义主入口的

[root@centos-02 pillar]# vim /etc/salt/master
[root@centos-02 pillar]# cat /etc/salt/master|grep file_roots
file_roots:
#file_roots:
# The master_roots setting configures a master-only copy of the file_roots dictionary,
# "roots" which uses the "file_roots" option.
[root@centos-02 pillar]# 
[root@centos-02 pillar]# systemctl restart salt-master
[root@centos-02 pillar]# mkdir /srv/salt
[root@centos-02 pillar]# cd /srv/salt/
[root@centos-02 salt]# vim /srv/salt/top.sls
[root@centos-02 salt]# cat !$
cat /srv/salt/top.sls
base:
  '*':
    - httpd
[root@centos-02 salt]# systemctl restart salt-master
[root@centos-02 salt]# 

1.创建httpd.sls

[root@centos-02 salt]# vim httpd.sls
[root@centos-02 salt]# cat !$
cat httpd.sls
http-service:
  pkg.installed:
    - names:
      - httpd
      - httpd-devel
  service.running:
    - name: httpd
    - enable: True
[root@centos-02 salt]# 
[root@centos-02 salt]# salt 'centos-02' state.highstate

2.httpd成功了

[root@centos-02 salt]# ps aux |grep httpd
root      12764  1.0  1.6 394396 16212 ?        Ss   23:15   0:00 /usr/sbin/httpd -DFOREGROUND
apache    12765  0.0  0.8 394532  8216 ?        S    23:15   0:00 /usr/sbin/httpd -DFOREGROUND
apache    12766  0.0  0.8 394532  8216 ?        S    23:15   0:00 /usr/sbin/httpd -DFOREGROUND
apache    12767  0.0  0.8 394532  8216 ?        S    23:15   0:00 /usr/sbin/httpd -DFOREGROUND
apache    12768  0.0  0.8 394532  8216 ?        S    23:15   0:00 /usr/sbin/httpd -DFOREGROUND
apache    12769  0.0  0.8 394532  8216 ?        S    23:15   0:00 /usr/sbin/httpd -DFOREGROUND
root      12890  0.0  0.0 112664   936 pts/0    R+   23:16   0:00 grep --color=auto http
[root@centos-02 salt]# 

3.涉及到的配置文件

[root@centos-02 salt]# date
Wed May 30 23:19:18 CST 2018
[root@centos-02 salt]# cat top.sls 
base:
  '*':
    - httpd
[root@centos-02 salt]# cat httpd.sls 
http-service:
  pkg.installed:
    - names:
      - httpd
      - httpd-devel
  service.running:
    - name: httpd
    - enable: True
[root@centos-02 salt]# 
[root@centos-02 salt]# ls /lib/systemd/system/httpd.service 
/lib/systemd/system/httpd.service
[root@centos-02 salt]# 

配置管理文件

https://www.kevintaolinux.cn/?p=199

[root@centos-02 ~]# vim /srv/salt/test.sls
[root@centos-02 ~]# cat /srv/salt/test.sls 
file_test: (id)
  file.managed:
    - name: /tmp/linux.com (对方机器的路径)
    - source: salt://test/123/1.txt (从那里来)
    - user: root
    - group: root
    - mode: 600
[root@centos-02 ~]# cd /srv/salt/
[root@centos-02 salt]# mkdir test
[root@centos-02 salt]# cd test
[root@centos-02 test]# mkdir 123
[root@centos-02 test]# cp /etc/inittab ../test/123/1.txt
[root@centos-02 test]# cd ../
[root@centos-02 salt]# vim top.sls 
[root@centos-02 salt]# cat top.sls (总入口top,top找到了test)
base:
  '*':
    - test
[root@centos-02 salt]# salt 'centos-03' state.highstate
[root@centos-02 salt]# salt 'centos-03' state.highstate
centos-03:
----------
          ID: file_test
    Function: file.managed
        Name: /tmp/linux.com
      Result: True
     Comment: File /tmp/linux.com updated
     Started: 22:34:02.956919
    Duration: 1624.217 ms
     Changes:   
              ----------
              diff:
                  New file

Summary for centos-03
------------
Succeeded: 1 (changed=1)
Failed:    0
------------
Total states run:     1
Total run time:   1.624 s
[root@centos-02 salt]#

2.检查minion上是否生成了linux.com

[root@centos-03 ~]# ls -lt /tmp/linux.com 
-rw------- 1 root root 511 5月  31 22:34 /tmp/linux.com
[root@centos-03 ~]# 

配置管理目录  

1.minion上不仅有testdir目录还创建了1.txt文件

[root@centos-02 salt]# vim test_dir.sls
[root@centos-02 salt]# cat test_dir.sls 
file_dir:
  file.recurse:
    - name: /tmp/testdir
    - source: salt://test/123
    - user: root
    - file_mode: 640
    - dir_mode: 750
    - mkdir: True
    - clean: True
[root@centos-02 salt]# vim top.sls 
[root@centos-02 salt]# cat top.sls 
base:
  '*':
    - test
    - test_dir
[root@centos-02 salt]# salt 'centos-03' state.highstate
centos-03:
----------
          ID: file_test
    Function: file.managed
        Name: /tmp/linux.com
      Result: True
     Comment: File /tmp/linux.com is in the correct state
     Started: 22:57:30.893487
    Duration: 938.246 ms
     Changes:   
----------
          ID: file_dir
    Function: file.recurse
        Name: /tmp/testdir
      Result: True
     Comment: Recursively updated /tmp/testdir
     Started: 22:57:31.857699
    Duration: 1311.945 ms
     Changes:   
              ----------
              /tmp/testdir/1.txt:
                  ----------
                  diff:
                      New file
                  mode:
                      0640

Summary for centos-03
------------
Succeeded: 2 (changed=1)
Failed:    0
------------
Total states run:     2
Total run time:   2.250 s
[root@centos-02 salt]# 
[root@centos-03 ~]# ls -l /tmp/testdir/
总用量 4
-rw-r----- 1 root root 511 5月  31 22:57 1.txt
[root@centos-03 ~]# 

2.现在在test上创建一个新的目录并创建一个文件

[root@centos-02 salt]# cd test
[root@centos-02 test]# ls
123
[root@centos-02 test]# mkdir abc
[root@centos-02 test]# touch 1.txt
[root@centos-02 test]# rm -rf 1
123/   1.txt  
[root@centos-02 test]# rm -rf 123/
[root@centos-02 test]# ls
1.txt  abc
[root@centos-02 test]# salt 'centos-03' state.highstate
centos-03:
----------
          ID: file_test
    Function: file.managed
        Name: /tmp/linux.com
      Result: False
     Comment: Source file salt://test/123/1.txt not found
     Started: 23:02:40.435153
    Duration: 733.812 ms
     Changes:   
----------
          ID: file_dir
    Function: file.recurse
        Name: /tmp/testdir
      Result: False
     Comment: Recurse failed: none of the specified sources were found
     Started: 23:02:41.171355
    Duration: 139.599 ms
     Changes:   

Summary for centos-03
------------
Succeeded: 0
Failed:    2
------------
Total states run:     2
Total run time: 873.411 ms
ERROR: Minions returned with non-zero exit code
[root@centos-02 test]#

3.报错是因为我们把1.txt删掉了,为了不影响我们实验我们改下配置

[root@centos-02 test]# cd ../
[root@centos-02 salt]# ls
httpd.sls  test  test_dir.sls  test.sls  top.sls
[root@centos-02 salt]# vim test.sls 
[root@centos-02 salt]# vim test.top
[root@centos-02 salt]# vim top.sls 
[root@centos-02 salt]# cat top.sls 
base:
  '*':
    - test_dir
[root@centos-02 salt]# cat test_dir.sls 
file_dir:
  file.recurse:
    - name: /tmp/testdir
    - source: salt://test/123
    - user: root
    - file_mode: 640
    - dir_mode: 750
    - mkdir: True
    - clean: True
[root@centos-02 salt]# mkdir test/123/
[root@centos-02 salt]# mv test/abc/ test/1.txt test/123/
[root@centos-02 salt]# salt 'centos-03' state.highstate
centos-03:
----------
          ID: file_dir
    Function: file.recurse
        Name: /tmp/testdir
      Result: True
     Comment: Recursively updated /tmp/testdir
     Started: 23:10:26.183198
    Duration: 1132.273 ms
     Changes:   
              ----------
              /tmp/testdir/1.txt:
                  ----------
                  diff:
                      --- 
                      +++ 
                      @@ -1,17 +0,0 @@
                      -# inittab is no longer used when using systemd.
                      -#
                      -# ADDING CONFIGURATION HERE WILL HAVE NO EFFECT ON YOUR SYSTEM.
                      -#
                      -# Ctrl-Alt-Delete is handled by /usr/lib/systemd/system/ctrl-alt-del.target
                      -#
                      -# systemd uses 'targets' instead of runlevels. By default, there are two main targets:
                      -#
                      -# multi-user.target: analogous to runlevel 3
                      -# graphical.target: analogous to runlevel 5
                      -#
                      -# To view current default target, run:
                      -# systemctl get-default
                      -#
                      -# To set a default target, run:
                      -# systemctl set-default TARGET.target
                      -#

Summary for centos-03
------------
Succeeded: 1 (changed=1)
Failed:    0
------------
Total states run:     1
Total run time:   1.132 s
[root@centos-02 salt]# 

4.检查是否生成了abc目录,没有abc目录,这是因为saltstack有一个特性如果这个目录是空目录它就不去同步了,如果想同步怎么办,需要在这个目录搞一个文件,哪怕是空文件也行

[root@centos-03 ~]# ls /tmp/testdir/
1.txt
[root@centos-03 ~]# 
[root@centos-02 salt]# touch test/123/abc/2.txt
[root@centos-02 salt]# tree test
test
└── 123
    ├── 1.txt
    └── abc
        └── 2.txt

2 directories, 2 files
[root@centos-02 salt]# salt 'centos-03' state.highstate
centos-03:
----------
          ID: file_dir
    Function: file.recurse
        Name: /tmp/testdir
      Result: True
     Comment: Recursively updated /tmp/testdir
     Started: 23:18:07.681431
    Duration: 1985.497 ms
     Changes:   
              ----------
              /tmp/testdir/abc:
                  ----------
                  /tmp/testdir/abc:
                      New Dir
              /tmp/testdir/abc/2.txt:
                  ----------
                  diff:
                      New file
                  mode:
                      0640

Summary for centos-03
------------
Succeeded: 1 (changed=1)
Failed:    0
------------
Total states run:     1
Total run time:   1.985 s
[root@centos-02 salt]# 

5.再次查看发现我x生成了

[root@centos-03 ~]# ls /tmp/testdir/
1.txt  abc
[root@centos-03 ~]# ls /tmp/testdir/abc/
2.txt
[root@centos-03 ~]# 

配置管理远程命令

 1.新建shell_test.sls文件

[root@centos-02 salt]# vim /srv/salt/shell_test.sls
[root@centos-02 salt]# cat /srv/salt/shell_test.sls 
shell_test:  (文件的id)
  cmd.script: (加载的模块)
    - source: salt://test/1.sh (脚本路径)
    - user: root (执行的用户)
[root@centos-02 salt]# vim /srv/salt/test/1.sh (编辑脚本)
[root@centos-02 salt]# cat /srv/salt/test/1.sh 
#!/bin/bash
touch /tmp/111.txt
if [ ! -d /tmp/1233 ]
then
  mkdir /tmp/1233
fi
[root@centos-02 salt]# vim top.sls 
[root@centos-02 salt]# cat top.sls 
base:
  '*':
    - shell_test
[root@centos-02 salt]# salt 'centos-03' state.highstate
centos-03:
----------
          ID: shell_test
    Function: cmd.script
      Result: True
     Comment: Command 'shell_test' run
     Started: 21:46:54.865773
    Duration: 580.834 ms
     Changes:   
              ----------
              pid:
                  5481
              retcode:
                  0
              stderr:
              stdout:

Summary for centos-03
------------
Succeeded: 1 (changed=1)
Failed:    0
------------
Total states run:     1
Total run time: 580.834 ms
[root@centos-02 salt]# 

2.验证是否执行成功,查看03服务器是否有111.txt文件和1233目录,发现有,说明脚本执行成功了。

[root@centos-03 tmp]# ls -lt
总用量 4
drwxr-xr-x 2 root   root     6 6月   3 21:46 1233
-rw-r--r-- 1 root   root     0 6月   3 21:46 111.txt

配置管理计划任务

1.编辑任务计划文件

[root@centos-02 salt]# vim /srv/salt/cron_test.sls
[root@centos-02 salt]# cat /srv/salt/cron_test.sls 
cron_test:
  cron.present:
    - name: /bin/touch /tmp/111.txt (计划任务执行的文件)
    - user: root (用户)
    - minute: '*' (分)
    - hour: 20 (时)
    - daymonth: '*' (日)
    - month: '*' (月)
    - dayweek: '*' (周)
[root@centos-02 salt]# 

2.修改top.sls

[root@centos-02 salt]# vim top.sls 
[root@centos-02 salt]# cat top.sls 
base:
  '*':
    - cron_test
[root@centos-02 salt]# salt 'centos-03' state.highstate
centos-03:
----------
          ID: cron_test
    Function: cron.present
        Name: /bin/touch /tmp/111.txt
      Result: True
     Comment: Cron /bin/touch /tmp/111.txt added to root's crontab
     Started: 23:56:36.086544
    Duration: 4184.541 ms
     Changes:   
              ----------
              root:
                  /bin/touch /tmp/111.txt

Summary for centos-03
------------
Succeeded: 1 (changed=1)
Failed:    0
------------
Total states run:     1
Total run time:   4.185 s
[root@centos-02 salt]# 

3.minion03上验证,成功添加了计划任务

[root@centos-03 tmp]# crontab -l
# Lines below here are managed by Salt, do not edit
# SALT_CRON_IDENTIFIER:/bin/touch /tmp/111.txt
* 20 * * * /bin/touch /tmp/111.txt
[root@centos-03 tmp]# 

4.删除cron

[root@centos-02 salt]# vim /srv/salt/cron_test.sls 
[root@centos-02 salt]# cat /srv/salt/cron_test.sls 
cron_test:
  cron.absent:
    - name: /bin/touch /tmp/111.txt
[root@centos-02 salt]# salt 'centos-03' state.highstate
centos-03:
----------
          ID: cron_test
    Function: cron.absent
        Name: /bin/touch /tmp/111.txt
      Result: True
     Comment: Cron /bin/touch /tmp/111.txt removed from root's crontab
     Started: 00:02:56.270655
    Duration: 3511.174 ms
     Changes:   
              ----------
              root:
                  /bin/touch /tmp/111.txt

Summary for centos-03
------------
Succeeded: 1 (changed=1)
Failed:    0
------------
Total states run:     1
Total run time:   3.511 s
[root@centos-02 salt]# 
[root@centos-03 tmp]# crontab -l
# Lines below here are managed by Salt, do not edit
[root@centos-03 tmp]# 

其他命令

1.拷贝master上的文件到客户端

[root@centos-02 salt]# cp /etc/passwd test/1.txt
[root@centos-02 salt]# salt '*' cp.get_file salt://test/1.txt /tmp/123.txt
centos-03:
    /tmp/123.txt
centos-02:
    /tmp/123.txt
[root@centos-02 salt]# ls -l /tmp/123.txt 
-rw-r--r-- 1 root root 2060 Jun  4 22:14 /tmp/123.txt
[root@centos-02 salt]# 

2.拷贝目录

[root@centos-02 salt]# ls test
123  1.sh  1.txt
[root@centos-02 salt]# salt '*' cp.get_dir salt://test/123 /tmp/
centos-02:
    - /tmp//123/1.txt
    - /tmp//123/abc/2.txt
centos-03:
    - /tmp//123/1.txt
    - /tmp//123/abc/2.txt
[root@centos-02 salt]# 

3.显示存活的minion

[root@centos-02 salt]# salt-run manage.up
- centos-02
- centos-03
[root@centos-02 salt]# 

4.命令行执行shell上的脚本

[root@centos-02 salt]# salt '*' cmd.script salt://test/1.sh
centos-03:
    ----------
    pid:
        7204
    retcode:
        0
    stderr:
    stdout:
centos-02:
    ----------
    pid:
        34092
    retcode:
        0
    stderr:
    stdout:
[root@centos-02 salt]# 

salt-ssh使用

1.安装yum包

[root@centos-02 salt]# yum install -y salt-ssh

2.编辑roster配置文件

[root@centos-02 yum.repos.d]# vim /etc/salt/roster 
[root@centos-02 yum.repos.d]# cat /etc/salt/roster 
# Sample salt-ssh config file
#web1:
#  host: 192.168.42.1 # The IP addr or DNS hostname
#  user: fred         # Remote executions will be executed as user fred
#  passwd: foobarbaz  # The password to use for login, if omitted, keys are used
#  sudo: True         # Whether to sudo to root, not enabled by default
#web2:
#  host: 192.168.42.2
centos-02:
  host: 192.168.133.88
  user: root
  passwd: root
centos-03:
  host: 192.168.133.66
  user: root
  passwd: root

[root@centos-02 yum.repos.d]# 

3.登录成功执行w命令

[root@centos-02 yum.repos.d]# vim /etc/salt/roster 
[root@centos-02 yum.repos.d]# 
[root@centos-02 yum.repos.d]# salt-ssh --key-deploy '*' -r 'w'
centos-03:
    ----------
    retcode:
        0
    stderr:
    stdout:
        root@192.168.133.66's password: 
         23:47:54 up  8:50,  2 users,  load average: 0.69, 0.28, 0.23
        USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
        root     pts/1    192.168.133.1    21:52    1:35m  0.20s  0.20s -bash
        root     pts/2    192.168.133.1    22:52   55:21   0.05s  0.05s -bash
centos-02:
    ----------
    retcode:
        0
    stderr:
    stdout:
        root@192.168.133.88's password: 
         23:47:57 up  8:49,  2 users,  load average: 1.03, 0.93, 1.42
        USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
        root     pts/1    192.168.133.1    21:52    1:22m  0.54s  0.54s -bash
        root     pts/2    192.168.133.1    22:52   45.00s 16.07s  0.21s salt-ssh
[root@centos-02 yum.repos.d]# ssh centos-03
The authenticity of host 'centos-03 (192.168.133.66)' can't be established.
ECDSA key fingerprint is bf:dc:4b:e3:1c:99:f4:12:6f:d0:a8:e0:13:8a:d0:dd.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'centos-03' (ECDSA) to the list of known hosts.
root@centos-03's password: 
Last login: Mon Jun  4 22:52:34 2018 from 192.168.133.1
[root@centos-03 ~]# ^C
[root@centos-03 ~]# exit
logout
Connection to centos-03 closed.
[root@centos-02 yum.repos.d]# salt-ssh --key-deploy '*' -r 'w'
centos-03:
    ----------
    retcode:
        0
    stderr:
    stdout:
         23:49:12 up  8:51,  2 users,  load average: 0.20, 0.22, 0.21
        USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
        root     pts/1    192.168.133.1    21:52    1:37m  0.20s  0.20s -bash
        root     pts/2    192.168.133.1    22:52   56:39   0.05s  0.05s -bash
centos-02:
    ----------
    retcode:
        0
    stderr:
    stdout:
         23:49:12 up  8:50,  2 users,  load average: 0.92, 0.90, 1.37
        USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
        root     pts/1    192.168.133.1    21:52    1:23m  0.54s  0.54s -bash
        root     pts/2    192.168.133.1    22:52    8.00s  2.55s  0.15s /usr/bin/python /usr/bin/salt-ssh --key-deploy * -r w
[root@centos-02 yum.repos.d]# 

4.查看更改公钥时间

[root@centos-02 yum.repos.d]# ls -l /root/.ssh/authorized_keys 
-r--------. 1 root root 1188 Jun  4 23:48 /root/.ssh/authorized_keys
[root@centos-02 yum.repos.d]# date
Mon Jun  4 23:52:12 CST 2018
[root@centos-02 yum.repos.d]# 
[root@centos-03 ~]# ls -l /root/.ssh/authorized_keys 
-rw-r--r--. 1 root root 777 6月   4 23:47 /root/.ssh/authorized_keys
[root@centos-03 ~]# date
2018年 06月 04日 星期一 23:54:07 CST
[root@centos-03 ~]# 

5.查看公钥、私钥内容

[root@centos-03 ~]# cat /root/.ssh/authorized_keys 
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA4Wpl8Dh8Tj4yqOphBTc0O5nZGZF24z86LsL46rPH95Hr0tjG/V4ulyW7VBtRvMe3Rbxv92DUYwcpeaM8v7BaVCzhn/I/FxK3gXcWfQWrfKz+Zr10QBv1RG5lZDEvZvFWfZSJySywG1mq10f6h
hwvsQmazVF9sJkb4nZ61/uC9bIENQ/QwGNBd02XgTkl2WfhxG3C+dF08Cdd/iRv9ybn/6jMAFh8aGyKdeBTrlZw2ZyU64zvDSpqRsHjMypNrL/jH3vK0EYKqEmQVgbTsBpO1NCEcTXuuM+M6i7DlPfSltdMRWqkfw2rcZDkLXcxIyAuyhv7o7
7j6bEtAX2SrH9brQ== ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCw1DhoGQzR46NloLYewjjPGWpyYkVfG0IPh9wryoU2lC5Najw6P+4C3ryLezE3B2Cs0m71e8ygHi3RN5fy5AgD8D9rT5TFusOwY5yk4fXi5D7Is2ACx2HGDIXpOcUTmSfe/2Mr/wk/7sGyFj
ci7Cj88iwDvzjmOzB5AYcfkb+fhW27eDpkrteq4Y58AqMv0bi2aaH+mBzV51/Ox4/NrREaZRW323RilPMDz2mgfV2y6vcDcWZHReJAI5MHzJRcAsK13JLjgs7Tn6IczXrFKIlBIHhfvf0lte8EEbgCybZydmP9hbsO6odzsAVPeebgu5wtIzWZ
Y8GU8ORhoCelUITZ root@centos-02 [root@centos-03 ~]#
[root@centos-02 yum.repos.d]# cat /root/.ssh/authorized_keys 
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA4Wpl8Dh8Tj4yqOphBTc0O5nZGZF24z86LsL46rPH95Hr0tjG/V4ulyW7VBtRvMe3Rbxv92DUYwcpeaM8v7BaVCzhn/I/FxK3gXcWfQWrfKz+Zr10QBv1RG5lZDEvZvFWfZSJySywG1mq10f6hh
wvsQmazVF9sJkb4nZ61/uC9bIENQ/QwGNBd02XgTkl2WfhxG3C+dF08Cdd/iRv9ybn/6jMAFh8aGyKdeBTrlZw2ZyU64zvDSpqRsHjMypNrL/jH3vK0EYKqEmQVgbTsBpO1NCEcTXuuM+M6i7DlPfSltdMRWqkfw2rcZDkLXcxIyAuyhv7o77j
6bEtAX2SrH9brQ== ###sunyujun02 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDYzwzucn1JkSSXBDNAZ9KNAbRFLUGn27xeJ/3H7bkXC8FpdNfesSuoHDHg3+RxLnOa7h5M2fLb/ThvPzpl8BA5PYdzY+adqjYzkaCubU/Yjt5GvZV0lTJN+Xsxf8X4wXQtZKQdgKKf+ejo6O
7fIlwPmypk9nd6RjgKoDe45s4jWHt0HttYCG+2IHLT+gMKcNPvkEPvRqnOlZMFW4e6fsyaBzfP+venLMU+ykuvmH9g3Sjh2dUF1wd3czxYcnxCFWbxxqkuH8VAUZFJ8DpBh3G6Cy/A4/5MzprKY/x3jpMfKbkrXkngcnfuCg9oEhTX9cNdbb3U
USrc+lQNbj3aOMmL root@sunyujun02 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCw1DhoGQzR46NloLYewjjPGWpyYkVfG0IPh9wryoU2lC5Najw6P+4C3ryLezE3B2Cs0m71e8ygHi3RN5fy5AgD8D9rT5TFusOwY5yk4fXi5D7Is2ACx2HGDIXpOcUTmSfe/2Mr/wk/7sGyFj
ci7Cj88iwDvzjmOzB5AYcfkb+fhW27eDpkrteq4Y58AqMv0bi2aaH+mBzV51/Ox4/NrREaZRW323RilPMDz2mgfV2y6vcDcWZHReJAI5MHzJRcAsK13JLjgs7Tn6IczXrFKIlBIHhfvf0lte8EEbgCybZydmP9hbsO6odzsAVPeebgu5wtIzWZ
Y8GU8ORhoCelUITZ root@centos-02 [root@centos-02 yum.repos.d]#

6.删除配置文件密码看看还能执行w命令吗

[root@centos-02 yum.repos.d]# vim /etc/salt/roster 
[root@centos-02 yum.repos.d]# cat /etc/salt/roster 
# Sample salt-ssh config file
#web1:
#  host: 192.168.42.1 # The IP addr or DNS hostname
#  user: fred         # Remote executions will be executed as user fred
#  passwd: foobarbaz  # The password to use for login, if omitted, keys are used
#  sudo: True         # Whether to sudo to root, not enabled by default
#web2:
#  host: 192.168.42.2
centos-02:
  host: 192.168.133.88
  user: root
centos-03:
  host: 192.168.133.66
  user: root

[root@centos-02 yum.repos.d]# 

7.完全可以,说明我们将公钥推送过去了,第一次需要输入密码第二次就不用了

[root@centos-02 yum.repos.d]# salt-ssh --key-deploy '*' -r 'w'
centos-03:
    ----------
    retcode:
        0
    stderr:
    stdout:
         00:06:26 up  9:08,  2 users,  load average: 0.00, 0.03, 0.10
        USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
        root     pts/1    192.168.133.1    21:52    1:54m  0.20s  0.20s -bash
        root     pts/2    192.168.133.1    22:52   10:34   0.15s  0.15s -bash
centos-02:
    ----------
    retcode:
        0
    stderr:
    stdout:
         00:06:26 up  9:07,  2 users,  load average: 0.32, 0.26, 0.60
        USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
        root     pts/1    192.168.133.1    21:52    1:40m  0.54s  0.54s -bash
        root     pts/2    192.168.133.1    22:52   10.00s  3.55s  0.48s /usr/bin/python /usr/bin/salt-ssh --key-deploy * -r w
[root@centos-02 yum.repos.d]# 

ansible介绍  

http://www.ansible.com.cn/docs/intro.html

ansible安装 

1.首先yum list查看下是否有ansible包,我们安装前两个包

[root@centos-02 ~]# yum list|grep ansible
ansible.noarch                            2.5.3-1.el7                  epel     
ansible-doc.noarch                        2.5.3-1.el7                  epel     
ansible-inventory-grapher.noarch          2.4.4-1.el7                  epel     
ansible-lint.noarch                       3.4.21-1.el7                 epel     
ansible-openstack-modules.noarch          0-20140902git79d751a.el7     epel     
ansible-review.noarch                     0.13.4-1.el7                 epel     
kubernetes-ansible.noarch                 0.6.0-0.1.gitd65ebd5.el7     epel     
python2-ansible-runner.noarch             1.0.1-1.el7                  epel     
python2-ansible-tower-cli.noarch          3.3.0-2.el7                  epel     
[root@centos-02 ~]# yum install -y ansible ansible-doc

2.在02上做秘钥认证,把公钥放到03服务器上

[root@centos-02 ~]# cd /root/.ssh/
[root@centos-02 .ssh]# 
[root@centos-02 .ssh]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
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:
11:2b:16:96:01:b4:a2:28:6a:e2:0a:46:78:b6:55:ff root@centos-02
The key's randomart image is:
+--[ RSA 2048]----+
|   .o.+o.        |
|     o.. o       |
|  . . + o        |
|o. . o o .       |
|=.o .   S        |
|+o o     .       |
|+o.       E      |
|*                |
|o.               |
+-----------------+
[root@centos-02 .ssh]# ls
authorized_keys  id_rsa  id_rsa.pub  jump  jump.pub  known_hosts  zhangsan  zhangsan.pub
[root@centos-02 .ssh]# 

3.将生成的公钥放到03服务器上

[root@centos-02 .ssh]# cat id_rsa.pub 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD810lCxBhCtMzrmSx302M6PUMKRxNK0TBrFQzwbsL8KAcgJXvH0ysc5OIw8lEFpIQirmZODVHg85I/2u3Xgz9yEf5ucF33R0xjJpcD0sq9LvMj0A2lO2RppsjgNyA4wcYcxfOg9HcYI97622l
ssO5012qWbr6k9Bv3QOD0r+F6mdoFXvXFIF2YL//60kPcPXzyPgW6ErDkA1Pum9DQOiys6iN/tH4iCa7ynRzCkLlVxt21V8mrewAldn/JOMuJVEcUtKrmtH+6wny6sJHqEStlF46xZyIH1/SeDyd8oCDwC+PU2HLTc3hishe/ny8ofm9QcC+zgb
BSPnm+I1+/vwfZ root@centos-02 [root@centos-02 .ssh]# [root@centos-03 ~]# vim .ssh/authorized_keys [root@centos-03 ~]# cat .ssh/authorized_keys ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA4Wpl8Dh8Tj4yqOphBTc0O5nZGZF24z86LsL46rPH95Hr0tjG/V4ulyW7VBtRvMe3Rbxv92DUYwcpeaM8v7BaVCzhn/I/FxK3gXcWfQWrfKz+Zr10QBv1RG5lZDEvZvFWfZSJySywG1mq10f6hhw
vsQmazVF9sJkb4nZ61/uC9bIENQ/QwGNBd02XgTkl2WfhxG3C+dF08Cdd/iRv9ybn/6jMAFh8aGyKdeBTrlZw2ZyU64zvDSpqRsHjMypNrL/jH3vK0EYKqEmQVgbTsBpO1NCEcTXuuM+M6i7DlPfSltdMRWqkfw2rcZDkLXcxIyAuyhv7o77j6b
EtAX2SrH9brQ== ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCw1DhoGQzR46NloLYewjjPGWpyYkVfG0IPh9wryoU2lC5Najw6P+4C3ryLezE3B2Cs0m71e8ygHi3RN5fy5AgD8D9rT5TFusOwY5yk4fXi5D7Is2ACx2HGDIXpOcUTmSfe/2Mr/wk/7sGyFjc
i7Cj88iwDvzjmOzB5AYcfkb+fhW27eDpkrteq4Y58AqMv0bi2aaH+mBzV51/Ox4/NrREaZRW323RilPMDz2mgfV2y6vcDcWZHReJAI5MHzJRcAsK13JLjgs7Tn6IczXrFKIlBIHhfvf0lte8EEbgCybZydmP9hbsO6odzsAVPeebgu5wtIzWZY8
GU8ORhoCelUITZ root@centos-02 sh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD810lCxBhCtMzrmSx302M6PUMKRxNK0TBrFQzwbsL8KAcgJXvH0ysc5OIw8lEFpIQirmZODVHg85I/2u3Xgz9yEf5ucF33R0xjJpcD0sq9LvMj0A2lO2RppsjgNyA4wcYcxfOg9HcYI97622ls
sO5012qWbr6k9Bv3QOD0r+F6mdoFXvXFIF2YL//60kPcPXzyPgW6ErDkA1Pum9DQOiys6iN/tH4iCa7ynRzCkLlVxt21V8mrewAldn/JOMuJVEcUtKrmtH+6wny6sJHqEStlF46xZyIH1/SeDyd8oCDwC+PU2HLTc3hishe/ny8ofm9QcC+zgbB
SPnm+I1+/vwfZ root@centos-02 [root@centos-03 ~]#

4.测试02ssh是否能够正常登录03,ssh登录成功。 

[root@centos-02 .ssh]# ssh centos-03
Last login: Wed Jun  6 21:12:41 2018 from 192.168.133.1
[root@centos-03 ~]# 

5.编辑ansible配置文件,配置主机组,我们管理机器可以分成多个组,我们实验添加一个testhost组,并添加两台主机,可以写ip或者主机名,写主机名需要先在/etc/host下配置下ip主机名对应关系  

[root@centos-03 ~]# logout
Connection to centos-03 closed.
[root@centos-02 .ssh]# vim /etc/ansible/hosts
[testhost]
127.0.0.1
centos-03
[root@centos-02 .ssh]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.133.88 centos-02
192.168.133.66 centos-03
[root@centos-02 .ssh]#

6.本机也需要做认证

[root@centos-02 ~]# cat .ssh/authorized_keys 
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA4Wpl8Dh8Tj4yqOphBTc0O5nZGZF24z86LsL46rPH95Hr0tjG/V4ulyW7VBtRvMe3Rbxv92DUYwcpeaM8v7BaVCzhn/I/FxK3gXcWfQWrfKz+Zr10QBv1RG5lZDEvZvFWfZSJySywG1mq10f6hhw
vsQmazVF9sJkb4nZ61/uC9bIENQ/QwGNBd02XgTkl2WfhxG3C+dF08Cdd/iRv9ybn/6jMAFh8aGyKdeBTrlZw2ZyU64zvDSpqRsHjMypNrL/jH3vK0EYKqEmQVgbTsBpO1NCEcTXuuM+M6i7DlPfSltdMRWqkfw2rcZDkLXcxIyAuyhv7o77j6b
EtAX2SrH9brQ== ###sunyujun02 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDYzwzucn1JkSSXBDNAZ9KNAbRFLUGn27xeJ/3H7bkXC8FpdNfesSuoHDHg3+RxLnOa7h5M2fLb/ThvPzpl8BA5PYdzY+adqjYzkaCubU/Yjt5GvZV0lTJN+Xsxf8X4wXQtZKQdgKKf+ejo6O7
fIlwPmypk9nd6RjgKoDe45s4jWHt0HttYCG+2IHLT+gMKcNPvkEPvRqnOlZMFW4e6fsyaBzfP+venLMU+ykuvmH9g3Sjh2dUF1wd3czxYcnxCFWbxxqkuH8VAUZFJ8DpBh3G6Cy/A4/5MzprKY/x3jpMfKbkrXkngcnfuCg9oEhTX9cNdbb3UUS
rc+lQNbj3aOMmL root@sunyujun02 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCw1DhoGQzR46NloLYewjjPGWpyYkVfG0IPh9wryoU2lC5Najw6P+4C3ryLezE3B2Cs0m71e8ygHi3RN5fy5AgD8D9rT5TFusOwY5yk4fXi5D7Is2ACx2HGDIXpOcUTmSfe/2Mr/wk/7sGyFjc
i7Cj88iwDvzjmOzB5AYcfkb+fhW27eDpkrteq4Y58AqMv0bi2aaH+mBzV51/Ox4/NrREaZRW323RilPMDz2mgfV2y6vcDcWZHReJAI5MHzJRcAsK13JLjgs7Tn6IczXrFKIlBIHhfvf0lte8EEbgCybZydmP9hbsO6odzsAVPeebgu5wtIzWZY8
GU8ORhoCelUITZ root@centos-02 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD810lCxBhCtMzrmSx302M6PUMKRxNK0TBrFQzwbsL8KAcgJXvH0ysc5OIw8lEFpIQirmZODVHg85I/2u3Xgz9yEf5ucF33R0xjJpcD0sq9LvMj0A2lO2RppsjgNyA4wcYcxfOg9HcYI97622ls
sO5012qWbr6k9Bv3QOD0r+F6mdoFXvXFIF2YL//60kPcPXzyPgW6ErDkA1Pum9DQOiys6iN/tH4iCa7ynRzCkLlVxt21V8mrewAldn/JOMuJVEcUtKrmtH+6wny6sJHqEStlF46xZyIH1/SeDyd8oCDwC+PU2HLTc3hishe/ny8ofm9QcC+zgbB
SPnm+I1+/vwfZ root@centos-02 [root@centos-02 ~]#
[root@centos-02 ~]# ssh 127.0.0.1
Last login: Wed Jun  6 21:11:55 2018 from 192.168.133.1
[root@centos-02 ~]#

ansible远程执行命令  

1.远程执行w命令,两台机器都执行了w命令

[root@centos-02 ~]# ansible testhost -m command -a 'w'
centos-03 | SUCCESS | rc=0 >>
 22:34:45 up 10:38,  2 users,  load average: 0.29, 0.15, 0.22
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0    192.168.133.1    21:12   24:45   0.10s  0.10s -bash
root     pts/1    centos-02        22:34   11.00s  7.97s  0.37s w

127.0.0.1 | SUCCESS | rc=0 >>
 22:34:45 up 10:39,  3 users,  load average: 1.24, 0.47, 0.39
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0    192.168.133.1    21:11   37.00s  0.63s  0.08s ssh 127.0.0.1
root     pts/1    localhost        22:27   37.00s 13.85s  0.05s ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssap
i-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/21f0e6a9ae -tt 127.0.0.1 /bin/sh -c '/usr/bin/python '"'
"'~None/.ansible/tmp/ansible-tmp-1528295668.9-116784222039411/command.py'"'"' && sleep 0' root pts/4 localhost 22:34 10.00s 5.67s 0.58s w [root@centos-02 ~]# ansible testhost -m command -a 'hostname' centos-03 | SUCCESS | rc=0 >> centos-03 127.0.0.1 | SUCCESS | rc=0 >> centos-02 [root@centos-02 ~]#

2.也可以访问一台机器

[root@centos-02 ~]# ansible 127.0.0.1 -m command -a 'hostname'
127.0.0.1 | SUCCESS | rc=0 >>
centos-02

[root@centos-02 ~]# 

3.也支持shell模块

[root@centos-02 ~]# ansible 127.0.0.1 -m shell -a 'hostname'
127.0.0.1 | SUCCESS | rc=0 >>
centos-02

[root@centos-02 ~]# 

ansible拷贝文件或目录

 1.命令是将本地etc/ansible/目录拷贝到远程03服务器上/tmp/ansible_test目录下,下面我们到03服务器验证下

[root@centos-02 ~]# ansible centos-03 -m copy -a "src=/etc/ansible dest=/tmp/ansible_test owner=root group=root mode=0755"
centos-03 | SUCCESS => {
    "changed": true, 
    "dest": "/tmp/ansible_test/", 
    "src": "/etc/ansible"
}
[root@centos-02 ~]# 
[root@centos-03 ~]# ls /tmp/ansible_test/
ansible
[root@centos-03 ~]# cd /tmp/ansible_test/ansible/
[root@centos-03 ansible]# ls
ansible.cfg  hosts  roles
[root@centos-03 ansible]# 

2.针对文件拷贝

[root@centos-02 ~]# ansible centos-03 -m copy -a "src=/etc/passwd dest=/tmp/ansible_test owner=root group=root mode=0755"
centos-03 | SUCCESS => {
    "changed": true, 
    "checksum": "433544a73db6492e59d37e53399bb94d574ba97e", 
    "dest": "/tmp/ansible_test/passwd", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "d7c5478065eb1697f01b5a8bf5d36e54", 
    "mode": "0755", 
    "owner": "root", 
    "size": 2060, 
    "src": "~None/.ansible/tmp/ansible-tmp-1528384844.06-4438665225310/source", 
    "state": "file", 
    "uid": 0
}
[root@centos-02 ~]# 
[root@centos-03 ansible_test]# ls
ansible  passwd
[root@centos-03 ansible_test]# 

3.如果目标路径不是文件是个文件,则前面复制的文件将会直接命名为后面的文件名

[root@centos-02 ~]# ansible centos-03 -m copy -a "src=/etc/passwd dest=/tmp/ansible_test/1.txt owner=root group=root mode=0755"
centos-03 | SUCCESS => {
    "changed": true, 
    "checksum": "433544a73db6492e59d37e53399bb94d574ba97e", 
    "dest": "/tmp/ansible_test/1.txt", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "d7c5478065eb1697f01b5a8bf5d36e54", 
    "mode": "0755", 
    "owner": "root", 
    "size": 2060, 
    "src": "~None/.ansible/tmp/ansible-tmp-1528385166.92-37275315457835/source", 
    "state": "file", 
    "uid": 0
}
[root@centos-02 ~]# 

ansible远程执行脚本

1.首先建立一个脚本

[root@centos-02 ~]# vim /tmp/1.sh
[root@centos-02 ~]# cat /tmp/1.sh 
#!/bin/bash
echo 'date' > /tmp/ansible_test.txt
[root@centos-02 ~]# 

2.把该脚本分发到各个机器上

[root@centos-02 ~]# ansible testhost -m copy -a "src=/tmp/1.sh dest=/tmp/test.sh mode=0755"
centos-03 | SUCCESS => {
    "changed": true, 
    "checksum": "a094de1e64b947adffdcb4a10923340c5d44122f", 
    "dest": "/tmp/test.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "1f4604666d1ffdb2d23976057f9ac59d", 
    "mode": "0755", 
    "owner": "root", 
    "size": 48, 
    "src": "~None/.ansible/tmp/ansible-tmp-1528385778.31-196433195400666/source", 
    "state": "file", 
    "uid": 0
}
127.0.0.1 | SUCCESS => {
    "changed": true, 
    "checksum": "a094de1e64b947adffdcb4a10923340c5d44122f", 
    "dest": "/tmp/test.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "1f4604666d1ffdb2d23976057f9ac59d", 
    "mode": "0755", 
    "owner": "root", 
    "size": 48, 
    "src": "~None/.ansible/tmp/ansible-tmp-1528385778.22-196688321343541/source", 
    "state": "file", 
    "uid": 0
}
[root@centos-02 ~]# 

3.发现拷贝成功

[root@centos-02 ~]# ls /tmp/test.sh 
/tmp/test.sh
[root@centos-02 ~]# cat /tmp/test.sh 
#!/bin/bash
echo ·date· > /tmp/ansible_test.txt
[root@centos-03 ~]# cat /tmp/test.sh 
#!/bin/bash
echo ·date· > /tmp/ansible_test.txt
[root@centos-03 ~]# 

4.下面远程执行成功

[root@centos-02 ~]# ansible testhost -m shell -a "/tmp/test.sh"
127.0.0.1 | SUCCESS | rc=0 >>


centos-03 | SUCCESS | rc=0 >>


[root@centos-02 ~]# cat /tmp/ansible_test.txt 
date
[root@centos-02 ~]# 
[root@centos-03 ~]# cat /tmp/ansible_test.txt 
date
[root@centos-03 ~]# 

5.comment不支持管道,执行报错,shell可以

[root@centos-02 ~]# ansible testhost -m command -a "cat /etc/passwd|wc -l"
127.0.0.1 | FAILED | rc=1 >>
cat: invalid option -- 'l'
Try 'cat --help' for more information.non-zero return code

centos-03 | FAILED | rc=1 >>
cat: invalid option -- 'l'
Try 'cat --help' for more information.non-zero return code

[root@centos-02 ~]# 
[root@centos-02 ~]# ansible testhost -m shell -a "cat /etc/passwd|wc -l"
centos-03 | SUCCESS | rc=0 >>
27

127.0.0.1 | SUCCESS | rc=0 >>
40

[root@centos-02 ~]# 

ansible管理任务计划

1.使用cron模块给03服务器生成计划任务

[root@centos-02 ~]# ansible centos-03 -m cron -a "name='test cron' job='/bin/touch /tmp/1212.txt' weekday=6"
centos-03 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test cron"
    ]
}
[root@centos-02 ~]# 

2.验证生成结果

[root@centos-03 ~]# crontab -l
# Lines below here are managed by Salt, do not edit
#Ansible: test cron
* * * * 6 /bin/touch /tmp/1212.txt
[root@centos-03 ~]# 

3.删除计划任务

[root@centos-02 ~]# ansible centos-03 -m cron -a "name='test cron' state=absent"
centos-03 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}
[root@centos-02 ~]# 
[root@centos-03 ~]# crontab -l
# Lines below here are managed by Salt, do not edit
[root@centos-03 ~]# 

4.给计划任务加上、分时日月周 

[root@centos-02 ~]# ansible centos-03 -m cron -a "name='test cron' job='/bin/touch /tmp/1212.txt' minute=20 hour=10 weekday=6"
centos-03 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test cron"
    ]
}
[root@centos-03 ~]# crontab -l
# Lines below here are managed by Salt, do not edit
#Ansible: test cron
20 10 * * 6 /bin/touch /tmp/1212.txt
[root@centos-03 ~]# 

ansible安装包和管理服务

1.使用yum模块安装httpd,因为我们之前已经安装过了,所有提示已经安装过了。

[root@centos-02 ~]# ansible centos-03 -m yum -a "name=httpd"
centos-03 | SUCCESS => {
    "changed": false, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "httpd-2.4.6-80.el7.centos.x86_64 providing httpd is already installed"
    ]
}
[root@centos-02 ~]# 

2.卸载一个包

[root@centos-02 ~]# ansible centos-03 -m yum -a "name=httpd state=removed" 
centos-03 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-80.el7.centos will be erased\n--> Finished Dependency
Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version
Repository Size\n================================================================================\nRemoving:\n httpd x86_64 2.4.6-80.el7.centos @base
9.4 M\n\nTransaction Summary\n================================================================================\nRemove 1 Package\n\nInstalled size: 9.4 M\nDownloading packages
:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Erasing : httpd-2.4.6-80.el7.centos.x86_64
1/1 \n Verifying : httpd-2.4.6-80.el7.centos.x86_64 1/1 \n\nRemoved:\n httpd.x86_64 0:2.4.6-80.el7.centos
\n\nComplete!\n" ] } [root@centos-02 ~]#

3.验证httpd包已经没有了

[root@centos-03 ~]# rpm -qa httpd
[root@centos-03 ~]# 

4.我们再次安装httpd,安装成功。

[root@centos-02 ~]# ansible centos-03 -m yum -a "name=httpd state=installed" 
centos-03 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.tuna.tsinghua.edu.cn\n * epel: mirrors.tongji.edu.cn\n * extras: mirrors.huaweicl
oud.com\n * updates: mirrors.huaweicloud.com\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-80.el7.centos will be installed\n--> Finished
Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version
Repository Size\n================================================================================\nInstalling:\n httpd x86_64 2.4.6-80.el7.centos
base 2.7 M\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 2.7
M\nInstalled size: 9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing :
httpd-2.4.6-80.el7.centos.x86_64 1/1 \n Verifying : httpd-2.4.6-80.el7.centos.x86_64 1/1 \n\nInstalled:\n
httpd.x86_64 0:2.4.6-80.el7.centos \n\nComplete!\n" ] } [root@centos-02 ~]#
[root@centos-03 ~]# rpm -qa httpd
httpd-2.4.6-80.el7.centos.x86_64
[root@centos-03 ~]# 

5.启动httpd服务,enabled=no开启不启动,设置为yes是开机启动。

[root@centos-02 ~]# ansible centos-03 -m service -a "name=httpd state=started enabled=no" 
centos-03 | SUCCESS => {
    "changed": true, 
    "enabled": false, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestampMonotonic": "0", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "inactive", 
        "After": "-.mount system.slice remote-fs.target nss-lookup.target network.target tmp.mount systemd-journald.socket basic.target", 
        "AllowIsolate": "no", 
        "AmbientCapabilities": "0", 
        "AssertResult": "no", 
        "AssertTimestampMonotonic": "0", 
        "Before": "shutdown.target", 
        "BlockIOAccounting": "no", 
        "BlockIOWeight": "18446744073709551615", 
        "CPUAccounting": "no", 
        "CPUQuotaPerSecUSec": "infinity", 
        "CPUSchedulingPolicy": "0", 
        "CPUSchedulingPriority": "0", 
        "CPUSchedulingResetOnFork": "no", 
        "CPUShares": "18446744073709551615", 
        "CanIsolate": "no", 
        "CanReload": "yes", 
        "CanStart": "yes", 
        "CanStop": "yes", 
        "CapabilityBoundingSet": "18446744073709551615", 
        "ConditionResult": "no", 
        "ConditionTimestampMonotonic": "0", 
        "Conflicts": "shutdown.target", 
        "ControlPID": "0", 
        "DefaultDependencies": "yes", 
        "Delegate": "no", 
        "Description": "The Apache HTTP Server", 
        "DevicePolicy": "auto", 
        "Documentation": "man:httpd(8) man:apachectl(8)", 
        "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)", 
        "ExecMainCode": "0", 
        "ExecMainExitTimestampMonotonic": "0", 
        "ExecMainPID": "0", 
        "ExecMainStartTimestampMonotonic": "0", 
        "ExecMainStatus": "0", 
        "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; 
status=0/0 }", "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ;
status=0/0 }", "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "FailureAction": "none", "FileDescriptorStoreMax": "0", "FragmentPath": "/usr/lib/systemd/system/httpd.service", "GuessMainPID": "yes", "IOScheduling": "0", "Id": "httpd.service", "IgnoreOnIsolate": "no", "IgnoreOnSnapshot": "no", "IgnoreSIGPIPE": "yes", "InactiveEnterTimestampMonotonic": "0", "InactiveExitTimestampMonotonic": "0", "JobTimeoutAction": "none", "JobTimeoutUSec": "0", "KillMode": "control-group", "KillSignal": "18", "LimitAS": "18446744073709551615", "LimitCORE": "18446744073709551615", "LimitCPU": "18446744073709551615", "LimitDATA": "18446744073709551615", "LimitFSIZE": "18446744073709551615", "LimitLOCKS": "18446744073709551615", "LimitMEMLOCK": "65536", "LimitMSGQUEUE": "819200", "LimitNICE": "0", "LimitNOFILE": "4096", "LimitNPROC": "3829", "LimitRSS": "18446744073709551615", "LimitRTPRIO": "0", "LimitRTTIME": "18446744073709551615", "LimitSIGPENDING": "3829", "LimitSTACK": "18446744073709551615", "LoadState": "loaded", "MainPID": "0", "MemoryAccounting": "no", "MemoryCurrent": "18446744073709551615", "MemoryLimit": "18446744073709551615", "MountFlags": "0", "Names": "httpd.service", "NeedDaemonReload": "no", "Nice": "0", "NoNewPrivileges": "no", "NonBlocking": "no", "NotifyAccess": "main", "OOMScoreAdjust": "0", "OnFailureJobMode": "replace", "PermissionsStartOnly": "no", "PrivateDevices": "no", "PrivateNetwork": "no", "PrivateTmp": "yes", "ProtectHome": "no", "ProtectSystem": "no", "RefuseManualStart": "no", "RefuseManualStop": "no", "RemainAfterExit": "no", "Requires": "-.mount basic.target", "RequiresMountsFor": "/var/tmp", "Restart": "no", "RestartUSec": "100ms", "Result": "success", "RootDirectoryStartOnly": "no", "RuntimeDirectoryMode": "0755", "SameProcessGroup": "no", "SecureBits": "0", "SendSIGHUP": "no", "SendSIGKILL": "yes", "Slice": "system.slice", "StandardError": "inherit", "StandardInput": "null", "StandardOutput": "journal", "StartLimitAction": "none", "StartLimitBurst": "5", "StartLimitInterval": "10000000", "StartupBlockIOWeight": "18446744073709551615", "StartupCPUShares": "18446744073709551615", "StatusErrno": "0", "StopWhenUnneeded": "no", "SubState": "dead", "SyslogLevelPrefix": "yes", "SyslogPriority": "30", "SystemCallErrorNumber": "0", "TTYReset": "no", "TTYVHangup": "no", "TTYVTDisallocate": "no", "TasksAccounting": "no", "TasksCurrent": "18446744073709551615", "TasksMax": "18446744073709551615", "TimeoutStartUSec": "1min 30s", "TimeoutStopUSec": "1min 30s", "TimerSlackNSec": "50000", "Transient": "no", "Type": "notify", "UMask": "0022", "UnitFilePreset": "disabled", "UnitFileState": "disabled", "Wants": "system.slice", "WatchdogTimestampMonotonic": "0", "WatchdogUSec": "0" } } [root@centos-02 ~]#
[root@centos-03 ~]# ps aux|grep httpd
root      29490  0.1  0.4 223964  4924 ?        Ss   23:03   0:00 /usr/sbin/httpd -DFOREGROUND
apache    29491  0.0  0.2 223964  2940 ?        S    23:03   0:00 /usr/sbin/httpd -DFOREGROUND
apache    29492  0.0  0.2 223964  2940 ?        S    23:03   0:00 /usr/sbin/httpd -DFOREGROUND
apache    29493  0.0  0.2 223964  2940 ?        S    23:03   0:00 /usr/sbin/httpd -DFOREGROUND
apache    29494  0.0  0.2 223964  2940 ?        S    23:03   0:00 /usr/sbin/httpd -DFOREGROUND
apache    29495  0.0  0.2 223964  2940 ?        S    23:03   0:00 /usr/sbin/httpd -DFOREGROUND
root      29625  0.0  0.0 112664   928 pts/1    R+   23:05   0:00 grep --color=auto http
[root@centos-03 ~]# 

6.查看ansiable所有的模块,常用的就几个server 、yum等。

[root@centos-02 ~]# ansible-doc -l

7.查看包用法

[root@centos-02 ~]# ansible-doc service

使用ansible playbook

 1.playbook把所有的配置放到一个配置文件里

[root@centos-02 ~]# cd /etc/ansible/
[root@centos-02 ansible]# vi test.yml
[root@centos-02 ansible]# cat test.yml 
---
- hosts: centos-03
  remote_user: root
  tasks:
    - name: test_playbook
      shell: touch /tmp/linux.txt
[root@centos-02 ansible]# 

2.执行文件

[root@centos-02 ansible]# ansible-playbook test.yml 

PLAY [centos-03] ************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [centos-03]

TASK [test_playbook] ********************************************************************
 [WARNING]: Consider using the file module with state=touch rather than running touch.
If you need to use command because file is insufficient you can add warn=False to this
command task or set command_warnings=False in ansible.cfg to get rid of this message.

changed: [centos-03]

PLAY RECAP ******************************************************************************
centos-03                  : ok=2    changed=1    unreachable=0    failed=0   

[root@centos-02 ansible]# 

3.检查03服务器是否有文件

[root@centos-03 ~]# ls -l /tmp/linux.txt 
-rw-r--r-- 1 root root 0 6月  12 22:12 /tmp/linux.txt
[root@centos-03 ~]# 

playbook里的变量

1.创建用户的playbooks

[root@centos-02 ansible]# vim /etc/ansible/create_user.yml
[root@centos-02 ansible]# cat /etc/ansible/create_user.yml 
---
- name: create_user
  hosts: centos-03
  user: root
  gather_facts: false
  vars:
    - user: "test"
  tasks:
    - name: create user
      user: name="{{ user }}"
[root@centos-02 ansible]# ansible-playbook create_user.yml 
[root@centos-02 ansible]# ansible-playbook create_user.yml 

PLAY [create_user] **********************************************************************

TASK [create user] **********************************************************************
changed: [centos-03]

PLAY RECAP ******************************************************************************
centos-03                  : ok=1    changed=1    unreachable=0    failed=0   

[root@centos-02 ansible]# 

2.检查是否创建成功test用户

[root@centos-03 ~]# id test
uid=1002(test) gid=1002(test) 组=1002(test)
[root@centos-03 ~]# 

 playbook循环

1.编辑循环配置文件提示03服务器没有文件

[root@centos-02 ansible]# vim /etc/ansible/while.yml
[root@centos-02 ansible]# cat /etc/ansible/while.yml 
---
- hosts: centos-03
  user: root
  tasks:
    - name: change mode for files
      file: path=/tmp/{{ item }} mode=600
      with_items:
        - 1.txt
        - 2.txt
        - 3.txt
[root@centos-02 ansible]# 
[root@centos-02 ansible]# ansible-playbook while.yml 

PLAY [centos-03] ************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [centos-03]

TASK [change mode for files] ************************************************************
failed: [centos-03] (item=1.txt) => {"changed": false, "item": "1.txt", "msg": "file (/tmp/1.txt) is absent, cannot continue", "path": "/tmp/1.txt", "state": "absent"}
failed: [centos-03] (item=2.txt) => {"changed": false, "item": "2.txt", "msg": "file (/tmp/2.txt) is absent, cannot continue", "path": "/tmp/2.txt", "state": "absent"}
failed: [centos-03] (item=3.txt) => {"changed": false, "item": "3.txt", "msg": "file (/tmp/3.txt) is absent, cannot continue", "path": "/tmp/3.txt", "state": "absent"}
	to retry, use: --limit @/etc/ansible/while.retry

PLAY RECAP ******************************************************************************
centos-03                  : ok=1    changed=0    unreachable=0    failed=1   

[root@centos-02 ansible]# 

2.我们再编辑配置文件创建3个文件

[root@centos-02 ansible]# vim /etc/ansible/while.yml
[root@centos-02 ansible]# cat /etc/ansible/while.yml 
---
- hosts: centos-03
  user: root
  tasks:
    - name: change mode for files
      file: path=/tmp/{{ item }} state=touch mode=600
      with_items:
        - 1.txt
        - 2.txt
        - 3.txt
[root@centos-02 ansible]# 
[root@centos-02 ansible]# ansible-playbook while.yml 

PLAY [centos-03] ************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [centos-03]

TASK [change mode for files] ************************************************************
changed: [centos-03] => (item=1.txt)
changed: [centos-03] => (item=2.txt)
changed: [centos-03] => (item=3.txt)

PLAY RECAP ******************************************************************************
centos-03                  : ok=2    changed=1    unreachable=0    failed=0   

[root@centos-02 ansible]# 
[root@centos-03 ~]# ls -l /tmp/1.txt /tmp/2.txt /tmp/3.txt
-rw------- 1 root root 0 6月  12 22:48 /tmp/1.txt
-rw------- 1 root root 0 6月  12 22:48 /tmp/2.txt
-rw------- 1 root root 0 6月  12 22:48 /tmp/3.txt
[root@centos-03 ~]#  

playbook中的条件判断  

 

1.执行setup命令查看ip地址路径,针对ip地址做为判断条件

[root@centos-02 ~]# ansible centos-03 -m setup (命令结果就是gather_facts)
centos-03 | SUCCESS => {
        "ansible_ens33": {
            "ipv4": {
                "address": "192.168.133.66", 

2.编辑配置文件

[root@centos-02 ~]# vim when.yml
[root@centos-02 ~]# cat when.yml 
---
- hosts: testhost
  user: root
  gather_facts: True
  tasks:
    - name: use when
      shell: touch /tmp/when.txt
      when: ansible_ens33.ipv4.address == "192.168.133.66"
[root@centos-02 ~]# 

3.执行

[root@centos-02 ~]# ansible-playbook when.yml 

PLAY [testhost] *************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [centos-03]
ok: [127.0.0.1]

TASK [use when] *************************************************************************
skipping: [127.0.0.1]
 [WARNING]: Consider using the file module with state=touch rather than running touch.
If you need to use command because file is insufficient you can add warn=False to this
command task or set command_warnings=False in ansible.cfg to get rid of this message.

changed: [centos-03]

PLAY RECAP ******************************************************************************
127.0.0.1                  : ok=1    changed=0    unreachable=0    failed=0   
centos-03                  : ok=2    changed=1    unreachable=0    failed=0   

[root@centos-02 ~]# 

playbook中的handlers  

 

1.hander相当于&&并且的意思,前面的命令执行完成之后执行后面的命令,用notify关联起来

[root@centos-02 ~]# vim hand.yml
[root@centos-02 ~]# cat hand.yml 
---
- name: handlers test
  hosts: centos-03
  user: root
  tasks:
    - name: copy file
      copy: src=/etc/passwd dest=/tmp/aaa.txt
      notify: test handlers
  handlers:
    - name: test handlers
      shell: echo "11111" >> /tmp/aaa.txt
[root@centos-02 ~]# 

2.执行命令

[root@centos-02 ~]# ansible-playbook hand.yml 

PLAY [handlers test] ********************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [centos-03]

TASK [copy file] ************************************************************************
changed: [centos-03]

RUNNING HANDLER [test handlers] *********************************************************
changed: [centos-03]

PLAY RECAP ******************************************************************************
centos-03                  : ok=3    changed=2    unreachable=0    failed=0   

[root@centos-02 ~]# 

3.查看03服务器

[root@centos-03 ~]# tail /tmp/aaa.txt 
mongod:x:993:991:mongod:/var/lib/mongo:/bin/false
git:x:1007:1007::/home/git:/usr/bin/git-shell
zhangsan:x:1008:1008::/home/jail/./home/zhangsan:/usr/sbin/jk_chrootsh
admin:x:1009:1009::/home/admin:/bin/bash
lisi:x:1010:1010::/home/lisi:/home/jumpserver-0.3.3/init.sh
wangwu:x:1011:1011::/home/wangwu:/home/jumpserver-0.3.3/init.sh
zhaoliu:x:1012:1012::/home/zhaoliu:/home/jumpserver-0.3.3/init.sh
sun4:x:1013:1013::/home/sun4:/home/jumpserver-0.3.3/init.sh
saslauth:x:992:76:Saslauthd user:/run/saslauthd:/sbin/nologin
11111
[root@centos-03 ~]# 

用playbook安装nginx(上)  

1.建目录

[root@centos-02 ansible]# pwd
/etc/ansible
[root@centos-02 ansible]# mkdir nginx_install
[root@centos-02 ansible]# cd nginx_install/
[root@centos-02 nginx_install]# mkdir -p roles/{common,install}/{handlers,files,meta,tasks,templates,vars}
[root@centos-02 nginx_install]# ls
roles
[root@centos-02 nginx_install]# ls roles/
common  install
[root@centos-02 nginx_install]# ls roles/install/
files  handlers  meta  tasks  templates  vars
[root@centos-02 nginx_install]# ls roles/common/
files  handlers  meta  tasks  templates  vars
[root@centos-02 nginx_install]# 

2.准备文件

 1.安装nginx后

[root@centos-02 conf]# ls /usr/local/nginx/  (nginx安装目录)
client_body_temp  fastcgi_temp  logs        sbin       uwsgi_temp
conf              html          proxy_temp  scgi_temp
[root@centos-02 conf]# ls /etc/init.d/nginx (nignx启动脚本)
/etc/init.d/nginx
[root@centos-02 conf]# ls /usr/local/nginx/conf/nginx.conf (nginx配置文件)
/usr/local/nginx/conf/nginx.conf
[root@centos-02 conf]# 

2.打包

[root@centos-02 conf]# cd /usr/local/
[root@centos-02 local]# tar czvf nginx.tar.gz --exclude "nginx.conf" --exclude "vhost" nginx/
nginx/
nginx/sbin/
nginx/sbin/nginx
nginx/conf/
nginx/conf/koi-win
nginx/conf/koi-utf
nginx/conf/win-utf
nginx/conf/mime.types
nginx/conf/mime.types.default
nginx/conf/fastcgi_params
nginx/conf/fastcgi_params.default
nginx/conf/fastcgi.conf
nginx/conf/fastcgi.conf.default
nginx/conf/uwsgi_params
nginx/conf/uwsgi_params.default
nginx/conf/scgi_params
nginx/conf/scgi_params.default
nginx/conf/nginx.conf.default
nginx/conf/nginx.conf.bak
nginx/logs/
nginx/logs/error.log
nginx/logs/nginx.pid
nginx/logs/nginx_error.log
nginx/logs/access.log
nginx/html/
nginx/html/50x.html
nginx/html/index.html
nginx/client_body_temp/
nginx/proxy_temp/
nginx/fastcgi_temp/
nginx/uwsgi_temp/
nginx/scgi_temp/
[root@centos-02 local]# 

3.拷贝文件

[root@centos-02 local]# mv nginx.tar.gz /etc/ansible/nginx_install/roles/install/files/
[root@centos-02 local]# cp nginx/conf/nginx.conf /etc/ansible/nginx_install/roles/install/templates/
[root@centos-02 local]# cp /etc/init.d/nginx /etc/ansible/nginx_install/roles/install/templates/
[root@centos-02 local]# 

4.创建main文件

[root@centos-02 local]# cd /etc/ansible/nginx_install/roles/
[root@centos-02 roles]# ls
common  install
[root@centos-02 roles]# cd common/
[root@centos-02 common]# ls
files  handlers  meta  tasks  templates  vars
[root@centos-02 common]# vi tasks/main.yml
[root@centos-02 common]# cat tasks/main.yml 
- name: Install initializtion require software
  yum: name={{ item }} state=installed (如果不行,可以修改成:yum: name="pcre-devel,zlib-devel" state=installed)
  with_items:
    - zlib-devel
    - pcre-devel
[root@centos-02 common]# 

5.定义变量

[root@centos-02 common]# vim /etc/ansible/nginx_install/roles/install/vars/main.yml
[root@centos-02 common]# cat /etc/ansible/nginx_install/roles/install/vars/main.yml 
nginx_user: www
nginx_port: 80
nginx_basedir: /usr/local/nginx
[root@centos-02 common]#

6.拷贝配置文件(子配置文件)

[root@centos-02 common]# vim /etc/ansible/nginx_install/roles/install/tasks/copy.yml
[root@centos-02 common]# cat /etc/ansible/nginx_install/roles/install/tasks/copy.yml
- name: Copy Nginx Software
  copy: src=nginx.tar.gz dest=/tmp/nginx.tar.gz owner=root group=root
- name: Uncompression Nginx Software
  shell: tar zxf /tmp/nginx.tar.gz -C /usr/local/
- name: Copy Nginx Start Script
  template: src=nginx dest=/etc/init.d/nginx owner=root group=root mode=0755
- name: Copy Nginx Config
  template: src=nginx.conf dest={{ nginx_basedir }}/conf/ owner=root group=root mode=0644
[root@centos-02 common]# 

用playbook安装nginx(下)

1.编辑安装的配置文件

[root@centos-02 common]# vim /etc/ansible/nginx_install/roles/install/tasks/install.yml
[root@centos-02 common]# cat /etc/ansible/nginx_install/roles/install/tasks/install.yml
- name: Create Nginx User
  user: name={{ nginx_user }} state=present createhome=no shell=/sbin/nologin
- name: Start Nginx Service
  shell: /etc/init.d/nginx start
- name: Add Boot Start Nginx Service
  shell: chkconfig --level 345 nginx on
- name: Delete Nginx compression files
  shell: rm -rf /tmp/nginx.tar.gz
[root@centos-02 common]# 

[root@centos-02 common]# cd ..
[root@centos-02 roles]# 
[root@centos-02 roles]# ls
common  install
[root@centos-02 roles]# cd install/
[root@centos-02 install]# ls
files  handlers  meta  tasks  templates  vars
[root@centos-02 install]# cd tasks/
[root@centos-02 tasks]# ls
copy.yml  install.yml
[root@centos-02 tasks]# vim main.yml
[root@centos-02 tasks]# cat main.yml 
- include: copy.yml
- include: install.yml
[root@centos-02 tasks]# 

1.添加入口文件

[root@centos-02 tasks]# vim /etc/ansible/nginx_install/install.yml
[root@centos-02 tasks]# cat /etc/ansible/nginx_install/install.yml
---
- hosts: testhost
  remote_user: root
  gather_facts: True
  roles:
    - common
    - install
[root@centos-02 tasks]# 

2.运行失败

[root@centos-02 tasks]# ansible-playbook /etc/ansible/nginx_install/install.yml 

PLAY [testhost] *************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [centos-03]
ok: [127.0.0.1]

TASK [common : Install initializtion require software] **********************************
failed: [centos-03] (item=[u'zlib-devel', u'pcre-devel']) => {"changed": false, "item": ["zlib-devel", "pcre-devel"], "msg": "No Package matching '['zlib-devel'' found available, 
installed or updated", "rc": 0, "results": []} failed: [127.0.0.1] (item=[u'zlib-devel', u'pcre-devel']) => {"changed": false, "item": ["zlib-devel", "pcre-devel"], "msg": "No Package matching '['zlib-devel'' found available,
installed or updated", "rc": 0, "results": []} to retry, use: --limit @/etc/ansible/nginx_install/install.retry PLAY RECAP ****************************************************************************** 127.0.0.1 : ok=1 changed=0 unreachable=0 failed=1 centos-03 : ok=1 changed=0 unreachable=0 failed=1 [root@centos-02 tasks]#

3.编辑配置文件并重新启动

[root@centos-02 tasks]# vim /etc/ansible/nginx_install/roles/common/tasks/main.yml 
[root@centos-02 tasks]# cat /etc/ansible/nginx_install/roles/common/tasks/main.yml 
- name: Install initializtion require software
  yum: name="pcre-devel,zlib-devel" state=installed
[root@centos-02 tasks]# ansible-playbook /etc/ansible/nginx_install/install.yml 

PLAY [testhost] *************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [centos-03]
ok: [127.0.0.1]

TASK [common : Install initializtion require software] **********************************
ok: [127.0.0.1]
changed: [centos-03]

TASK [install : Copy Nginx Software] ****************************************************
changed: [centos-03]
changed: [127.0.0.1]

TASK [install : Uncompression Nginx Software] *******************************************
 [WARNING]: Consider using the unarchive module rather than running tar.  If you need to
use command because unarchive is insufficient you can add warn=False to this command
task or set command_warnings=False in ansible.cfg to get rid of this message.

changed: [centos-03]
changed: [127.0.0.1]

TASK [install : Copy Nginx Start Script] ************************************************
changed: [centos-03]
ok: [127.0.0.1]

TASK [install : Copy Nginx Config] ******************************************************
ok: [127.0.0.1]
changed: [centos-03]

TASK [install : Create Nginx User] ******************************************************
changed: [centos-03]
changed: [127.0.0.1]

TASK [install : Start Nginx Service] ****************************************************
changed: [127.0.0.1]
changed: [centos-03]

TASK [install : Add Boot Start Nginx Service] *******************************************
changed: [127.0.0.1]
changed: [centos-03]

TASK [install : Delete Nginx compression files] *****************************************
 [WARNING]: Consider using the file module with state=absent rather than running rm.  If
you need to use command because file is insufficient you can add warn=False to this
command task or set command_warnings=False in ansible.cfg to get rid of this message.

changed: [centos-03]
changed: [127.0.0.1]

PLAY RECAP ******************************************************************************
127.0.0.1                  : ok=10   changed=6    unreachable=0    failed=0   
centos-03                  : ok=10   changed=9    unreachable=0    failed=0   

[root@centos-02 tasks]# 

4.我x不成功启动了系统自带的nginx,我们将自带的nginx卸载,重新执行

[root@centos-03 ~]# netstat -lntp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      998/sshd            
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1942/master         
tcp        0      0 0.0.0.0:10050           0.0.0.0:*               LISTEN      931/zabbix_agentd   
tcp        0      0 192.168.133.66:27017    0.0.0.0:*               LISTEN      1893/mongod         
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      1893/mongod         
tcp6       0      0 :::3306                 :::*                    LISTEN      1399/mysqld         
tcp6       0      0 :::22                   :::*                    LISTEN      998/sshd            
tcp6       0      0 ::1:25                  :::*                    LISTEN      1942/master         
tcp6       0      0 :::10050                :::*                    LISTEN      931/zabbix_agentd   
[root@centos-03 ~]# ps aux|grep nginx
root      51783  0.0  0.2 122896  2108 ?        Ss   23:38   0:00 nginx: master process /usr/sbin/nginx
nginx     51784  0.0  0.3 123360  3136 ?        S    23:38   0:00 nginx: worker process
root      51993  0.0  0.0 112668   932 pts/1    R+   23:39   0:00 grep --color=auto ngin
[root@centos-03 ~]# 
[root@centos-03 ~]# yum remove nginx
[root@centos-02 tasks]# ansible-playbook /etc/ansible/nginx_install/install.yml

5.这次就对了

[root@centos-03 ~]# ps aux|grep nginx
root      52822  0.0  0.0  20496   624 ?        Ss   23:44   0:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nobody    52823  0.0  0.3  22984  3200 ?        S    23:44   0:00 nginx: worker process
nobody    52824  0.0  0.3  22984  3200 ?        S    23:44   0:00 nginx: worker process
root      52967  0.0  0.0 112668   932 pts/1    R+   23:44   0:00 grep --color=auto ngin
[root@centos-03 ~]# 

playbook管理配置文件(上)  

1.创建nginxconfig的目录

[root@centos-02 tasks]# cd 
[root@centos-02 ~]# mkdir -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}
[root@centos-02 ~]# cd /etc/ansible/
[root@centos-02 ansible]# ls
ansible.cfg        create_user.yml  nginx_config   roles     while.retry
create_user.retry  hosts            nginx_install  test.yml  while.yml
[root@centos-02 ansible]# cd nginx_config/
[root@centos-02 nginx_config]# ls
roles
[root@centos-02 nginx_config]# ls roles/
new  old
[root@centos-02 nginx_config]# 

2.拷贝文件

[root@centos-02 conf]# cp -r  nginx.conf /etc/ansible/nginx_config/roles/new/files/
cp: overwrite ‘/etc/ansible/nginx_config/roles/new/files/nginx.conf’? y
[root@centos-02 conf]# 

[root@centos-02 conf]# vim /etc/ansible/nginx_config/roles/new/vars/main.yml
[root@centos-02 conf]# cat /etc/ansible/nginx_config/roles/new/vars/main.yml
nginx_basedir: /usr/local/nginx
[root@centos-02 conf]# vim /etc/ansible/nginx_config/roles/new/handlers/main.yml
[root@centos-02 conf]# cat /etc/ansible/nginx_config/roles/new/handlers/main.yml
- name: restart nginx
  shell: /etc/init.d/nginx reload
[root@centos-02 conf]# vim /etc/ansible/nginx_config/roles/new/tasks/main.yml
[root@centos-02 conf]# cat /etc/ansible/nginx_config/roles/new/tasks/main.yml
- name: copy conf file
  copy: src={{ item.src }} dest={{ nginx_basedir }}/{{ item.dest }} backup=yes owner=root group=root mode=0644
  with_items:
    - { src: nginx.conf, dest: conf/nginx.conf }
###    - { src: vhosts, dest: conf/ }
  notify: restart nginx
[root@centos-02 conf]# 

1.总入口文件

[root@centos-02 ~]# vim /etc/ansible/nginx_config/update.yml
[root@centos-02 ~]# cat /etc/ansible/nginx_config/update.yml
---
- hosts: centos-03
  user: root
  roles:
  - new
[root@centos-02 ~]# 

2.成功

[root@centos-02 ~]# ansible-playbook /etc/ansible/nginx_config/update.yml 

PLAY [centos-03] ************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [centos-03]

TASK [new : copy conf file] *************************************************************
ok: [centos-03] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})

PLAY RECAP ******************************************************************************
centos-03                  : ok=2    changed=0    unreachable=0    failed=0   

[root@centos-02 ~]# 

3.我们给nginx文件做个变更试试

[root@centos-02 ~]# cd /etc/ansible/nginx_config/roles/new/files/
[root@centos-02 files]# vim nginx.conf 
[root@centos-02 files]# cat nginx.conf 
user nobody nobody;                               
worker_processes 2;                            
error_log /usr/local/nginx/logs/nginx_error.log crit;           
pid /usr/local/nginx/logs/nginx.pid;                     
worker_rlimit_nofile 51200;                            
events
{
    use epoll;
    worker_connections 6000;                           
}
http
{
    include mime.types;
    default_type application/octet-stream;
    server_names_hash_bucket_size 3526;
    server_names_hash_max_size 4096;
    log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
    ' $host "$request_uri" $status'
    ' "$http_referer" "$http_user_agent"';
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 30;
    client_header_timeout 3m;
    client_body_timeout 3m;
    send_timeout 3m;
    connection_pool_size 256;
    client_header_buffer_size 1k;
    large_client_header_buffers 8 4k;
    request_pool_size 4k;
    output_buffers 4 32k;
    postpone_output 1460;
    client_max_body_size 10m;
    client_body_buffer_size 256k;
    client_body_temp_path /usr/local/nginx/client_body_temp;
    proxy_temp_path /usr/local/nginx/proxy_temp;
    fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
    fastcgi_intercept_errors on;
    tcp_nodelay on;
   # gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 8k;
    gzip_comp_level 5;
    gzip_http_version 1.1;
    gzip_types text/plain application/x-javascript text/css text/htm
    application/xml;
    server                                 
    {
        listen 8080;                                
        server_name localhost;                         
        index index.html index.htm index.php;                
        root /usr/local/nginx/html;                      
        location ~ \.php$                               
        {
            include fastcgi_params;
            fastcgi_pass unix:/tmp/php-fcgi.sock;
           #fastcgi_pass 127.0.0.1:9000;   (和上面一行的意思相同,只是不同的写法,监听127.0.0.1:9000)
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;
        }   
    }
}
[root@centos-02 files]# 
[root@centos-02 files]# ansible-playbook /etc/ansible/nginx_config/update.yml 

PLAY [centos-03] ************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [centos-03]

TASK [new : copy conf file] *************************************************************
changed: [centos-03] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})

RUNNING HANDLER [new : restart nginx] ***************************************************
changed: [centos-03]

PLAY RECAP ******************************************************************************
centos-03                  : ok=3    changed=2    unreachable=0    failed=0   

[root@centos-02 files]# 

4.03服务器也做了变更了

[root@centos-03 ansible]# cat /usr/local/nginx/conf/nginx.conf
user nobody nobody;                               
worker_processes 2;                            
error_log /usr/local/nginx/logs/nginx_error.log crit;           
pid /usr/local/nginx/logs/nginx.pid;                     
worker_rlimit_nofile 51200;                            
events
{
    use epoll;
    worker_connections 6000;                           
}
http
{
    include mime.types;
    default_type application/octet-stream;
    server_names_hash_bucket_size 3526;
    server_names_hash_max_size 4096;
    log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
    ' $host "$request_uri" $status'
    ' "$http_referer" "$http_user_agent"';
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 30;
    client_header_timeout 3m;
    client_body_timeout 3m;
    send_timeout 3m;
    connection_pool_size 256;
    client_header_buffer_size 1k;
    large_client_header_buffers 8 4k;
    request_pool_size 4k;
    output_buffers 4 32k;
    postpone_output 1460;
    client_max_body_size 10m;
    client_body_buffer_size 256k;
    client_body_temp_path /usr/local/nginx/client_body_temp;
    proxy_temp_path /usr/local/nginx/proxy_temp;
    fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
    fastcgi_intercept_errors on;
    tcp_nodelay on;
   # gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 8k;
    gzip_comp_level 5;
    gzip_http_version 1.1;
    gzip_types text/plain application/x-javascript text/css text/htm
    application/xml;
    server                                 
    {
        listen 8080;                                
        server_name localhost;                         
        index index.html index.htm index.php;                
        root /usr/local/nginx/html;                      
        location ~ \.php$                               
        {
            include fastcgi_params;
            fastcgi_pass unix:/tmp/php-fcgi.sock;
           #fastcgi_pass 127.0.0.1:9000;   (和上面一行的意思相同,只是不同的写法,监听127.0.0.1:9000)
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;
        }   
    }
}
[root@centos-03 ansible]# 

playbook管理配置文件(下)  

1.首先需要将new下面的文件都拷贝到old下面

[root@centos-02 files]# rsync -av /etc/ansible/nginx_config/roles/new/ /etc/ansible/nginx_config/roles/old/
sending incremental file list
files/
files/nginx.conf
handlers/
handlers/main.yml
tasks/
tasks/main.yml
vars/
vars/main.yml

sent 2873 bytes  received 104 bytes  5954.00 bytes/sec
total size is 2485  speedup is 0.83
[root@centos-02 files]# 
[root@centos-02 files]# rsync -av ./ /etc/ansible/nginx_config/roles/old/files/
sending incremental file list

sent 45 bytes  received 12 bytes  114.00 bytes/sec
total size is 2176  speedup is 38.18
[root@centos-02 files]# 
[root@centos-02 files]# vim nginx.conf 
[root@centos-02 files]# cat nginx.conf 
user nobody nobody;                               
worker_processes 2;                            
error_log /usr/local/nginx/logs/nginx_error.log crit;           
pid /usr/local/nginx/logs/nginx.pid;                     
worker_rlimit_nofile 51200;                            
events
{
    use epoll;
    worker_connections 6000;                           
}
http
{
    include mime.types;
    default_type application/octet-stream;
    server_names_hash_bucket_size 3526;
    server_names_hash_max_size 4096;
    log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
    ' $host "$request_uri" $status'
    ' "$http_referer" "$http_user_agent"';
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 30;
    client_header_timeout 3m;
    client_body_timeout 3m;
    send_timeout 3m;
    connection_pool_size 256;
    client_header_buffer_size 1k;
    large_client_header_buffers 8 4k;
    request_pool_size 4k;
    output_buffers 4 32k;
    postpone_output 1460;
    client_max_body_size 10m;
    client_body_buffer_size 256k;
    client_body_temp_path /usr/local/nginx/client_body_temp;
    proxy_temp_path /usr/local/nginx/proxy_temp;
    fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
    fastcgi_intercept_errors on;
    tcp_nodelay on;
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 8k;
    gzip_comp_level 5;
    gzip_http_version 1.1;
    gzip_types text/plain application/x-javascript text/css text/htm
    application/xml;
    server                                 
    {
        listen 8080;                                
        server_name localhost;                         
        index index.html index.htm index.php;                
        root /usr/local/nginx/html;                      
        location ~ \.php$                               
        {
            include fastcgi_params;
            fastcgi_pass unix:/tmp/php-fcgi.sock;
           #fastcgi_pass 127.0.0.1:9000;   (和上面一行的意思相同,只是不同的写法,监听127.0.0.1:9000)
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;
        }   
    }
}
[root@centos-02 files]# ansible-playbook /etc/ansible/nginx_config/update.yml 

PLAY [centos-03] ************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [centos-03]

TASK [new : copy conf file] *************************************************************
changed: [centos-03] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})

RUNNING HANDLER [new : restart nginx] ***************************************************
changed: [centos-03]

PLAY RECAP ******************************************************************************
centos-03                  : ok=3    changed=2    unreachable=0    failed=0   

[root@centos-02 files]# rsync -av ./ /etc/ansible/nginx_config/roles/old/files/
sending incremental file list
./
nginx.conf

sent 2266 bytes  received 34 bytes  4600.00 bytes/sec
total size is 2175  speedup is 0.95
[root@centos-02 files]# 
[root@centos-02 files]# vim nginx.conf 
[root@centos-02 files]# cat nginx.conf 
user nobody nobody;                               
worker_processes 2;                            
error_log /usr/local/nginx/logs/nginx_error.log crit;           
pid /usr/local/nginx/logs/nginx.pid;                     
worker_rlimit_nofile 51200;                            
events
{
    use epoll;
    worker_connections 6000;                           
}
http
{
    include mime.types;
    default_type application/octet-stream;
    server_names_hash_bucket_size 3526;
    server_names_hash_max_size 4096;
    log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
    ' $host "$request_uri" $status'
    ' "$http_referer" "$http_user_agent"';
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 30;
    client_header_timeout 3m;
    client_body_timeout 3m;
    send_timeout 3m;
    connection_pool_size 256;
    client_header_buffer_size 1k;
    large_client_header_buffers 8 4k;
    request_pool_size 4k;
    output_buffers 4 32k;
    postpone_output 1460;
    client_max_body_size 10m;
    client_body_buffer_size 256k;
    client_body_temp_path /usr/local/nginx/client_body_temp;
    proxy_temp_path /usr/local/nginx/proxy_temp;
    fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
    fastcgi_intercept_errors on;
    tcp_nodelay on;
   # gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 8k;
    gzip_comp_level 5;
    gzip_http_version 1.1;
    gzip_types text/plain application/x-javascript text/css text/htm
    application/xml;
    server                                 
    {
        listen 8080;                                
        server_name localhost;                         
        index index.html index.htm index.php;                
        root /usr/local/nginx/html;                      
        location ~ \.php$                               
        {
            include fastcgi_params;
            fastcgi_pass unix:/tmp/php-fcgi.sock;
           #fastcgi_pass 127.0.0.1:9000;   (和上面一行的意思相同,只是不同的写法,监听127.0.0.1:9000)
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;
        }   
    }
}
[root@centos-02 files]# 
[root@centos-02 files]# cd ..
[root@centos-02 new]# cd ..
[root@centos-02 roles]# ls
new  old
[root@centos-02 roles]# cd ..
[root@centos-02 nginx_config]# cp update.yml rollback.yml
[root@centos-02 nginx_config]# vim rollback.yml 
[root@centos-02 nginx_config]# cat rollback.yml 
---
- hosts: centos-03
  user: root
  roles:
  - old
[root@centos-02 nginx_config]# 
[root@centos-02 nginx_config]# ansible-playbook rollback.yml 

PLAY [centos-03] ************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [centos-03]

TASK [old : copy conf file] *************************************************************
ok: [centos-03] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})

PLAY RECAP ******************************************************************************
centos-03                  : ok=2    changed=0    unreachable=0    failed=0   

[root@centos-02 nginx_config]# 

总结:要想回滚肯定是把变更之前的文件拷贝回去,拷贝回去的前提是原来的文件要有,所以我们在变更之前就要把new下面的文件先拷贝到old下,之后再做更改,执行update,有问题执行rollback  

  

  

  

  

 

posted @ 2018-05-24 00:30  278108678  阅读(2001)  评论(0编辑  收藏  举报