1 案例1:环境准备
1.1 问题
本案例要求准备ansible的基础环境:
启动6台虚拟机
禁用selinux和firewalld
编辑/etc/hosts
配置yum扩展源并在管理节点安装ansible
1.2 方案
此方案需要准备六台主机,1台管理主机,5台托管主机,以实现批量程序部署,批量运行命令等功能,具体要求如表-1所示:
表-1
1.3 步骤
实现此案例需要按照如下步骤进行。
步骤一:基础环境准备
1)启动6台虚拟机,由于已经讲过怎么创建,这里不再在案例里体现
2)真机配置yum仓库
[[email protected] ~]# tar -xf ansible_soft.tar.xz
[[email protected] ~]# cd ansible_soft/
[[email protected] ansible_soft]# mkdir /var/ftp/ansible
[[email protected] ansible_soft]# cp * /var/ftp/ansible
[[email protected] ansible_soft]# createrepo /var/ftp/ansible
Spawning worker 0 with 1 pkgs
Spawning worker 1 with 1 pkgs
Spawning worker 2 with 1 pkgs
Spawning worker 3 with 1 pkgs
Spawning worker 4 with 1 pkgs
Spawning worker 5 with 1 pkgs
Workers Finished
Saving Primary metadata
Saving file lists metadata
Saving other metadata
Generating sqlite DBs
Sqlite DBs complete
3)修改主机名(容易区分,6台机器都需要修改)这里以ansible主机为例子
[[email protected] ~]# echo ansible > /etc/hostname
[[email protected] ~]# hostname ansible
4)配置ip(6台机器都需要配置),这里以ansible主机为例子
[[email protected] ~]# vim /etc/sysconfig/network-scripts/ifcfg-eth0
# Generated by dracut initrd
DEVICE=”eth0″
ONBOOT=”yes”
IPV6INIT=”no”
IPV4_FAILURE_FATAL=”no”
NM_CONTROLLED=”no”
TYPE=”Ethernet”
BOOTPROTO=”static”
IPADDR=192.168.1.51
PREFIX=24
GATEWAY=192.168.1.254
[[email protected] ~]# systemctl restart network
[[email protected] ~]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.1.51 netmask 255.255.255.0 broadcast 192.168.1.255
ether 52:54:00:b2:69:9e txqueuelen 1000 (Ethernet)
RX packets 234 bytes 16379 (15.9 KiB)
RX errors 0 dropped 36 overruns 0 frame 0
TX packets 31 bytes 2618 (2.5 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
5)配置yum客户端,在管理节点ansible上面配置
[[email protected] ~]# vim /etc/yum.repos.d/local.repo
[local_repo]
name=CentOS-$releasever – Base
baseurl=”ftp://192.168.1.254/system”
enabled=1
gpgcheck=1
[local]
name=local
baseurl=”ftp://192.168.1.254/ansible”
enabled=1
gpgcheck=0
[[email protected] ~]# yum clean all
[[email protected] ~]# yum repolist
[[email protected] ~]# yum -y install ansible
[[email protected] ~]# ansible –version
ansible 2.4.2.0 //显示版本说明安装成功
config file = /etc/ansible/ansible.cfg
configured module search path = [u’/root/.ansible/plugins/modules’, u’/usr/share/ansible/plugins/modules’]
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Aug 4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]
6)请在6台主机上面配置/etc/hosts,这里以ansible主机为例子
[[email protected] ansible]# cat /etc/hosts
192.168.1.51 ansible
192.168.1.52 web1
192.168.1.53 web2
192.168.1.54 db1
192.168.1.55 db2
192.168.1.56 cache
6台机器名及IP的分配如下
ansible 192.168.1.51 管理主机
web1 192.168.1.52 托管主机
web2 192.168.1.53 托管主机
db1 192.168.1.54 托管主机
db2 192.168.1.55 托管主机
cache 192.168.1.56 托管主机
代码如下
把5台虚拟机先创建好,具体的代码就不贴了,就贴个步骤,本案例5台虚拟机改下名称就行了
[[email protected] qemu]# sed ‘s/node/node51/’ /etc/libvirt/qemu/node.xml > /etc/libvirt/qemu/node51.xml
[[email protected] qemu]# sed ‘s/node/node52/’ /etc/libvirt/qemu/node.xml > /etc/libvirt/qemu/node52.xml
[[email protected] qemu]# sed ‘s/node/node53/’ /etc/libvirt/qemu/node.xml > /etc/libvirt/qemu/node53.xml
[[email protected] qemu]# sed ‘s/node/node54/’ /etc/libvirt/qemu/node.xml > /etc/libvirt/qemu/node54.xml
[[email protected] qemu]# sed ‘s/node/node55/’ /etc/libvirt/qemu/node.xml > /etc/libvirt/qemu/node55.xml
[[email protected] ~]# cd /var/lib/libvirt/images/
[[email protected] images]# pwd
/var/lib/libvirt/images
[[email protected] images]# qemu-img create -b node.qcow2 -f qcow2 node51.img
Formatting ‘node51.img’, fmt=qcow2 size=17179869184 backing_file=’node.qcow2′ encryption=off cluster_size=65536 lazy_refcounts=off
[[email protected] images]# qemu-img create -b node.qcow2 -f qcow2 node52.img
Formatting ‘node52.img’, fmt=qcow2 size=17179869184 backing_file=’node.qcow2′ encryption=off cluster_size=65536 lazy_refcounts=off
[[email protected] images]# qemu-img create -b node.qcow2 -f qcow2 node53.img
Formatting ‘node53.img’, fmt=qcow2 size=17179869184 backing_file=’node.qcow2′ encryption=off cluster_size=65536 lazy_refcounts=off
[[email protected]om9pc52 images]# qemu-img create -b node.qcow2 -f qcow2 node54.img
Formatting ‘node54.img’, fmt=qcow2 size=17179869184 backing_file=’node.qcow2′ encryption=off cluster_size=65536 lazy_refcounts=off
[[email protected] images]# qemu-img create -b node.qcow2 -f qcow2 node55.img
Formatting ‘node55.img’, fmt=qcow2 size=17179869184 backing_file=’node.qcow2′ encryption=off cluster_size=65536 lazy_refcounts=off
[[email protected] images]# ll -h node5*
-rw-r–r– 1 root root 193K 10月 19 10:03 node51.img
-rw-r–r– 1 root root 193K 10月 19 10:03 node52.img
-rw-r–r– 1 root root 193K 10月 19 10:03 node53.img
-rw-r–r– 1 root root 193K 10月 19 10:03 node54.img
-rw-r–r– 1 root root 193K 10月 19 10:03 node55.img
我刚才创建的前端镜像名叫*.img,但是模板里面是*.qcow2,所以模板要改一下
[[email protected] images]# cd /etc/libvirt/qemu/
[[email protected] qemu]# vim node51.xml
[[email protected] qemu]# vim node52.xml
[[email protected] qemu]# vim node53.xml
[[email protected] qemu]# vim node54.xml
[[email protected] qemu]# vim node55.xml
[[email protected] qemu]# virsh define node51.xml
定义域 node51(从 node51.xml)
[[email protected] qemu]# virsh define node52.xml
定义域 node52(从 node52.xml)
[[email protected] qemu]# virsh define node53.xml
定义域 node53(从 node53.xml)
[[email protected] qemu]# virsh define node54.xml
定义域 node54(从 node54.xml)
[[email protected] qemu]# virsh define node55.xml
定义域 node55(从 node55.xml)
[[email protected] qemu]#
[[email protected] qemu]# virsh start node51
域 node51 已开始
[[email protected] qemu]# virsh start node52
域 node52 已开始
[[email protected] qemu]# virsh start node53
域 node53 已开始
[[email protected] qemu]# virsh start node54
域 node54 已开始
[[email protected] qemu]# virsh start node55
域 node55 已开始
在真机上配置好本地yum源
[[email protected] ansible 1]# tar -xf ansible_soft.tar.xz
[[email protected] ansible 1]# cd ansible_soft/
[[email protected] ansible_soft]# ll -h
总用量 8.6M
-rw-r–r– 1 root root 7.6M 1月 30 2018 ansible-2.4.2.0-2.el7.noarch.rpm
-rw-r–r– 1 root root 39K 10月 25 2017 python2-jmespath-0.9.0-3.el7.noarch.rpm
-rw-r–r– 1 root root 116K 9月 22 2017 python-httplib2-0.9.2-1.el7.noarch.rpm
-rw-r–r– 1 root root 269K 4月 4 2018 python-paramiko-2.1.1-4.el7.noarch.rpm
-rw-r–r– 1 root root 489K 9月 8 2017 python-passlib-1.6.5-2.el7.noarch.rpm
-rw-r–r– 1 root root 22K 9月 8 2017 sshpass-1.06-2.el7.x86_64.rpm
[[email protected] ansible_soft]# mkdir /var/ftp/ansible
[[email protected] ansible_soft]# cp * /var/ftp/ansible
[[email protected] ansible_soft]# createrepo /var/ftp/ansible
Spawning worker 0 with 2 pkgs
Spawning worker 1 with 2 pkgs
Spawning worker 2 with 1 pkgs
Spawning worker 3 with 1 pkgs
Workers Finished
Saving Primary metadata
Saving file lists metadata
Saving other metadata
Generating sqlite DBs
Sqlite DBs complete
[[email protected] ansible_soft]# ll /var/ftp/ansible
总用量 8732
-rw-r–r– 1 root root 7968876 10月 19 10:26 ansible-2.4.2.0-2.el7.noarch.rpm
-rw-r–r– 1 root root 39576 10月 19 10:26 python2-jmespath-0.9.0-3.el7.noarch.rpm
-rw-r–r– 1 root root 117968 10月 19 10:26 python-httplib2-0.9.2-1.el7.noarch.rpm
-rw-r–r– 1 root root 274640 10月 19 10:26 python-paramiko-2.1.1-4.el7.noarch.rpm
-rw-r–r– 1 root root 500108 10月 19 10:26 python-passlib-1.6.5-2.el7.noarch.rpm
drwxr-xr-x 2 root root 4096 10月 19 10:26 repodata
-rw-r–r– 1 root root 21896 10月 19 10:26 sshpass-1.06-2.el7.x86_64.rpm
[[email protected] ansible_soft]#
(刚才少创建了1台虚拟机56,现在补上)
[[email protected] qemu]# sed ‘s/node/node56/’ /etc/libvirt/qemu/node.xml > /etc/libvirt/qemu/node56.xml
[[email protected] qemu]# cd /var/lib/libvirt/images/
[[email protected] images]# qemu-img create -b node.qcow2 -f qcow2 node56.qcow2
Formatting ‘node56.qcow2′, fmt=qcow2 size=17179869184 backing_file=’node.qcow2′ encryption=off cluster_size=65536 lazy_refcounts=off
[[email protected] images]# cd /etc/libvirt/qemu/
[[email protected] qemu]# virsh define node56.xml
定义域 node56(从 node56.xml)
[[email protected] qemu]# virsh start node56
域 node56 已开始
挨个登陆虚拟机,配置主机名、YUM源、IP地址
以node51为例,其它主机也要配置
[[email protected] ~]# cat /etc/hostname
ansible
[[email protected] ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
# Generated by dracut initrd
DEVICE=”eth0″
NAME=”eth0″
ONBOOT=yes
IPV6INIT=no
TYPE=Ethernet
BOOTPROTO=”static”
IPADDR=192.168.1.51
PREFIX=24
GATEWAY=192.168.1.254
[[email protected] ~]# systemctl restart network
[[email protected] ~]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.1.51 netmask 255.255.255.0 broadcast 192.168.1.255
inet6 fe80::5054:ff:fe3c:4de6 prefixlen 64 scopeid 0x20<link>
ether 52:54:00:3c:4d:e6 txqueuelen 1000 (Ethernet)
RX packets 755 bytes 50490 (49.3 KiB)
RX errors 0 dropped 12 overruns 0 frame 0
TX packets 137 bytes 11204 (10.9 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1 (Local Loopback)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
配置yum源
[[email protected] ~]# cd /etc/yum.repos.d/
[[email protected] yum.repos.d]# ls
CentOS-Base.repo CentOS-Debuginfo.repo CentOS-Media.repo CentOS-Vault.repo
CentOS-CR.repo CentOS-fasttrack.repo CentOS-Sources.repo dvd.repo
[[email protected] yum.repos.d]# rm -rf dvd.repo
[[email protected] yum.repos.d]# cat local.repo
[local_repo]
name=CentOS-$releasever – Base
baseurl=”ftp://192.168.1.254/system”
enabled=1
gpgcheck=1
[local]
name=local
baseurl=”ftp://192.168.1.254/ansible”
enabled=1
gpgcheck=0
[[email protected] yum.repos.d]# yum clean all
Loaded plugins: fastestmirror
Cleaning repos: base extras local local_repo updates
Cleaning up everything
Maybe you want: rm -rf /var/cache/yum, to also free up space taken by orphaned data from disabled or removed repos
[[email protected] yum.repos.d]# yum repolist
Loaded plugins: fastestmirror
base | 3.6 kB 00:00
extras | 3.4 kB 00:00
local | 2.9 kB 00:00
local_repo | 3.6 kB 00:00
updates | 3.4 kB 00:00
(1/7): local/primary_db | 5.2 kB 00:00
(2/7): local_repo/group_gz | 156 kB 00:00
(3/7): local_repo/primary_db | 5.7 MB 00:00
(4/7): base/7/x86_64/group_gz | 166 kB 00:12
(5/7): extras/7/x86_64/primary_db | 204 kB 00:14
(6/7): updates/7/x86_64/primary_db | 6.0 MB 00:39
(7/7): base/7/x86_64/primary_db | 5.9 MB 00:59
Determining fastest mirrors
* base: mirrors.163.com
* extras: mirrors.163.com
* updates: mirrors.cn99.com
repo id repo name status
base/7/x86_64 CentOS-7 – Base 9,911
extras/7/x86_64 CentOS-7 – Extras 432
local local 6
local_repo CentOS-7 – Base 9,591
updates/7/x86_64 CentOS-7 – Updates 1,561
repolist: 21,501
其他机器同样配置好yum源
[[email protected] ~]# for i in 52 53 54 55 56 ;do scp /etc/yum.repos.d/local.repo 192.168.1.$i:/etc/yum.repos.d/ ;done
local.repo 100% 180 109.7KB/s 00:00
local.repo 100% 180 86.1KB/s 00:00
local.repo 100% 180 92.8KB/s 00:00
local.repo 100% 180 91.8KB/s 00:00
local.repo 100% 180 112.7KB/s 00:00
安装ansible
[[email protected] yum.repos.d]# yum install -y ansible
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.163.com
* extras: mirrors.163.com
* updates: mirrors.cn99.com
Resolving Dependencies
–> Running transaction check
—> Package ansible.noarch 0:2.4.2.0-2.el7 will be installed
–> Processing Dependency: sshpass for package: ansible-2.4.2.0-2.el7.noarch
–> Processing Dependency: python2-jmespath for package: ansible-2.4.2.0-2.el7.noarch
–> Processing Dependency: python-six for package: ansible-2.4.2.0-2.el7.noarch
–> Processing Dependency: python-setuptools for package: ansible-2.4.2.0-2.el7.noarch
–> Processing Dependency: python-passlib for package: ansible-2.4.2.0-2.el7.noarch
–> Processing Dependency: python-paramiko for package: ansible-2.4.2.0-2.el7.noarch
–> Processing Dependency: python-jinja2 for package: ansible-2.4.2.0-2.el7.noarch
–> Processing Dependency: python-httplib2 for package: ansible-2.4.2.0-2.el7.noarch
–> Processing Dependency: python-cryptography for package: ansible-2.4.2.0-2.el7.noarch
–> Processing Dependency: PyYAML for package: ansible-2.4.2.0-2.el7.noarch
–> Running transaction check
—> Package PyYAML.x86_64 0:3.10-11.el7 will be installed
–> Processing Dependency: libyaml-0.so.2()(64bit) for package: PyYAML-3.10-11.el7.x86_64
—> Package python-httplib2.noarch 0:0.9.2-1.el7 will be installed
—> Package python-jinja2.noarch 0:2.7.2-2.el7 will be installed
–> Processing Dependency: python-babel >= 0.8 for package: python-jinja2-2.7.2-2.el7.noarch
–> Processing Dependency: python-markupsafe for package: python-jinja2-2.7.2-2.el7.noarch
—> Package python-paramiko.noarch 0:2.1.1-4.el7 will be installed
–> Processing Dependency: python2-pyasn1 for package: python-paramiko-2.1.1-4.el7.noarch
—> Package python-passlib.noarch 0:1.6.5-2.el7 will be installed
—> Package python-setuptools.noarch 0:0.9.8-7.el7 will be installed
–> Processing Dependency: python-backports-ssl_match_hostname for package: python-setuptools-0.9.8-7.el7.noarch
—> Package python-six.noarch 0:1.9.0-2.el7 will be installed
—> Package python2-cryptography.x86_64 0:1.7.2-2.el7 will be installed
–> Processing Dependency: python-idna >= 2.0 for package: python2-cryptography-1.7.2-2.el7.x86_64
–> Processing Dependency: python-cffi >= 1.4.1 for package: python2-cryptography-1.7.2-2.el7.x86_64
–> Processing Dependency: python-ipaddress for package: python2-cryptography-1.7.2-2.el7.x86_64
–> Processing Dependency: python-enum34 for package: python2-cryptography-1.7.2-2.el7.x86_64
—> Package python2-jmespath.noarch 0:0.9.0-3.el7 will be installed
—> Package sshpass.x86_64 0:1.06-2.el7 will be installed
–> Running transaction check
—> Package libyaml.x86_64 0:0.1.4-11.el7_0 will be installed
—> Package python-babel.noarch 0:0.9.6-8.el7 will be installed
—> Package python-backports-ssl_match_hostname.noarch 0:3.5.0.1-1.el7 will be installed
–> Processing Dependency: python-backports for package: python-backports-ssl_match_hostname-3.5.0.1-1.el7.noarch
—> Package python-cffi.x86_64 0:1.6.0-5.el7 will be installed
–> Processing Dependency: python-pycparser for package: python-cffi-1.6.0-5.el7.x86_64
—> Package python-enum34.noarch 0:1.0.4-1.el7 will be installed
—> Package python-idna.noarch 0:2.4-1.el7 will be installed
—> Package python-ipaddress.noarch 0:1.0.16-2.el7 will be installed
—> Package python-markupsafe.x86_64 0:0.11-10.el7 will be installed
—> Package python2-pyasn1.noarch 0:0.1.9-7.el7 will be installed
–> Running transaction check
—> Package python-backports.x86_64 0:1.0-8.el7 will be installed
—> Package python-pycparser.noarch 0:2.14-1.el7 will be installed
–> Processing Dependency: python-ply for package: python-pycparser-2.14-1.el7.noarch
–> Running transaction check
—> Package python-ply.noarch 0:3.4-11.el7 will be installed
–> Finished Dependency Resolution
Dependencies Resolved
================================================================================
Package Arch Version Repository
Size
================================================================================
Installing:
ansible noarch 2.4.2.0-2.el7 extras 7.6 M
Installing for dependencies:
PyYAML x86_64 3.10-11.el7 base 153 k
libyaml x86_64 0.1.4-11.el7_0 base 55 k
python-babel noarch 0.9.6-8.el7 base 1.4 M
python-backports x86_64 1.0-8.el7 base 5.8 k
python-backports-ssl_match_hostname noarch 3.5.0.1-1.el7 base 13 k
python-cffi x86_64 1.6.0-5.el7 base 218 k
python-enum34 noarch 1.0.4-1.el7 base 52 k
python-httplib2 noarch 0.9.2-1.el7 extras 115 k
python-idna noarch 2.4-1.el7 base 94 k
python-ipaddress noarch 1.0.16-2.el7 base 34 k
python-jinja2 noarch 2.7.2-2.el7 base 515 k
python-markupsafe x86_64 0.11-10.el7 base 25 k
python-paramiko noarch 2.1.1-4.el7 extras 268 k
python-passlib noarch 1.6.5-2.el7 extras 488 k
python-ply noarch 3.4-11.el7 base 123 k
python-pycparser noarch 2.14-1.el7 base 104 k
python-setuptools noarch 0.9.8-7.el7 base 397 k
python-six noarch 1.9.0-2.el7 base 29 k
python2-cryptography x86_64 1.7.2-2.el7 base 502 k
python2-jmespath noarch 0.9.0-3.el7 extras 39 k
python2-pyasn1 noarch 0.1.9-7.el7 base 100 k
sshpass x86_64 1.06-2.el7 extras 21 k
Transaction Summary
================================================================================
Install 1 Package (+22 Dependent packages)
Total download size: 12 M
Installed size: 60 M
Downloading packages:
(1/23): PyYAML-3.10-11.el7.x86_64.rpm | 153 kB 00:00
(2/23): libyaml-0.1.4-11.el7_0.x86_64.rpm | 55 kB 00:00
(3/23): python-backports-ssl_match_hostname-3.5.0.1-1.el7. | 13 kB 00:00
(4/23): python-backports-1.0-8.el7.x86_64.rpm | 5.8 kB 00:00
(5/23): python-enum34-1.0.4-1.el7.noarch.rpm | 52 kB 00:00
(6/23): python-idna-2.4-1.el7.noarch.rpm | 94 kB 00:00
(7/23): python-ipaddress-1.0.16-2.el7.noarch.rpm | 34 kB 00:00
(8/23): python-cffi-1.6.0-5.el7.x86_64.rpm | 218 kB 00:00
(9/23): python-markupsafe-0.11-10.el7.x86_64.rpm | 25 kB 00:00
(10/23): python-jinja2-2.7.2-2.el7.noarch.rpm | 515 kB 00:00
(11/23): ansible-2.4.2.0-2.el7.noarch.rpm | 7.6 MB 00:01
(12/23): python-ply-3.4-11.el7.noarch.rpm | 123 kB 00:00
(13/23): python-paramiko-2.1.1-4.el7.noarch.rpm | 268 kB 00:01
(14/23): python-pycparser-2.14-1.el7.noarch.rpm | 104 kB 00:00
(15/23): python-six-1.9.0-2.el7.noarch.rpm | 29 kB 00:00
(16/23): python2-cryptography-1.7.2-2.el7.x86_64.rpm | 502 kB 00:00
(17/23): python2-jmespath-0.9.0-3.el7.noarch.rpm | 39 kB 00:00
(18/23): python2-pyasn1-0.1.9-7.el7.noarch.rpm | 100 kB 00:00
(19/23): python-setuptools-0.9.8-7.el7.noarch.rpm | 397 kB 00:00
(20/23): sshpass-1.06-2.el7.x86_64.rpm | 21 kB 00:00
(21/23): python-babel-0.9.6-8.el7.noarch.rpm | 1.4 MB 00:02
(22/23): python-httplib2-0.9.2-1.el7.noarch.rpm | 115 kB 00:03
(23/23): python-passlib-1.6.5-2.el7.noarch.rpm | 488 kB 00:02
——————————————————————————–
Total 2.7 MB/s | 12 MB 00:04
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : python2-pyasn1-0.1.9-7.el7.noarch 1/23
Installing : python-ipaddress-1.0.16-2.el7.noarch 2/23
Installing : python-six-1.9.0-2.el7.noarch 3/23
Installing : python-httplib2-0.9.2-1.el7.noarch 4/23
Installing : python-enum34-1.0.4-1.el7.noarch 5/23
Installing : libyaml-0.1.4-11.el7_0.x86_64 6/23
Installing : PyYAML-3.10-11.el7.x86_64 7/23
Installing : python-backports-1.0-8.el7.x86_64 8/23
Installing : python-backports-ssl_match_hostname-3.5.0.1-1.el7.noarch 9/23
Installing : python-setuptools-0.9.8-7.el7.noarch 10/23
Installing : python-babel-0.9.6-8.el7.noarch 11/23
Installing : python-passlib-1.6.5-2.el7.noarch 12/23
Installing : python-ply-3.4-11.el7.noarch 13/23
Installing : python-pycparser-2.14-1.el7.noarch 14/23
Installing : python-cffi-1.6.0-5.el7.x86_64 15/23
Installing : python-markupsafe-0.11-10.el7.x86_64 16/23
Installing : python-jinja2-2.7.2-2.el7.noarch 17/23
Installing : python-idna-2.4-1.el7.noarch 18/23
Installing : python2-cryptography-1.7.2-2.el7.x86_64 19/23
Installing : python-paramiko-2.1.1-4.el7.noarch 20/23
Installing : sshpass-1.06-2.el7.x86_64 21/23
Installing : python2-jmespath-0.9.0-3.el7.noarch 22/23
Installing : ansible-2.4.2.0-2.el7.noarch 23/23
Verifying : python-jinja2-2.7.2-2.el7.noarch 1/23
Verifying : python-backports-ssl_match_hostname-3.5.0.1-1.el7.noarch 2/23
Verifying : python2-jmespath-0.9.0-3.el7.noarch 3/23
Verifying : sshpass-1.06-2.el7.x86_64 4/23
Verifying : python-setuptools-0.9.8-7.el7.noarch 5/23
Verifying : python-six-1.9.0-2.el7.noarch 6/23
Verifying : python-idna-2.4-1.el7.noarch 7/23
Verifying : python-markupsafe-0.11-10.el7.x86_64 8/23
Verifying : python-ply-3.4-11.el7.noarch 9/23
Verifying : python-passlib-1.6.5-2.el7.noarch 10/23
Verifying : python-babel-0.9.6-8.el7.noarch 11/23
Verifying : python-paramiko-2.1.1-4.el7.noarch 12/23
Verifying : python-backports-1.0-8.el7.x86_64 13/23
Verifying : python-cffi-1.6.0-5.el7.x86_64 14/23
Verifying : python-pycparser-2.14-1.el7.noarch 15/23
Verifying : libyaml-0.1.4-11.el7_0.x86_64 16/23
Verifying : ansible-2.4.2.0-2.el7.noarch 17/23
Verifying : python-ipaddress-1.0.16-2.el7.noarch 18/23
Verifying : python-enum34-1.0.4-1.el7.noarch 19/23
Verifying : python-httplib2-0.9.2-1.el7.noarch 20/23
Verifying : python2-pyasn1-0.1.9-7.el7.noarch 21/23
Verifying : PyYAML-3.10-11.el7.x86_64 22/23
Verifying : python2-cryptography-1.7.2-2.el7.x86_64 23/23
Installed:
ansible.noarch 0:2.4.2.0-2.el7
Dependency Installed:
PyYAML.x86_64 0:3.10-11.el7
libyaml.x86_64 0:0.1.4-11.el7_0
python-babel.noarch 0:0.9.6-8.el7
python-backports.x86_64 0:1.0-8.el7
python-backports-ssl_match_hostname.noarch 0:3.5.0.1-1.el7
python-cffi.x86_64 0:1.6.0-5.el7
python-enum34.noarch 0:1.0.4-1.el7
python-httplib2.noarch 0:0.9.2-1.el7
python-idna.noarch 0:2.4-1.el7
python-ipaddress.noarch 0:1.0.16-2.el7
python-jinja2.noarch 0:2.7.2-2.el7
python-markupsafe.x86_64 0:0.11-10.el7
python-paramiko.noarch 0:2.1.1-4.el7
python-passlib.noarch 0:1.6.5-2.el7
python-ply.noarch 0:3.4-11.el7
python-pycparser.noarch 0:2.14-1.el7
python-setuptools.noarch 0:0.9.8-7.el7
python-six.noarch 0:1.9.0-2.el7
python2-cryptography.x86_64 0:1.7.2-2.el7
python2-jmespath.noarch 0:0.9.0-3.el7
python2-pyasn1.noarch 0:0.1.9-7.el7
sshpass.x86_64 0:1.06-2.el7
Complete!
确认一下ansible安装完成
[[email protected] yum.repos.d]# ansible –version
ansible 2.4.2.0
config file = /etc/ansible/ansible.cfg
configured module search path = [u’/root/.ansible/plugins/modules’, u’/usr/share/ansible/plugins/modules’]
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /bin/ansible
python version = 2.7.5 (default, Aug 4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]
然后在6台主机上都配置hosts
[[email protected] yum.repos.d]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.1.51 ansible
192.168.1.52 web1
192.168.1.53 web2
192.168.1.54 db1
192.168.1.55 db2
192.168.1.56 cache
配置好免密登陆,6台主机都要做好
[[email protected] ~]# ssh-keygen
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:
SHA256:UpwSw0qKAn6BFYmxsLEQOECUF33ZMT/FVf2s3p+2kEE [email protected]
The key’s randomart image is:
+—[RSA 2048]—-+
|@=*+=.o oo. ….+|
|*B.+…* oo .. .|
|=+.o..o + o E ..|
|o…. o o o|
|. . . S . . |
| . + |
| + . |
| o.o|
| .o+|
+—-[SHA256]—–+
[[email protected] ~]#
[[email protected] ~]#
[[email protected] ~]# for i in 51 52 53 54 55 56;do ssh-copy-id 192.168.1.$i;done
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: “/root/.ssh/id_rsa.pub”
The authenticity of host ‘192.168.1.51 (192.168.1.51)’ can’t be established.
ECDSA key fingerprint is SHA256:VukYDuqTUky93mbDoL/7WPAM6PvQ05R3xYae7JinddU.
ECDSA key fingerprint is MD5:6e:94:23:bf:32:01:47:72:a5:d4:5b:93:75:04:f5:f4.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed — if you are prompted now it is to install the new keys
[email protected]’s password:
Number of key(s) added: 1
Now try logging into the machine, with: “ssh ‘192.168.1.51’”
and check to make sure that only the key(s) you wanted were added.
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: “/root/.ssh/id_rsa.pub”
The authenticity of host ‘192.168.1.52 (192.168.1.52)’ can’t be established.
ECDSA key fingerprint is SHA256:aY08I9sIdWG6kBkovQIjmtpLw1/ZWh2Fl4VlLK3zCto.
ECDSA key fingerprint is MD5:96:40:4f:68:c5:8a:ee:dd:d9:38:99:03:51:ca:c7:34.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed — if you are prompted now it is to install the new keys
[email protected]’s password:
Number of key(s) added: 1
Now try logging into the machine, with: “ssh ‘192.168.1.52’”
and check to make sure that only the key(s) you wanted were added.
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: “/root/.ssh/id_rsa.pub”
The authenticity of host ‘192.168.1.53 (192.168.1.53)’ can’t be established.
ECDSA key fingerprint is SHA256:pHxO2IbX3qHtbvUkZylqOxgWiYFSJJZKbc3CziKNkqw.
ECDSA key fingerprint is MD5:81:61:15:83:6c:09:f4:41:e2:c5:01:00:fe:24:96:55.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed — if you are prompted now it is to install the new keys
[email protected]’s password:
Number of key(s) added: 1
Now try logging into the machine, with: “ssh ‘192.168.1.53’”
and check to make sure that only the key(s) you wanted were added.
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: “/root/.ssh/id_rsa.pub”
The authenticity of host ‘192.168.1.54 (192.168.1.54)’ can’t be established.
ECDSA key fingerprint is SHA256:6QMsdZy5v54ZwrVCnM0HmMs6GkisjYO15U0SapxPEMU.
ECDSA key fingerprint is MD5:96:ed:7d:76:28:43:b9:29:32:b2:b8:33:ad:22:b0:4a.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed — if you are prompted now it is to install the new keys
[email protected]’s password:
Number of key(s) added: 1
Now try logging into the machine, with: “ssh ‘192.168.1.54’”
and check to make sure that only the key(s) you wanted were added.
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: “/root/.ssh/id_rsa.pub”
The authenticity of host ‘192.168.1.55 (192.168.1.55)’ can’t be established.
ECDSA key fingerprint is SHA256:/dd+4S4Nql02kVMpsFftbkUEKu0s8obXFPyLHIEmNOI.
ECDSA key fingerprint is MD5:26:0d:38:05:9f:73:3c:b7:33:7b:6b:9d:42:34:10:a0.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed — if you are prompted now it is to install the new keys
[email protected]’s password:
Number of key(s) added: 1
Now try logging into the machine, with: “ssh ‘192.168.1.55’”
and check to make sure that only the key(s) you wanted were added.
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: “/root/.ssh/id_rsa.pub”
The authenticity of host ‘192.168.1.56 (192.168.1.56)’ can’t be established.
ECDSA key fingerprint is SHA256:I3NbgSWe/ruEhXCHgUAjVkvohx8Fss0nyjdKLrA+IgA.
ECDSA key fingerprint is MD5:cd:c7:4c:ba:d8:b8:2c:75:8d:88:2e:c3:11:7d:f3:3f.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed — if you are prompted now it is to install the new keys
[email protected]’s password:
Number of key(s) added: 1
Now try logging into the machine, with: “ssh ‘192.168.1.56’”
and check to make sure that only the key(s) you wanted were added.
2 案例2:主机定义与分组:
2.1 问题
本案例要求:
熟悉ansible配置文件
定义主机,分组和子组练习
自定义文件,多配置路径练习
2.2 步骤
实现此案例需要按照如下步骤进行。
步骤一:ansible.cfg配置文件
[[email protected] ~]# cd /etc/ansible/
[[email protected] ansible]# ls
ansible.cfg hosts roles
[[email protected] ansible]# vim ansible.cfg
#inventory = /etc/ansible/hosts //指定分组文件路径,主机的分组文件hosts
[selinux] //组名称,selinux的相关选项在这个下面配置
…
[colors] //组名称,colors的相关选项在这个下面配置
…
步骤二:定义主机,分组和子组练习
1)静态主机的定义
[[email protected] ansible]# vim hosts
[web]
web1
web2
[db]
db[1:2] //1:2为db1到db2两台主机,1:20为db1到db20多台主机
[other]
cache
[[email protected] ansible]# ansible web –list-host //显示web组的主机
hosts (2):
web1
web2
[[email protected] ansible]# ansible db –list-host
hosts (2):
db1
db2
[[email protected] ansible]# ansible other –list-host
hosts (1):
cache
[[email protected] ansible]# ansible all –list-host //显示所有组的主机
hosts (5):
web1
web2
cache
db1
db2
2)直接测试
[[email protected] ansible]# ansible cache -m ping
//测试是否可以连接,若失败颜色为红色
cache | UNREACHABLE! => {
“changed”: false,
“msg”: “Failed to connect to the host via ssh: ssh: Could not resolve hostname cache: Name or service not known\r\n”,
“unreachable”: true
}
3)修改后测试
[[email protected] ansible]# vi hosts
[other]
cache ansible_ssh_user=”root” ansible_ssh_pass=”a”
[[email protected] ansible]# ansible other -m ping //测试成功,颜色为绿色
cache | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
4)不检测主机的sshkey,在第一次连接的时候不用输入yes
[[email protected] ansible]# vim ansible.cfg
61 host_key_checking = False
[[email protected] ansible]# vim hosts
[web]
web1
web2
[web:vars] //web组:变量(vars不改),web组的多台机器共用一个用户名和密码
ansible_ssh_user=”root”
ansible_ssh_pass=”a”
[[email protected] ansible]# ansible web -m ping
web2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
web1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
步骤三:定义子组
[[email protected] ansible]# vi hosts
[app:children] //指定子分组(app可改:children不改),web,db是提前分好的组
web
db
[app:vars]
ansible_ssh_user=”root”
ansible_ssh_pass=”a”
[[email protected] ansible]# ansible app –list-host //查看
hosts (4):
web1
web2
db1
db2
[[email protected] ansible]# ansible app -m ping //测试
web1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
web2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
db1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
db2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
步骤四:多路径练习
自定义的ansible文件只在当前路径生效
1)多路径
[[email protected] ~]# mkdir aaa
[[email protected] ~]# cd aaa/
[[email protected] aaa]# vim myhost
[app1]
web1
db1
[app2]
web2
db2
[app:children]
app1
app2
[other]
cache
[app:vars]
ansible_ssh_user=”root”
ansible_ssh_pass=”a”
[[email protected] aaa]# touch ansible.cfg
[[email protected] aaa]# grep -Ev “^#|^$” /etc/ansible/ansible.cfg
[defaults]
roles_path = /etc/ansible/roles:/usr/share/ansible/roles
host_key_checking = False
[inventory]
[privilege_escalation]
[paramiko_connection]
[ssh_connection]
[persistent_connection]
[accelerate]
[selinux]
[colors]
[diff]
[[email protected] aaa]# vim ansible.cfg
[defaults]
inventory = myhost
host_key_checking = False
2)测试结果
[[email protected] aaa]# ansible app1 -m ping
web1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
db1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
[[email protected] aaa]# ansible app -m ping
web1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
db1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
db2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
web2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
[[email protected] aaa]# ansible app –list-host
hosts (4):
web1
db1
web2
db2
[[email protected] aaa]# cd
[[email protected] ~]# ansible app1 –list-host //切换到别的目录,测试失败
[WARNING]: Could not match supplied host pattern, ignoring: app1
[WARNING]: No hosts matched, nothing to do
hosts (0):
代码如下
进入ansible配置目录,编写和查看配置文件
[[email protected] ~]# cd /etc/ansible/
[[email protected] ansible]# ls
ansible.cfg hosts roles
[[email protected] ansible]# vim ansible.cfg
[[email protected] ansible]# vim hosts
[web]
web1
web2
[db]
db[1:2]
[other]
cache
[[email protected] ansible]# ansible web –list-host
hosts (2):
web1
web2
[[email protected] ansible]# ansible db –list-host
hosts (2):
db1
db2
[[email protected] ansible]# ansible other –list-host
hosts (1):
cache
[[email protected] ansible]# ansible all –list-host
hosts (5):
web1
web2
cache
db1
db2
ping测试
分别ping一下cache 和 db1 主机
[[email protected] ansible]# ansible cache -m ping
The authenticity of host ‘cache (192.168.1.56)’ can’t be established.
ECDSA key fingerprint is SHA256:I3NbgSWe/ruEhXCHgUAjVkvohx8Fss0nyjdKLrA+IgA.
ECDSA key fingerprint is MD5:cd:c7:4c:ba:d8:b8:2c:75:8d:88:2e:c3:11:7d:f3:3f.
Are you sure you want to continue connecting (yes/no)? yes
cache | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
[[email protected] ansible]# ansible db1 -m ping
The authenticity of host ‘db1 (192.168.1.54)’ can’t be established.
ECDSA key fingerprint is SHA256:6QMsdZy5v54ZwrVCnM0HmMs6GkisjYO15U0SapxPEMU.
ECDSA key fingerprint is MD5:96:ed:7d:76:28:43:b9:29:32:b2:b8:33:ad:22:b0:4a.
Are you sure you want to continue connecting (yes/no)? yes
db1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
[[email protected] ansible]#
不检测主机的sshkey,第一次连接的时候不用输入yes
[[email protected] ansible]# vim ansible.cfg
61 host_key_checking = False
[[email protected] ansible]# grep -v “^#” hosts | grep -v “^$”
[web]
web1
web2
[web:vars]
ansible_ssh_user=”root”
ansible_ssh_pass=”123456″
[db]
db[1:2]
[other]
cache
重新测试一下,就不用输入密码也不用输入yes了
[[email protected] ansible]# ansible web -m ping
web2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
web1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
[[email protected] ansible]#
增加一个app组,然后测试一下
[[email protected] ansible]# grep -v “^#” hosts | grep -v “^$”
[web]
web1
web2
[web:vars]
ansible_ssh_user=”root”
ansible_ssh_pass=”123456″
[db]
db[1:2]
[other]
cache
[app:children]
web
db
[app:vars]
ansible_ssh_user=”root”
ansible_ssh_pass=”123456″
列出,并测试连通性
[[email protected] ansible]# ansible app –list-host
hosts (4):
web1
web2
db1
db2
[[email protected] ansible]# ansible app -m ping
web2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
db1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
web1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
db2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
换一个目录创建配置文件
[[email protected] ansible]# cd
[[email protected] ~]# mkdir aaa
[[email protected] ~]# cd aaa/
[[email protected] aaa]# vim myhost
[[email protected] aaa]# grep -v “^#” myhost | grep -v “^$”
[app1]
web1
db1
[app2]
web2
db2
[app:children]
app1
app2
[other]
cache
[app:vars]
ansible_ssh_user=”root”
ansible_ssh_pass=”123456″
先看一眼默认目录下的cfg配置文件是怎么写的
[[email protected] aaa]# grep -Ev “^#|^$” /etc/ansible/ansible.cfg
[defaults]
roles_path = /etc/ansible/roles:/usr/share/ansible/roles
host_key_checking = False
[inventory]
[privilege_escalation]
[paramiko_connection]
[ssh_connection]
[persistent_connection]
[accelerate]
[selinux]
[colors]
[diff]
[[email protected] aaa]#
[[email protected] aaa]# vim ansible.cfg
然后我们自己写一个
[[email protected] aaa]# cat ansible.cfg
[defaults]
inventory = myhost
host_key_checking = False
测试一下
[[email protected] aaa]# ansible app1 -m ping
web1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
db1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
[[email protected] aaa]# ansible app -m ping
db1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
web1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
web2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
db2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
[[email protected] aaa]# ansible app –list-host
hosts (4):
web1
db1
web2
db2
如果切换了目录就失败了,说明要在配置文件的目录下执行命令
[[email protected] aaa]# cd
[[email protected] ~]# ansible app1 –list-host
[WARNING]: Could not match supplied host pattern, ignoring: app1
[WARNING]: No hosts matched, nothing to do
hosts (0):
3 案例3:动态主机
3.1 问题
本案例要求:
脚本输出主机列表
3.2 步骤
实现此案例需要按照如下步骤进行。
步骤一:脚本输出主机列表
[[email protected] ~]# cd aaa
[[email protected] aaa]# vim host.py
#!/usr/bin/python
import json
hostlist = {}
hostlist[“bb”] = [“192.168.1.52”, “192.168.1.53”]
hostlist[“192.168.1.54”] = {
“ansible_ssh_user”:”root”,”ansible_ssh_pass”:”pwd”
}
hostlist[“aa”] = {
“hosts” : [“192.168.1.55”, “192.168.1.56”],
“vars” : {
“ansible_ssh_user”:”root”,”ansible_ssh_pass”:”pwd”
}
}
print(json.dumps(hostlist))
[[email protected] aaa]# chmod 755 ./host.py
步骤二:脚本输出样例(这样写输出的结果有些乱)
[[email protected] aaa]# ./host.py
{“aa”: {“hosts”: [“192.168.1.55”, “192.168.1.56”], “vars”: {“ansible_ssh_user”: “root”, “ansible_ssh_pass”: “a”}}, “192.168.1.54”: {“ansible_ssh_user”: “root”, “ansible_ssh_pass”: “a”}, “bb”: [“192.168.1.52”, “192.168.1.53”]}
步骤三:可以用shell脚本输出
[[email protected] aaa]# vim my.sh
#!/bin/bash
echo ‘
{ “aa”: {
“hosts”:
[“192.168.1.55”, “192.168.1.56”],
“vars”: {
“ansible_ssh_user”: “root”,
“ansible_ssh_pass”: “a”}
},
}’
[[email protected] aaa]# chmod 755 my.sh
[[email protected] aaa]# ./my.sh
{ “aa”: {
“hosts”:
[“192.168.1.55”, “192.168.1.56”],
“vars”: {
“ansible_ssh_user”: “root”,
“ansible_ssh_pass”: “a”}
},
}
[[email protected] aaa]# vim ansible.cfg
[defaults]
inventory = my.sh
host_key_checking = False
[[email protected] aaa]# ansible aa -m ping
192.168.1.55 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
192.168.1.56 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
步骤二:批量执行
1)查看负载
[[email protected] aaa]# ansible app -m command -a ‘uptime’
db1 | SUCCESS | rc=0 >>
11:35:52 up 1:59, 2 users, load average: 0.00, 0.01, 0.01
web1 | SUCCESS | rc=0 >>
11:35:52 up 2:00, 2 users, load average: 0.00, 0.01, 0.02
db2 | SUCCESS | rc=0 >>
11:35:53 up 1:59, 2 users, load average: 0.00, 0.01, 0.03
web2 | SUCCESS | rc=0 >>
11:35:52 up 1:59, 2 users, load average: 0.00, 0.01, 0.02
2)查看时间
[[email protected] aaa]# ansible app -m command -a ‘date +%F\ %T’
db1 | SUCCESS | rc=0 >>
2018-09-06 11:42:18
web1 | SUCCESS | rc=0 >>
2018-09-06 11:42:18
web2 | SUCCESS | rc=0 >>
2018-09-06 11:42:18
db2 | SUCCESS | rc=0 >>
2018-09-06 11:42:19
代码如下
1、用脚本输出主机列表
[[email protected] ~]# cd aaa/
[[email protected] aaa]# pwd
/root/aaa
[[email protected] aaa]# vim host.py
[[email protected] aaa]# cat host.py
#!/usr/bin/python
import json
hostlist = {}
hostlist[“bb”] = [“192.168.1.52”, “192.168.1.53”]
hostlist[“192.168.1.54”] = {
“ansible_ssh_user”:”root”,”ansible_ssh_pass”:”pwd”
}
hostlist[“aa”] = {
“hosts” : [“192.168.1.55”, “192.168.1.56”],
“vars” : {
“ansible_ssh_user”:”root”,”ansible_ssh_pass”:”pwd”
}
}
print(json.dumps(hostlist))
[[email protected] aaa]# chmod 755 ./host.py
[[email protected] aaa]# ll -h host.py
-rwxr-xr-x 1 root root 392 10月 20 09:26 host.py
2、用脚本输出主机列表,但是看不清,结果混乱
[[email protected] aaa]# ./host.py
{“aa”: {“hosts”: [“192.168.1.55”, “192.168.1.56”], “vars”: {“ansible_ssh_user”: “root”, “ansible_ssh_pass”: “pwd”}}, “192.168.1.54”: {“ansible_ssh_user”: “root”, “ansible_ssh_pass”: “pwd”}, “bb”: [“192.168.1.52”, “192.168.1.53”]}
3、也可以用脚本输出
注意我的主机的密码是123456,和上面的案例不一样
[[email protected] aaa]# vim my.sh
[[email protected] aaa]# cat my.sh
#!/bin/bash
echo ‘
{ “aa”: {
“hosts”:
[“192.168.1.55”, “192.168.1.56”],
“vars”: {
“ansible_ssh_user”: “root”,
“ansible_ssh_pass”: “123456”}
},
}’
[[email protected] aaa]# chmod 755 my.sh
[[email protected] aaa]# ./my.sh
{ “aa”: {
“hosts”:
[“192.168.1.55”, “192.168.1.56”],
“vars”: {
“ansible_ssh_user”: “root”,
“ansible_ssh_pass”: “123456”}
},
}
[[email protected] aaa]#
[[email protected] aaa]# vim ansible.cfg
[[email protected] aaa]# cat ansible.cfg
[defaults]
inventory = my.sh
host_key_checking = False
[[email protected] aaa]#
[[email protected] aaa]# ansible aa -m ping
192.168.1.56 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
192.168.1.55 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
步骤二、批量执行命令
先把主机配置文件改回去,不用脚本,用myhost
[[email protected] aaa]# cat ansible.cfg
[defaults]
inventory = myhost
host_key_checking = False
1、查看负载
[[email protected] aaa]# ansible app -m command -a ‘uptime’
db1 | SUCCESS | rc=0 >>
09:32:45 up 22:28, 2 users, load average: 0.00, 0.01, 0.05
web1 | SUCCESS | rc=0 >>
09:32:46 up 22:28, 2 users, load average: 0.00, 0.01, 0.05
db2 | SUCCESS | rc=0 >>
09:32:46 up 22:28, 2 users, load average: 0.00, 0.01, 0.05
web2 | SUCCESS | rc=0 >>
09:32:46 up 22:28, 2 users, load average: 0.04, 0.03, 0.05
[[email protected] aaa]#
2、查看时间
[[email protected] aaa]# ansible app -m command -a ‘date +%F\ %T’
db1 | SUCCESS | rc=0 >>
2018-10-20 09:34:10
db2 | SUCCESS | rc=0 >>
2018-10-20 09:34:10
web1 | SUCCESS | rc=0 >>
2018-10-20 09:34:10
web2 | SUCCESS | rc=0 >>
2018-10-20 09:34:10
[[email protected] aaa]#
批量部署密钥
先把之前的改动都改回去
[[email protected] aaa]# cd /root/.ssh/
[[email protected] .ssh]# vim /etc/ansible/hosts
[[email protected] .ssh]# grep -v “^#” /etc/ansible/hosts | grep -v “^$”
[web]
web1
web2
[db]
db[1:2]
[other]
cache
因为我之前做了免密,所以Ping都成功了,实际上是不成功的
[[email protected] .ssh]# ansible all -m ping
web2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
db1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
cache | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
web1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
db2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
部署密钥,并测试
[[email protected] .ssh]# ansible all -m authorized_keys -a “user=root exclusive=true manage_dir=true key=’$(< /root/.ssh/id_rsa.pub)'” -k
SSH password:
[[email protected] .ssh]# ansible all -m ping
web2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
db2 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
cache | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
db1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
web1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
5 案例5:练习模块
5.1 问题
本案例要求:
练习使用command , shell , raw, script模块
5.2 步骤
实现此案例需要按照如下步骤进行。
步骤一:练习模块
ansible-doc //模块的手册,相当于man
ansible-doc -l //列出所有模块
ansible-doc 模块名 //查看指定模块的帮助信息
1)ping模块
[[email protected] .ssh]# ansible web1 -m ping
web1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
2)command模块
[[email protected] .ssh]# ansible web1 -m command -a ‘chdir=/tmp touch f1’ //创建成功
[[email protected] ~]# cd /tmp/
[[email protected] tmp]# ls //在web1上面查看
f1
3)shell模块
[[email protected] .ssh]# ansible web1 -m shell -a ‘chdir=/tmp touch f2’ //创建成功
[[email protected] ~]# cd /tmp/
[[email protected] tmp]# ls //在web1上面查看
f2
4)raw模块
[[email protected] .ssh]# ansible web1 -m raw -a ‘chdir=/tmp touch f3’
//文件可以创建,但无法切换目录,文件在用户家目录下生成
web1 | SUCCESS | rc=0 >>
Shared connection to web1 closed.
[[email protected] tmp]# cd /root/
[[email protected] ~]# ls //在web1上面查看
f3
5)script模块
对于太复杂的命令,可以写个脚本,然后用script模块执行
在web1主机上创建zhangsan3用户,修改zhangsan3的密码为123456,设置zhangsan3第一次登陆必须修改密码
用命令写:
[[email protected] .ssh]# ansible web1 -m shell -a ‘useradd zhangsan3’
[[email protected] .ssh]# ansible web1 -m shell -a ‘echo 123456 | passwd –stdin zhangsan3’
[[email protected] .ssh]# ssh -l zhangsan3 web1
[email protected]’s password: //输入zhangsan3的密码
[[email protected] .ssh]# ansible web1 -m shell -a ‘chage -d 0 zhangsan3’
[[email protected] .ssh]# ssh -l zhangsan3 web1
用脚本写,script模块执行:
[[email protected] .ssh]# vim user.sh
#!/bin/bash
useradd zhangsan3
echo 123456 | passwd –stdin zhangsan3
chage -d 0 zhangsan3
echo
[[email protected] .ssh]# ansible web1 -m script -a ‘./user.sh’
web1 | SUCCESS => {
“changed”: true,
“rc”: 0,
“stderr”: “Shared connection to web1 closed.\r\n”,
“stdout”: “Changing password for user zhangsan3.\r\npasswd: all authentication tokens updated successfully.\r\n\r\n”,
“stdout_lines”: [
“Changing password for user zhangsan3.”,
“passwd: all authentication tokens updated successfully.”,
“”
]
}
[[email protected] .ssh]# ssh -l lisi web1
[email protected]’s password:
You are required to change your password immediately (root enforced)
Last login: Thu Sep 6 14:51:33 2018 from 192.168.1.51
WARNING: Your password has expired.
You must change your password now and login again!
Changing password for user lisi.
Changing password for lisi.
(current) UNIX password:
代码如下
查看模块和帮助文档
[[email protected] .ssh]# ansible-doc (后面接模块名,查看详细的帮助信息)
Usage: ansible-doc [-l|-s] [options] [-t <plugin type] [plugin]
plugin documentation tool
Options:
-a, –all **For internal testing only** Show documentation for
all plugins.
-h, –help show this help message and exit
-l, –list List available plugins
-M MODULE_PATH, –module-path=MODULE_PATH
prepend colon-separated path(s) to module library
(default=[u’/root/.ansible/plugins/modules’,
u’/usr/share/ansible/plugins/modules’])
-s, –snippet Show playbook snippet for specified plugin(s)
-t TYPE, –type=TYPE Choose which plugin type (defaults to “module”)
-v, –verbose verbose mode (-vvv for more, -vvvv to enable
connection debugging)
–version show program’s version number and exit
See man pages for Ansible CLI options or website for tutorials
https://docs.ansible.com
ERROR! Incorrect options passed
[[email protected] .ssh]# ansible-doc -l
a10_server Manage A10 Networks AX/SoftAX/Thunder/vThunder devices’ server obj…
a10_server_axapi3 Manage A10 Networks AX/SoftAX/Thunder/vThunder devices
1、使用PING模块
[[email protected] .ssh]# ansible web1 -m ping
web1 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
2、使用COMMAND模块
[[email protected] .ssh]# ansible web1 -m command -a ‘chdir=/tmp touch f1’
[WARNING]: Consider using file module with state=touch rather than running touch
web1 | SUCCESS | rc=0 >>
[[email protected] .ssh]# ssh web1
Last login: Sat Oct 20 11:23:16 2018 from 192.168.1.51
[[email protected] ~]# ll /tmp/
总用量 0
-rw-r–r– 1 root root 0 10月 20 11:23 f1
drwx—— 3 root root 17 10月 19 11:04 systemd-private-767695a249a54d18959ba8b304711521-chronyd.service-4NUlRQ
[[email protected] ~]#
3、使用SHELL模块
[[email protected] .ssh]# ansible web1 -m shell -a ‘chdir=/tmp touch f2’
[WARNING]: Consider using file module with state=touch rather than running touch
web1 | SUCCESS | rc=0 >>
[[email protected] .ssh]# ssh web1
Last login: Sat Oct 20 11:24:54 2018 from 192.168.1.51
[[email protected] ~]# ll /tmp/
总用量 0
-rw-r–r– 1 root root 0 10月 20 11:23 f1
-rw-r–r– 1 root root 0 10月 20 11:24 f2
drwx—— 3 root root 17 10月 19 11:04 systemd-private-767695a249a54d18959ba8b304711521-chronyd.service-4NUlRQ
[[email protected] ~]#
4、使用RAW模块,可以看到RAW不支持切换目录
[[email protected] ~]# ansible web1 -m raw -a ‘chdir=/tmp touch f3’
web1 | SUCCESS | rc=0 >>
Shared connection to web1 closed.
5、SCRIPT模块,达到创建用户zhangsan3,密码123456,然后开机马上修改密码,可以看到如果用SSH那要操作很多步
[[email protected] ~]# ssh web1
Last login: Sat Oct 20 11:48:01 2018 from 192.168.1.51
[[email protected] ~]# ls
f3 RPM-GPG-KEY-CentOS-7
[[email protected] ~]# ll /tmp/
总用量 0
-rw-r–r– 1 root root 0 10月 20 11:23 f1
-rw-r–r– 1 root root 0 10月 20 11:24 f2
drwx—— 3 root root 17 10月 19 11:04 systemd-private-767695a249a54d18959ba8b304711521-chronyd.service-4NUlRQ
[[email protected] ~]#
[[email protected] ~]# ansible web1 -m shell -a ‘useradd zhangsan3’
web1 | SUCCESS | rc=0 >>
[[email protected] ~]# ansible web1 -m shell -a ‘echo 123456 | passwd –stdin zhangsan3’
web1 | SUCCESS | rc=0 >>
更改用户 zhangsan3 的密码 。
passwd:所有的身份验证令牌已经成功更新。
[[email protected] ~]# ssh -l zhangsan3 web1
[email protected]’s password:
[[email protected] ~]$ exit
登出
Connection to web1 closed.
[[email protected] ~]# ansible web1 -m shell -a ‘chage -d 0 zhangsan3’
web1 | SUCCESS | rc=0 >>
You are required to change your password immediately (root enforced)
Last login: Sat Oct 20 11:53:59 2018 from 192.168.1.51
WARNING: Your password has expired.
You must change your password now and login again!
Changing password for user zhangsan3.
Changing password for zhangsan3.
(current) UNIX password:
New password:
BAD PASSWORD: The password is shorter than 8 characters
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
Connection to web1 closed.
所以操作一下,用script模块,可以支持脚本
[[email protected] ~]# vim user.sh
[[email protected] ~]# cat user.sh
#!/bin/bash
useradd zhangsan4
echo 123456 | passwd –stdin zhangsan4
chage -d 0 zhangsan3
echo
[[email protected] ~]# ansible web1 -m script -a ‘./user.sh’
web1 | SUCCESS => {
“changed”: true,
“rc”: 0,
“stderr”: “Shared connection to web1 closed.\r\n”,
“stdout”: “更改用户 zhangsan4 的密码 。\r\npasswd:所有的身份验证令牌已经成功更新。\r\n\r\n”,
“stdout_lines”: [
“更改用户 zhangsan4 的密码 。”,
“passwd:所有的身份验证令牌已经成功更新。”,
“”
]
}
6 案例6:模块练习
6.1 问题
本案例要求:
使用copy模块同步数据
使用lineinfile模块编辑文件
使用replace模块修改文件
6.2 步骤
实现此案例需要按照如下步骤进行。
步骤一:模块练习
1)使用copy模块同步数据
src:要复制到进程主机的文件在本地的地址,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用”/”来结尾,则只复制目录里的内容,如果没有使用”/”来结尾,则包含目录在内的整个内容全部复制,类似于rsync
dest:必选项。进程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录
backup:在覆盖之前将原文件备份,备份文件包含时间信息。有两个选项:yes|no
force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes
[[email protected] .ssh]# ansible all -m shell -a ‘cat /etc/resolv.conf’
//查看/etc/resolv.conf
cache | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 192.168.1.254
search localhost
db2 | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 192.168.1.254
search localhost
web1 | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 192.168.1.254
search localhost
web2 | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 192.168.1.254
search localhost
db1 | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 192.168.1.254
search localhost
[[email protected] .ssh]# vi /etc/resolv.conf
nameserver 172.40.1.10
[[email protected] .ssh]# ansible all -m copy -a ‘src=/etc/resolv.conf dest=/etc/resolv.conf’ //复制本机的resolv.conf到其他主机
[[email protected] .ssh]# ansible all -m shell -a ‘cat /etc/resolv.conf’
//查看有nameserver 172.40.1.10
[[email protected] ~]# mkdir aa
[[email protected] ~]# ansible all -m copy -a ‘src=/root/aa dest=/root/a.log’
//复制本机的目录/root/aa到其他机器的/root/a.log,复制目录只能少数批量执行同步
[[email protected] ~]# ansible all -m shell -a ‘ls -ld /root’
db2 | SUCCESS | rc=0 >>
dr-xr-x—. 4 root root 167 Sep 6 11:48 /root
web2 | SUCCESS | rc=0 >>
dr-xr-x—. 4 root root 167 Sep 6 11:48 /root
cache | SUCCESS | rc=0 >>
dr-xr-x—. 4 root root 177 Sep 6 14:35 /root
db1 | SUCCESS | rc=0 >>
dr-xr-x—. 4 root root 167 Sep 6 11:48 /root
web1 | SUCCESS | rc=0 >>
dr-xr-x—. 4 root root 177 Sep 6 14:35 /root
2)使用lineinfile模块编辑文件
以行为基础,整行修改(整行被替换掉)
[[email protected] ~]# ansible cache -m lineinfile \
-a ‘path=/etc/sysconfig/network-scripts/ifcfg-eth0 \
regexp=”^ONBOOT=” line=”ONBOOT=\”no\””‘
cache | SUCCESS => {
“backup”: “”,
“changed”: true,
“msg”: “line replaced”
}
3)使用replace模块修改文件
修改文件的某一部分(替换一行中匹配的内容),以正则表达式匹配为基础修改
[[email protected] ~]# ansible cache -m replace -a \
‘path=/etc/sysconfig/network-scripts/ifcfg-eth0 \
regexp=”^(ONBOOT=).*” replace=”\1\”yes\””‘
cache | SUCCESS => {
“changed”: true,
“msg”: “1 replacements made”
}
代码如下
1、使用COPY模块同步数据
先看一眼原来的数据
[[email protected] ~]# ansible all -m shell -a ‘cat /etc/resolv.conf’
web2 | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 192.168.1.254
search localdomain
cache | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 192.168.1.254
search localdomain
db2 | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 192.168.1.254
search localdomain
web1 | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 192.168.1.254
search localdomain
db1 | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 192.168.1.254
search localdomain
改一下配置文件
[[email protected] ~]# vim /etc/resolv.conf
[[email protected] ~]# cat /etc/resolv.conf
; generated by /usr/sbin/dhclient-script
nameserver 176.204.0.227
search localdomain
然后同步复制一下
[[email protected] ~]# ansible all -m copy -a ‘src=/etc/resolv.conf dest=/etc/resolv.conf’
web2 | SUCCESS => {
“changed”: true,
“checksum”: “434fa1d70ea9d1ecd5b8880199f8677a8d7f208c”,
“dest”: “/etc/resolv.conf”,
“gid”: 0,
“group”: “root”,
“md5sum”: “acbefc844e58cc09b7f80d342bef9805”,
“mode”: “0644”,
“owner”: “root”,
“size”: 85,
“src”: “/root/.ansible/tmp/ansible-tmp-1540015462.08-33163582311272/source”,
“state”: “file”,
“uid”: 0
}
db1 | SUCCESS => {
“changed”: true,
“checksum”: “434fa1d70ea9d1ecd5b8880199f8677a8d7f208c”,
“dest”: “/etc/resolv.conf”,
“gid”: 0,
“group”: “root”,
“md5sum”: “acbefc844e58cc09b7f80d342bef9805”,
“mode”: “0644”,
“owner”: “root”,
“size”: 85,
“src”: “/root/.ansible/tmp/ansible-tmp-1540015462.08-65291445031988/source”,
“state”: “file”,
“uid”: 0
}
db2 | SUCCESS => {
“changed”: true,
“checksum”: “434fa1d70ea9d1ecd5b8880199f8677a8d7f208c”,
“dest”: “/etc/resolv.conf”,
“gid”: 0,
“group”: “root”,
“md5sum”: “acbefc844e58cc09b7f80d342bef9805”,
“mode”: “0644”,
“owner”: “root”,
“size”: 85,
“src”: “/root/.ansible/tmp/ansible-tmp-1540015462.09-203084136213341/source”,
“state”: “file”,
“uid”: 0
}
web1 | SUCCESS => {
“changed”: true,
“checksum”: “434fa1d70ea9d1ecd5b8880199f8677a8d7f208c”,
“dest”: “/etc/resolv.conf”,
“gid”: 0,
“group”: “root”,
“md5sum”: “acbefc844e58cc09b7f80d342bef9805”,
“mode”: “0644”,
“owner”: “root”,
“size”: 85,
“src”: “/root/.ansible/tmp/ansible-tmp-1540015462.03-68166612195333/source”,
“state”: “file”,
“uid”: 0
}
cache | SUCCESS => {
“changed”: true,
“checksum”: “434fa1d70ea9d1ecd5b8880199f8677a8d7f208c”,
“dest”: “/etc/resolv.conf”,
“gid”: 0,
“group”: “root”,
“md5sum”: “acbefc844e58cc09b7f80d342bef9805”,
“mode”: “0644”,
“owner”: “root”,
“size”: 85,
“src”: “/root/.ansible/tmp/ansible-tmp-1540015462.06-47005818047152/source”,
“state”: “file”,
“uid”: 0
}
再看一下
[[email protected] ~]# ansible all -m shell -a ‘cat /etc/resolv.conf’
cache | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 176.204.0.227
search localdomain
db1 | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 176.204.0.227
search localdomain
web1 | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 176.204.0.227
search localdomain
web2 | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 176.204.0.227
search localdomain
db2 | SUCCESS | rc=0 >>
; generated by /usr/sbin/dhclient-script
nameserver 176.204.0.227
search localdomain
复制本机的目录/root/aa到其他机器的/root/a.log,复制目录只能少数批量执行同步
[[email protected] ~]# ansible all -m copy -a ‘src=/root/aa dest=/root/a.log’
db2 | SUCCESS => {
“changed”: false,
“dest”: “/root/a.log/”,
“src”: “/root/aa”
}
web1 | SUCCESS => {
“changed”: false,
“dest”: “/root/a.log/”,
“src”: “/root/aa”
}
db1 | SUCCESS => {
“changed”: false,
“dest”: “/root/a.log/”,
“src”: “/root/aa”
}
cache | SUCCESS => {
“changed”: false,
“dest”: “/root/a.log/”,
“src”: “/root/aa”
}
web2 | SUCCESS => {
“changed”: false,
“dest”: “/root/a.log/”,
“src”: “/root/aa”
}
[[email protected] ~]# ansible all -m shell -a ‘ls -ld /root’
db2 | SUCCESS | rc=0 >>
dr-xr-x—. 6 root root 213 10月 20 09:15 /root
cache | SUCCESS | rc=0 >>
dr-xr-x—. 6 root root 213 10月 20 09:04 /root
db1 | SUCCESS | rc=0 >>
dr-xr-x—. 6 root root 235 10月 20 09:05 /root
web2 | SUCCESS | rc=0 >>
dr-xr-x—. 6 root root 213 10月 20 09:09 /root
web1 | SUCCESS | rc=0 >>
dr-xr-x—. 6 root root 223 10月 20 11:48 /root
[[email protected] ~]# ansible all -m shell -a ‘ls -lh /root’
cache | SUCCESS | rc=0 >>
总用量 4.0K
-rw-r–r–. 1 root root 1.7K 12月 10 2015 RPM-GPG-KEY-CentOS-7
db2 | SUCCESS | rc=0 >>
总用量 4.0K
-rw-r–r–. 1 root root 1.7K 12月 10 2015 RPM-GPG-KEY-CentOS-7
web2 | SUCCESS | rc=0 >>
总用量 4.0K
-rw-r–r–. 1 root root 1.7K 12月 10 2015 RPM-GPG-KEY-CentOS-7
db1 | SUCCESS | rc=0 >>
总用量 12K
-rw——- 1 root root 1.7K 10月 19 11:08 \
-rw-r–r– 1 root root 390 10月 19 11:08 \.pub
-rw-r–r–. 1 root root 1.7K 12月 10 2015 RPM-GPG-KEY-CentOS-7
web1 | SUCCESS | rc=0 >>
总用量 4.0K
-rw-r–r– 1 root root 0 10月 20 11:48 f3
-rw-r–r–. 1 root root 1.7K 12月 10 2015 RPM-GPG-KEY-CentOS-7
2、使用lineinfile编辑文件
[[email protected] ~]# ansible cache -m lineinfile -a ‘path=/etc/sysconfig/network-scripts/ifcfg-eth0 regexp=”^ONBOOT=” line=”ONBOOT=\”no\””‘
cache | SUCCESS => {
“backup”: “”,
“changed”: true,
“msg”: “line replaced”
}
确认一下,可以看到ONBOOT行已经更改
[[email protected] ~]# ansible cache -m shell -a ‘cat /etc/sysconfig/network-scripts/ifcfg-eth0’
cache | SUCCESS | rc=0 >>
# Generated by dracut initrd
DEVICE=”eth0″
NAME=”eth0″
ONBOOT=”no”
IPV6INIT=no
TYPE=Ethernet
BOOTPROTO=”static”
IPADDR=192.168.1.56
PREFIX=24
GATEWAY=192.168.1.254
3、使用replace模块修改文件
[[email protected] ~]# ansible cache -m replace -a ‘path=/etc/sysconfig/network-scripts/ifcfg-eth0 regexp=”^(ONBOOT=).*” replace=”\1\”yes\””‘
cache | SUCCESS => {
“changed”: true,
“msg”: “1 replacements made”
}
确认一下,可以看到ONBOOT行又改回去了
[[email protected] ~]# ansible cache -m shell -a ‘cat /etc/sysconfig/network-scripts/ifcfg-eth0’cache | SUCCESS | rc=0 >>
# Generated by dracut initrd
DEVICE=”eth0″
NAME=”eth0″
ONBOOT=”yes”
IPV6INIT=no
TYPE=Ethernet
BOOTPROTO=”static”
IPADDR=192.168.1.56
PREFIX=24
GATEWAY=192.168.1.254
7 案例7:综合练习
7.1 问题
本案例要求:
安装Apache并修改监听端口为8080
修改ServerName配置,执行apachectl -t命令不报错
设置默认主页hello world
启动服务并设开机自启
7.2 步骤
实现此案例需要按照如下步骤进行。
步骤一:熟悉模块
1)yum模块
[[email protected] ~]# ansible other -m yum -a ‘name=”lrzsz” state=removed’
//lrzsz软件包名,removed=absent删除
[[email protected] ~]# ansible other -m yum -a ‘name=”lrzsz,lftp” state=installed’
//安装多个软件包,不写state默认为安装
2)service模块
[[email protected] ~]# ansible other -m service -a ‘name=”sshd” enabled=”yes” state=”started”‘ //sshd服务名,开机启动同时启动这个服务
3)setup模块
filter 过滤指定的关键字(可以过滤到我们需要的信息)
[[email protected] ~]# ansible cache -m setup -a ‘filter=os’
cache | SUCCESS => {
“ansible_facts”: {},
“changed”: false
}
[[email protected] ~]# ansible cache -m setup -a ‘filter=ansible_distribution’
cache | SUCCESS => {
“ansible_facts”: {
“ansible_distribution”: “CentOS”
},
“changed”: false
}
步骤二:安装Apache
1)安装Apache服务设置开机自启
[[email protected] ~]# ansible cache -m yum -a ‘name=httpd state=installed’
[[email protected] ~]# ansible cache -m service -a ‘name=httpd enabled=yes state=started’
2)修改端口号为8080
[[email protected] ~]# ssh cache
Last login: Thu Sep 6 15:30:33 2018 from 192.168.1.51
[[email protected] ~]# cat /etc/httpd/conf/httpd.conf | grep Listen
Listen 80
[[email protected] ~]# ansible cache -m lineinfile -a ‘path=”/etc/httpd/conf/httpd.conf” regexp=”^Listen ” line=”Listen 8080″‘cache | SUCCESS => {
“backup”: “”,
“changed”: true,
“msg”: “line replaced”
}
[[email protected] ~]# ssh cache
Listen 8080
步骤三:修改ServerName配置,执行apachectl -t命令不报错
1)没有修改之前
[[email protected] ~]# apachectl -t //有报错
AH00558: httpd: Could not reliably determine the server’s fully qualified domain name, using 192.168.1.56. Set the ‘ServerName’ directive globally to suppress this message
Syntax OK
2)修改之后
[[email protected] ~]# ansible cache -m lineinfile -a ‘path=”/etc/httpd/conf/httpd.conf” regexp=”^ServerName ” line=”ServerName 0.0.0.0″‘
cache | SUCCESS => {
“backup”: “”,
“changed”: true,
“msg”: “line added”
}
[[email protected] ~]# ssh cache
Last login: Thu Sep 6 15:36:08 2018 from 192.168.1.51
[[email protected] ~]# apachectl -t
Syntax OK
步骤四:设置默认主页为hello world
[[email protected] ~]# ansible cache -m copy -a ‘src=/root/index.html dest=/var/www/html/index.html’ ///root/index.html这个页面可以自己写
cache | SUCCESS => {
“changed”: true,
“checksum”: “22596363b3de40b06f981fb85d82312e8c0ed511”,
“dest”: “/var/www/html/index.html”,
“gid”: 0,
“group”: “root”,
“md5sum”: “6f5902ac237024bdd0c176cb93063dc4”,
“mode”: “0644”,
“owner”: “root”,
“size”: 12,
“src”: “/root/.ansible/tmp/ansible-tmp-1536219767.29-30682157793478/source”,
“state”: “file”,
“uid”: 0
}
代码如下
1、YUM模块
把yum清理一下
[[email protected] ~]# ansible all -m shell -a ‘rm -rf /etc/yum.repos.d/dvd.repo’
[WARNING]: Consider using file module with state=absent rather than running rm
db1 | SUCCESS | rc=0 >>
web1 | SUCCESS | rc=0 >>
web2 | SUCCESS | rc=0 >>
cache | SUCCESS | rc=0 >>
db2 | SUCCESS | rc=0 >>
[[email protected] ~]# ansible all -m shell -a ‘ls -lh /etc/yum.repos.d/’
db1 | SUCCESS | rc=0 >>
总用量 32K
-rw-r–r–. 1 root root 1.7K 8月 30 2017 CentOS-Base.repo
-rw-r–r–. 1 root root 1.3K 8月 30 2017 CentOS-CR.repo
-rw-r–r–. 1 root root 649 8月 30 2017 CentOS-Debuginfo.repo
-rw-r–r–. 1 root root 314 8月 30 2017 CentOS-fasttrack.repo
-rw-r–r–. 1 root root 630 8月 30 2017 CentOS-Media.repo
-rw-r–r–. 1 root root 1.3K 8月 30 2017 CentOS-Sources.repo
-rw-r–r–. 1 root root 3.8K 8月 30 2017 CentOS-Vault.repo
-rw-r–r– 1 root root 180 10月 19 11:16 local.repo
cache | SUCCESS | rc=0 >>
总用量 32K
-rw-r–r–. 1 root root 1.7K 8月 30 2017 CentOS-Base.repo
-rw-r–r–. 1 root root 1.3K 8月 30 2017 CentOS-CR.repo
-rw-r–r–. 1 root root 649 8月 30 2017 CentOS-Debuginfo.repo
-rw-r–r–. 1 root root 314 8月 30 2017 CentOS-fasttrack.repo
-rw-r–r–. 1 root root 630 8月 30 2017 CentOS-Media.repo
-rw-r–r–. 1 root root 1.3K 8月 30 2017 CentOS-Sources.repo
-rw-r–r–. 1 root root 3.8K 8月 30 2017 CentOS-Vault.repo
-rw-r–r– 1 root root 180 10月 19 11:16 local.repo
db2 | SUCCESS | rc=0 >>
总用量 32K
-rw-r–r–. 1 root root 1.7K 8月 30 2017 CentOS-Base.repo
-rw-r–r–. 1 root root 1.3K 8月 30 2017 CentOS-CR.repo
-rw-r–r–. 1 root root 649 8月 30 2017 CentOS-Debuginfo.repo
-rw-r–r–. 1 root root 314 8月 30 2017 CentOS-fasttrack.repo
-rw-r–r–. 1 root root 630 8月 30 2017 CentOS-Media.repo
-rw-r–r–. 1 root root 1.3K 8月 30 2017 CentOS-Sources.repo
-rw-r–r–. 1 root root 3.8K 8月 30 2017 CentOS-Vault.repo
-rw-r–r– 1 root root 180 10月 19 11:16 local.repo
web2 | SUCCESS | rc=0 >>
总用量 32K
-rw-r–r–. 1 root root 1.7K 8月 30 2017 CentOS-Base.repo
-rw-r–r–. 1 root root 1.3K 8月 30 2017 CentOS-CR.repo
-rw-r–r–. 1 root root 649 8月 30 2017 CentOS-Debuginfo.repo
-rw-r–r–. 1 root root 314 8月 30 2017 CentOS-fasttrack.repo
-rw-r–r–. 1 root root 630 8月 30 2017 CentOS-Media.repo
-rw-r–r–. 1 root root 1.3K 8月 30 2017 CentOS-Sources.repo
-rw-r–r–. 1 root root 3.8K 8月 30 2017 CentOS-Vault.repo
-rw-r–r– 1 root root 180 10月 19 11:16 local.repo
web1 | SUCCESS | rc=0 >>
总用量 32K
-rw-r–r–. 1 root root 1.7K 8月 30 2017 CentOS-Base.repo
-rw-r–r–. 1 root root 1.3K 8月 30 2017 CentOS-CR.repo
-rw-r–r–. 1 root root 649 8月 30 2017 CentOS-Debuginfo.repo
-rw-r–r–. 1 root root 314 8月 30 2017 CentOS-fasttrack.repo
-rw-r–r–. 1 root root 630 8月 30 2017 CentOS-Media.repo
-rw-r–r–. 1 root root 1.3K 8月 30 2017 CentOS-Sources.repo
-rw-r–r–. 1 root root 3.8K 8月 30 2017 CentOS-Vault.repo
-rw-r–r– 1 root root 180 10月 19 11:16 local.repo
[[email protected] ~]#
先安装一个lrzsz
[[email protected] ~]# ansible other -m yum -a ‘name=’lrzsz’ state=installed’
cache | SUCCESS => {
“changed”: true,
“msg”: “”,
“rc”: 0,
“results”: [
“Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.163.com\n * extras: mirrors.163.com\n * updates: mirrors.163.com\nResolving Dependencies\n–> Running transaction check\n—> Package lrzsz.x86_64 0:0.12.20-36.el7 will be installed\n–> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n lrzsz x86_64 0.12.20-36.el7 base 78 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 78 k\nInstalled size: 181 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : lrzsz-0.12.20-36.el7.x86_64 1/1 \n Verifying : lrzsz-0.12.20-36.el7.x86_64 1/1 \n\nInstalled:\n lrzsz.x86_64 0:0.12.20-36.el7 \n\nComplete!\n”
]
}
然后卸载是一下
[[email protected] ~]# ansible other -m yum -a ‘name=’lrzsz’ state=removed’
cache | SUCCESS => {
“changed”: true,
“msg”: “”,
“rc”: 0,
“results”: [
“已加载插件:fastestmirror\n正在解决依赖关系\n–> 正在检查事务\n—> 软件包 lrzsz.x86_64.0.0.12.20-36.el7 将被 删除\n–> 解决依赖关系完成\n\n依赖关系解决\n\n================================================================================\n Package 架构 版本 源 大小\n================================================================================\n正在删除:\n lrzsz x86_64 0.12.20-36.el7 @base 181 k\n\n事务概要\n================================================================================\n移除 1 软件包\n\n安装大小:181 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n 正在删除 : lrzsz-0.12.20-36.el7.x86_64 1/1 \n 验证中 : lrzsz-0.12.20-36.el7.x86_64 1/1 \n\n删除:\n lrzsz.x86_64 0:0.12.20-36.el7 \n\n完毕!\n”
]
}
2、service模块
[[email protected] ~]# ansible other -m service -a ‘name=”sshd” enabled=”yes” state=”started”‘
cache | SUCCESS => {
“changed”: false,
“enabled”: true,
“name”: “sshd”,
“state”: “started”,
“status”: {
“ActiveEnterTimestamp”: “五 2018-10-19 11:04:46 CST”,
“ActiveEnterTimestampMonotonic”: “7203799”,
“ActiveExitTimestampMonotonic”: “0”,
“ActiveState”: “active”,
“After”: “sshd-keygen.service system.slice network.target systemd-journald.socket basic.target”,
“AllowIsolate”: “no”,
“AmbientCapabilities”: “0”,
“AssertResult”: “yes”,
“AssertTimestamp”: “五 2018-10-19 11:04:46 CST”,
“AssertTimestampMonotonic”: “7185185”,
“Before”: “shutdown.target multi-user.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”: “yes”,
“ConditionTimestamp”: “五 2018-10-19 11:04:46 CST”,
“ConditionTimestampMonotonic”: “7185184”,
“ConflictedBy”: “sshd.socket”,
“Conflicts”: “shutdown.target”,
“ConsistsOf”: “sshd-keygen.service”,
“ControlGroup”: “/system.slice/sshd.service”,
“ControlPID”: “0”,
“DefaultDependencies”: “yes”,
“Delegate”: “no”,
“Description”: “OpenSSH server daemon”,
“DevicePolicy”: “auto”,
“Documentation”: “man:sshd(8) man:sshd_config(5)”,
“EnvironmentFile”: “/etc/sysconfig/sshd (ignore_errors=no)”,
“ExecMainCode”: “0”,
“ExecMainExitTimestampMonotonic”: “0”,
“ExecMainPID”: “697”,
“ExecMainStartTimestamp”: “五 2018-10-19 11:04:46 CST”,
“ExecMainStartTimestampMonotonic”: “7185992”,
“ExecMainStatus”: “0”,
“ExecReload”: “{ path=/bin/kill ; argv[]=/bin/kill -HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }”,
“ExecStart”: “{ path=/usr/sbin/sshd ; argv[]=/usr/sbin/sshd -D $OPTIONS ; ignore_errors=no ; start_time=[五 2018-10-19 11:04:46 CST] ; stop_time=[n/a] ; pid=697 ; code=(null) ; status=0/0 }”,
“FailureAction”: “none”,
“FileDescriptorStoreMax”: “0”,
“FragmentPath”: “/usr/lib/systemd/system/sshd.service”,
“GuessMainPID”: “yes”,
“IOScheduling”: “0”,
“Id”: “sshd.service”,
“IgnoreOnIsolate”: “no”,
“IgnoreOnSnapshot”: “no”,
“IgnoreSIGPIPE”: “yes”,
“InactiveEnterTimestampMonotonic”: “0”,
“InactiveExitTimestamp”: “五 2018-10-19 11:04:46 CST”,
“InactiveExitTimestampMonotonic”: “7186043”,
“JobTimeoutAction”: “none”,
“JobTimeoutUSec”: “0”,
“KillMode”: “process”,
“KillSignal”: “15”,
“LimitAS”: “18446744073709551615”,
“LimitCORE”: “18446744073709551615”,
“LimitCPU”: “18446744073709551615”,
“LimitDATA”: “18446744073709551615”,
“LimitFSIZE”: “18446744073709551615”,
“LimitLOCKS”: “18446744073709551615”,
“LimitMEMLOCK”: “65536”,
“LimitMSGQUEUE”: “819200”,
“LimitNICE”: “0”,
“LimitNOFILE”: “4096”,
“LimitNPROC”: “7923”,
“LimitRSS”: “18446744073709551615”,
“LimitRTPRIO”: “0”,
“LimitRTTIME”: “18446744073709551615”,
“LimitSIGPENDING”: “7923”,
“LimitSTACK”: “18446744073709551615”,
“LoadState”: “loaded”,
“MainPID”: “697”,
“MemoryAccounting”: “no”,
“MemoryCurrent”: “18446744073709551615”,
“MemoryLimit”: “18446744073709551615”,
“MountFlags”: “0”,
“Names”: “sshd.service”,
“NeedDaemonReload”: “no”,
“Nice”: “0”,
“NoNewPrivileges”: “no”,
“NonBlocking”: “no”,
“NotifyAccess”: “main”,
“OOMScoreAdjust”: “0”,
“OnFailureJobMode”: “replace”,
“PermissionsStartOnly”: “no”,
“PrivateDevices”: “no”,
“PrivateNetwork”: “no”,
“PrivateTmp”: “no”,
“ProtectHome”: “no”,
“ProtectSystem”: “no”,
“RefuseManualStart”: “no”,
“RefuseManualStop”: “no”,
“RemainAfterExit”: “no”,
“Requires”: “basic.target”,
“Restart”: “on-failure”,
“RestartUSec”: “42s”,
“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”: “running”,
“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”: “enabled”,
“UnitFileState”: “enabled”,
“WantedBy”: “multi-user.target”,
“Wants”: “sshd-keygen.service system.slice”,
“WatchdogTimestamp”: “五 2018-10-19 11:04:46 CST”,
“WatchdogTimestampMonotonic”: “7203782”,
“WatchdogUSec”: “0”
}
}
3、setup模块
filter过滤指定的关键字
[[email protected] ~]# ansible cache -m setup -a ‘filter=os’
cache | SUCCESS => {
“ansible_facts”: {},
“changed”: false
}
[[email protected] ~]# ansible cache -m setup -a ‘filter=ansible_distribution’
cache | SUCCESS => {
“ansible_facts”: {
“ansible_distribution”: “CentOS”
},
“changed”: false
}
[[email protected] ~]#
步骤2,安装Apache
[[email protected] ~]# ansible cache -m yum -a ‘name=httpd state=installed’
cache | SUCCESS => {
“changed”: true,
“msg”: “”,
“rc”: 0,
“results”: [
“Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.163.com\n * extras: mirrors.163.com\n * updates: mirrors.163.com\nResolving Dependencies\n–> Running transaction check\n—> Package httpd.x86_64 0:2.4.6-80.el7.centos.1 will be installed\n–> Processing Dependency: httpd-tools = 2.4.6-80.el7.centos.1 for package: httpd-2.4.6-80.el7.centos.1.x86_64\n–> Processing Dependency: /etc/mime.types for package: httpd-2.4.6-80.el7.centos.1.x86_64\n–> Processing Dependency: libaprutil-1.so.0()(64bit) for package: httpd-2.4.6-80.el7.centos.1.x86_64\n–> Processing Dependency: libapr-1.so.0()(64bit) for package: httpd-2.4.6-80.el7.centos.1.x86_64\n–> Running transaction check\n—> Package apr.x86_64 0:1.4.8-3.el7_4.1 will be installed\n—> Package apr-util.x86_64 0:1.5.2-6.el7 will be installed\n—> Package httpd-tools.x86_64 0:2.4.6-80.el7.centos.1 will be installed\n—> Package mailcap.noarch 0:2.1.41-2.el7 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.1 updates 2.7 M\nInstalling for dependencies:\n apr x86_64 1.4.8-3.el7_4.1 base 103 k\n apr-util x86_64 1.5.2-6.el7 base 92 k\n httpd-tools x86_64 2.4.6-80.el7.centos.1 updates 90 k\n mailcap noarch 2.1.41-2.el7 base 31 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package (+4 Dependent packages)\n\nTotal download size: 3.0 M\nInstalled size: 10 M\nDownloading packages:\n——————————————————————————–\nTotal 2.6 MB/s | 3.0 MB 00:01 \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : apr-1.4.8-3.el7_4.1.x86_64 1/5 \n Installing : apr-util-1.5.2-6.el7.x86_64 2/5 \n Installing : httpd-tools-2.4.6-80.el7.centos.1.x86_64 3/5 \n Installing : mailcap-2.1.41-2.el7.noarch 4/5 \n Installing : httpd-2.4.6-80.el7.centos.1.x86_64 5/5 \n Verifying : mailcap-2.1.41-2.el7.noarch 1/5 \n Verifying : httpd-tools-2.4.6-80.el7.centos.1.x86_64 2/5 \n Verifying : apr-util-1.5.2-6.el7.x86_64 3/5 \n Verifying : apr-1.4.8-3.el7_4.1.x86_64 4/5 \n Verifying : httpd-2.4.6-80.el7.centos.1.x86_64 5/5 \n\nInstalled:\n httpd.x86_64 0:2.4.6-80.el7.centos.1 \n\nDependency Installed:\n apr.x86_64 0:1.4.8-3.el7_4.1 apr-util.x86_64 0:1.5.2-6.el7 \n httpd-tools.x86_64 0:2.4.6-80.el7.centos.1 mailcap.noarch 0:2.1.41-2.el7 \n\nComplete!\n”
]
}
启动appache
[[email protected] ~]# ansible cache -m service -a ‘name=httpd enabled=yes state=started’
cache | SUCCESS => {
“changed”: true,
“enabled”: true,
“name”: “httpd”,
“state”: “started”,
“status”: {
“ActiveEnterTimestampMonotonic”: “0”,
“ActiveExitTimestampMonotonic”: “0”,
“ActiveState”: “inactive”,
“After”: “remote-fs.target nss-lookup.target basic.target tmp.mount systemd-journald.socket system.slice network.target -.mount”,
“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”: “7923”,
“LimitRSS”: “18446744073709551615”,
“LimitRTPRIO”: “0”,
“LimitRTTIME”: “18446744073709551615”,
“LimitSIGPENDING”: “7923”,
“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”: “basic.target -.mount”,
“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”
}
}
[[email protected] ~]#
2、修改端口号为8080
修改前看一眼
[[email protected] ~]# ansible cache -m shell -a ‘cat /etc/httpd/conf/httpd.conf | grep Listen’
cache | SUCCESS | rc=0 >>
# Listen: Allows you to bind Apache to specific IP addresses and/or
# Change this to Listen on specific IP addresses as shown below to
#Listen 12.34.56.78:80
Listen 80
更改端口
[[email protected] ~]# ansible cache -m lineinfile -a ‘path=”/etc/httpd/conf/httpd.conf” regexp=”^Listen ” line=”Listen 8080″‘
cache | SUCCESS => {
“backup”: “”,
“changed”: true,
“msg”: “line added”
}
修改后确认
[[email protected] ~]# ansible cache -m shell -a ‘cat /etc/httpd/conf/httpd.conf | grep Listen’cache | SUCCESS | rc=0 >>
# Listen: Allows you to bind Apache to specific IP addresses and/or
# Change this to Listen on specific IP addresses as shown below to
#Listen 12.34.56.78:80
Listen 8080
登陆到cache可以发现apachectl检查不通过
[[email protected] ~]# apachectl -t
AH00558: httpd: Could not reliably determine the server’s fully qualified domain name, using 192.168.1.56. Set the ‘ServerName’ directive globally to suppress this message
Syntax OK
修改一下
[[email protected] ~]# ansible cache -m lineinfile -a ‘path=”/etc/httpd/conf/httpd.conf” regexp=”^ServerName ” line=”ServerName 0.0.0.0″‘
cache | SUCCESS => {
“backup”: “”,
“changed”: true,
“msg”: “line added”
}
[[email protected] ~]# ssh cache
Last login: Sat Oct 20 15:11:42 2018 from 192.168.1.51
[[email protected] ~]# apachectl -t
Syntax OK
登陆到cache重启下服务
[[email protected] ~]# systemctl restart httpd
重启服务并拷贝配置文件
[[email protected] ~]# ansible cache -m copy -a ‘src=/root/index.html dest=/var/www/html/index.html’
cache | SUCCESS => {
“changed”: true,
“checksum”: “22596363b3de40b06f981fb85d82312e8c0ed511”,
“dest”: “/var/www/html/index.html”,
“gid”: 0,
“group”: “root”,
“md5sum”: “6f5902ac237024bdd0c176cb93063dc4”,
“mode”: “0644”,
“owner”: “root”,
“size”: 12,
“src”: “/root/.ansible/tmp/ansible-tmp-1540019610.06-226153421523891/source”,
“state”: “file”,
“uid”: 0
}
测试一下网页
[[email protected] ~]# curl cache:8080
hello world