Ansible自动化运维实战

Ansible自动化运维实战

一.Ansible简介

Ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具的优点,实现了批量系统配置,批量程序部署,批量运行命令等功能(puppet,cfengie,chef,func,fabric)
它使用SSH来和节点进行通信。分布式,无需客户端,轻量级,配置语法使用 YMAL 及Jinja2模板语言,更强的远程命令执行操作。

二.工作原理

Ansible 在管理节点将 Ansible 模块通过 SSH 协议推送到被管理端执行,执行完之后自动删除,可以使用 SVN 等来管理自定义模块及编排

三.install部署

ansilbe主服务器配置DNS域名解析

1.添加

[root@localhost ~]# vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.200.145 ansible
192.168.200.146 host1
192.168.200.147 host2
192.168.200.148 host3
192.168.200.149 host4`

2.配置完成DNS解析,ping一下查看是否成功

[root@localhost ~]# ping host1
PING host1 (192.168.200.146) 56(84) bytes of data.
64 bytes from host1 (192.168.200.146): icmp_seq=1 ttl=64 time=1.94 ms
64 bytes from host1 (192.168.200.146): icmp_seq=2 ttl=64 time=1.06 ms
2 packets transmitted, 2 received, 0% packet loss, time 1009ms
rtt min/avg/max/mdev = 1.062/1.503/1.945/0.443 ms`
[root@localhost ~]# ping host2
PING host2 (192.168.200.147) 56(84) bytes of data.
64 bytes from host2 (192.168.200.147): icmp_seq=1 ttl=64 time=1.81 ms
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 1.812/1.812/1.812/0.000 ms`
[root@localhost ~]# ping host3
PING host3 (192.168.200.148) 56(84) bytes of data.
64 bytes from host3 (192.168.200.148): icmp_seq=1 ttl=64 time=0.730 ms
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.730/0.730/0.730/0.000 ms`
[root@localhost ~]# ping host4
PING host4 (192.168.200.149) 56(84) bytes of data.
64 bytes from host4 (192.168.200.149): icmp_seq=1 ttl=64 time=0.711 ms
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.711/0.711/0.711/0.000 ms`

ansilbe 客户机无需配置

3.install ansible,安装ansible

[root@localhost ~]# yum -y install epel-release`
[root@localhost ~]# yum -y install ansible`
检查yum是否安装成功
>`[root@localhost ~]# rpm -qc ansible
/etc/ansible/ansible.cfg
/etc/ansible/hosts

ssh-key(可选)

1.生成密钥

[root@localhost ~]# ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Created directory '/root/.ssh'.
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:U7JxuQLNdLymGGwCOkXD2dPJqppwtsgQUpTYxPI+c6s [email protected]
The key's randomart image is:
+---[RSA 2048]----+
| O=+ o ....      |
|o X.o ++ ...     |
| * . +. = +.     |
|= . o +. *o.     |
|.+ . o oSo.      |
|o B . . .o       |
|+* = .           |
|+.. .            |
|  E.             |
+----[SHA256]-----+

2.生成两个密钥文件

[root@localhost ~]# ls .ssh/
id_rsa  id_rsa.pub

3.将密钥发送出去,发给需要免密的服务器

[root@localhost ~]# ssh-copy-id 192.168.200.146
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.200.146 (192.168.200.146)' can't be established.
ECDSA key fingerprint is SHA256:zwhKo1o7AJBSuXoO9N/AP4GSbVQsKvfGQrgl8EqMbW8.
ECDSA key fingerprint is MD5:8b:6c:0d:c0:80:6a:68:8c:e9:2d:5a:21:77:f2:b4:7c.
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: 
Now try logging into the machine, with:   "ssh '192.168.200.146'"
and check to make sure that only the key(s) you wanted were added.

四.ansible基础

定义主机清单

1.编辑配置文件在最后加上四台主机,我们配置了四台服务器的DNS,可以被ansilbe控制

[root@localhost ~]# vim /etc/ansible/hosts 
host1
host2
host3
host4

2.利用ansible工具测试连通性,显示绿色证明结果成功

[root@localhost ~]# ansible localhost -m ping
localhost | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}`

参数说明:
loaclhost 本机
-m   调用模块
ping  调用的模块

测试1号主机,第一次测试会显示选项yes/no,第二次测试就不会显示,直接显示测试结果。

[root@localhost ~]# ansible host1 -m ping
The authenticity of host 'host1 (192.168.200.146)' can't be established.
ECDSA key fingerprint is SHA256:zwhKo1o7AJBSuXoO9N/AP4GSbVQsKvfGQrgl8EqMbW8.
ECDSA key fingerprint is MD5:8b:6c:0d:c0:80:6a:68:8c:e9:2d:5a:21:77:f2:b4:7c.
Are you sure you want to continue connecting (yes/no)? **yes**
host1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

测试2号主机,由于上面对1号主机做了免密可以直接ping通,其他的主机没有做是ping不通的,这里显示结果失败,没有设置免密的主机下面会进行处理。

[root@localhost ~]# ansible  host2 -m ping
host2 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}

测试没有设置免密的主机,以2号主机为例

[root@localhost ~]# ansible  host2 -m ping  -u root -k  -o
SSH password: **隐式输入2号主机的密码**
host3 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}

>参数说明:
-u:ssh连接时使用用户
-k:交互式输入密码
-o:简洁显示结果

正确测试没有设置免密的主机连通性,需要两次访问。如果不这样操作,不论你怎样测试都是失败的。
第一次确认

[root@localhost ~]# ansible  host3 -m ping
The authenticity of host 'host3 (192.168.200.148)' can't be established.
ECDSA key fingerprint is SHA256:MoZUnS5n8wsVFKJiBxIbN1W9eaFUxwRs+U+uxQZ7sE0.
ECDSA key fingerprint is MD5:7c:24:f1:36:44:7c:9d:96:24:b1:e6:9a:0c:23:fd:b2.
Are you sure you want to continue connecting (yes/no)? **yes**
host3 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added 'host3,192.168.200.148' (ECDSA) to the list of known hosts.\r\nPermission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}

第二次测试增加用户名和密码选项,显示成功

[root@localhost ~]# ansible  host3 -m ping  -u root -k  -o
SSH password: 
host3 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}

3.取消yes/no的询问,只需要一次就可以访问成功,在ansible的服务器上修改配置文件

[root@localhost ~]# vim /etc/ssh/ssh_config
35 #   StrictHostKeyChecking ask
将35行取消注释,ask改为no,保存退出
35 StrictHostKeyChecking no`

重启ssh服务

[root@localhost ~]# systemctl restart sshd`

我们再去访问目标服务器时就不会提示yes/no的选项了,这里我访问4号主机此时一次就可以访问了,不需要上一步那样两次访问

[root@localhost ~]# ansible  host4 -m ping  -u root -k  -o
SSH password: 
host4 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}

错误示范:主机清单里没有添加5号主机,这里显示失败,在工作中一定要注意。

[root@localhost ~]# ansible host5 -m ping
[WARNING]: Could not match supplied host pattern, ignoring: host5
[WARNING]: No hosts matched, nothing to do

注意:ping和ssh的区别,这是两个程序
ping:网络层ICMP网际消息管理协议
ssh:应用层安全登录协议
结论:ansible的ping,是一个模块探测ssh程序是否连接,不是ICMP协议,和平时的ping不一样,所以在ansilbe里,能ping通目标主机,不一定能够进行ssh连接。

五.Inventory-主机清单

路径:/etc/ansible/hosts
含义:清查;存货清单;财产目录;主机清单

增加主机组

1.再配置文件里增加主机组

[root@localhost ~]# vim /etc/ansible/hosts
[webserver]
host1
host2
host3
host4`
添加[webserver],这四个主机都会被分到[webserver]这个组里

2.测试主机组:这里主机组测试是成功的,但是测试连通性结果2,3,4号主机是失败,只有1号主机测试成功,是因为只有1号主机做了免密,我这里只是测试一下主机组是否添加成功,显然webserver主机组是添加成功的。

[root@localhost ~]# ansible webserver -m ping -o 
host2 | UNREACHABLE!: Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

host3 | UNREACHABLE!: Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

host4 | UNREACHABLE!: Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

host1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}

增加用户名和密码

1.第一种写法:主机的用户名和密码不一样只能用第一种

[root@localhost ~]# vim /etc/ansible/hosts 
[webserver]
host1  ansible_ssh_user='root'  ansible_ssh_pass='666666'
host2  ansible_ssh_user='root'  ansible_ssh_pass='666666'
host3  ansible_ssh_user='root'  ansible_ssh_pass='666666'
host4  ansible_ssh_user='root'  ansible_ssh_pass='666666'

第二种写法:我的四个主机用户名密码一样可以这么写。

[root@localhost ~]# vim /etc/ansible/hosts 
[webserver]
host[1:4]  ansible_ssh_user='root'  ansible_ssh_pass='666666'

2.开始测试webserver主机组,结果都成功了。

[root@localhost ~]# ansible webserver -m ping -o 
host2 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
host1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
host3 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
host4 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}

增加端口

端口范围最好在1024-65535避免冲突

1.给4号主机添加2222端口,实验时必须将系统的安全机制关闭,不然修改端口后,shhd服务无法重启

[root@192 ~]# vim /etc/ssh/sshd_config 
17 #Port 22
取消注释,添加端口2222,保存退出
17 Port 2222

2.重启sshd服务

[root@192 ~]# systemctl  restart sshd

3.查看端口

[root@192 ~]# ss -anp | grep sshd
u_dgr  UNCONN     0      0         * 17292                 * 9190                users:(("sshd",pid=1253,fd=4))
u_str  ESTAB      0      0         * 19987                 * 21772               users:(("sshd",pid=1288,fd=2),("sshd",pid=1288,fd=1))
tcp    LISTEN     0      128       *:**2222**                  *:*                   users:(("sshd",pid=1288,fd=3))
tcp    ESTAB      0      228    192.168.200.149:22                 192.168.200.1:56484               users:(("sshd",pid=1253,fd=3))
tcp    LISTEN     0      128      :::**2222**                 :::*                  `

4.测试4号主机的连通性,此时失败的,因为端口号已经更改

[root@localhost ~]# ansible host4 -m ping -o 
host4 | UNREACHABLE!: Failed to connect to the host via ssh: ssh: connect to host host4 port 22: Connection refused

5.在主机清单配置文件中添加修改后的端口号

[root@localhost ~]# vim /etc/ansible/hosts 
[webserver]
host[1:3]  ansible_ssh_user='root'  ansible_ssh_pass='666666'
host4  ansible_ssh_user='root'  ansible_ssh_pass='666666' **ansible_ssh_port='2222'**

6.再次访问4号主机成功,切记关闭系统的安全机制,不然失败。

[root@localhost ~]# ansible host4 -m ping -o 
host4 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}

组:变量

1.作用:ansible内部变量可以简化主机清单的设置

常用变量:

参数 用途 例子
ansible_ssh_host 定义host ssh 地址 ansible_ssh_host=‘192.168.200.88’
ansible_ssh_port 定义host ssh端口 ansible_ssh_port=‘2222’
ansible_ssh_user 定义host ssh认证用户 ansible_ssh_user=‘user’
ansible_ssh_pass 定义host ssh认证密码 ansible_ssh_pass=‘pass’

2.修改主机清单配置文件设置变量,我4号主机端口和其他三个不一样,这里得单独写出来,修改完成保存退出

[root@localhost ~]# vim /etc/ansible/hosts
[webserver]
host[1:3]  
host4    ansible_ssh_port='2222'
[webserver:vars]
ansible_ssh_user='root'
ansible_ssh_pass='666666'

3.测试webserver组连通性

[root@localhost ~]# ansible webserver -m ping -o 
host2 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
host4 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
host1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
host3 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}

子分组

1.含义:将不同的分组进行组合

2.配置主机清单文件,添加子分组,这里我提前把4号主机的端口号改为22,和其他三台主机一样

[root@localhost ~]# vim /etc/ansible/hosts 
[apache]
host[1:2]
[nginx]
host[3:4]`

[webserver:children]
apache
nginx
变量:
[webserver:vars]
ansible_ssh_user='root'
ansible_ssh_pass='666666

这里webserver是一个父亲,下面还有儿子,就是子分组:apache;nginx,ansible控制webserver就是控制他的组成员

3.测试设置的组连通性,直接调用总的组webserver,测试结果成功,设置子分组成功

[root@localhost ~]# ansible webserver -m ping -o 
host2 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
host1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
host4 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
host3 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}

自定义主机列表

1.新建文件,添加主机列表

[root@192 ~]# vim hostlist
[dockers]
host1
host2
[dockers:vars]
ansible_ssh_user='root'
ansible_ssh_pass='666666'

2.链接外部主机清单进行测试,这里dockers是个组

[root@192 ~]# ansible **-i hostlist dockers** -m ping -o
host2 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
host1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}

参数解释:
-i:链接外部主机清单,后面跟需要链接的文件绝对路径,主机名

六.Ad-Hoc-点对点模式

简介

在ansible中是指需要快速执行的单条命令,并且不需要保存的命令,对于复杂的命令则为playbook

复制模块copy

1.查看copy模块的用法说明

[root@192 ~]# ansible -doc copy 

2.案例1:在生产环境中,利用ansible将文件快速复制到多台目标主机

[root@192 ~]# ansible webserver -m copy -a 'src=/etc/hosts  dest=/tmp/1.txt owner=root group=bin  mode=700'

host2 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“checksum”: “cbea3fdf3497786aaa2a4bdb30d74aaa2980131d”,
“dest”: “/tmp/1.txt”,
“gid”: 1,
“group”: “bin”,
“md5sum”: “9150cfc9c1c262252007daa873fe64f9”,
“mode”: “0700”,
“owner”: “root”,
“size”: 270,
“src”: “/root/.ansible/tmp/ansible-tmp-1668510228.51-15209-275898371286556/source”,
“state”: “file”,
“uid”: 0
}
host1 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“checksum”: “cbea3fdf3497786aaa2a4bdb30d74aaa2980131d”,
“dest”: “/tmp/1.txt”,
“gid”: 1,
“group”: “bin”,
“md5sum”: “9150cfc9c1c262252007daa873fe64f9”,
“mode”: “0700”,
“owner”: “root”,
“size”: 270,
“src”: “/root/.ansible/tmp/ansible-tmp-1668510228.48-15207-115863170173259/source”,
“state”: “file”,
“uid”: 0
}
host3 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“checksum”: “cbea3fdf3497786aaa2a4bdb30d74aaa2980131d”,
“dest”: “/tmp/1.txt”,
“gid”: 1,
“group”: “bin”,
“md5sum”: “9150cfc9c1c262252007daa873fe64f9”,
“mode”: “0700”,
“owner”: “root”,
“size”: 270,
“src”: “/root/.ansible/tmp/ansible-tmp-1668510228.52-15211-118937029871613/source”,
“state”: “file”,
“uid”: 0
}
host4 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“checksum”: “cbea3fdf3497786aaa2a4bdb30d74aaa2980131d”,
“dest”: “/tmp/1.txt”,
“gid”: 1,
“group”: “bin”,
“md5sum”: “9150cfc9c1c262252007daa873fe64f9”,
“mode”: “0700”,
“owner”: “root”,
“size”: 270,
“src”: “/root/.ansible/tmp/ansible-tmp-1668510228.53-15213-38106504039786/source”,
“state”: “file”,
“uid”: 0
}

这里显示黄色正常,结果成功,可以找一台目标主机查看文件复制是否成功。

参数解释:
-m:调用copy模块
-a:attribute属性
src:source源头;资源,被复制到远程主机的本地文件。可以是绝对路径,也可以是相对路径。如果路径是一个目录,则会递归复制,用法类似于"rsync"
dest:destnation目的地,这里指的是目标主机接收文件的位置
owner:指定文件拷贝到远程主机后的属主,但是远程主机上必须有对应的用户,否则会报错
group:指定文件拷贝到远程主机后的属组,但是远程主机上必须有对应的组,否则会报错
mode:指定文件拷贝到远程主机后的权限,如果你想将权限设置为”rw-r–r–“,则可以使用mode=0644表示,如果你想要在user对应的权限位上添加执行权限,则可以使用mode=u+x表示。

3.案例2:将/etc/hosts文件追加内容,利用ansible将文件快速复制到多台目标主机

[root@192 ~]# echo "welcome"  >> /etc/hosts
[root@192 ~]# ansible webserver -m copy -a 'src=/etc/hosts  dest=/tmp/1.txt owner=root group=bin  mode=700 backup=yes'

host1 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“backup_file”: “/tmp/1.txt.2367.2022-11-15@19:45:39~”,
“changed”: true,
“checksum”: “2dfe3f1859cc3bb5f215f3856f0d0ddf955cf624”,
“dest”: “/tmp/1.txt”,
“gid”: 1,
“group”: “bin”,
“md5sum”: “e97a57516cb4e1610caa25df55bbbadf”,
“mode”: “0700”,
“owner”: “root”,
“size”: 278,
“src”: “/root/.ansible/tmp/ansible-tmp-1668512739.35-15533-165179004027355/source”,
“state”: “file”,
“uid”: 0
}
host2 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“backup_file”: “/tmp/1.txt.2305.2022-11-15@19:45:39~”,
“changed”: true,
“checksum”: “2dfe3f1859cc3bb5f215f3856f0d0ddf955cf624”,
“dest”: “/tmp/1.txt”,
“gid”: 1,
“group”: “bin”,
“md5sum”: “e97a57516cb4e1610caa25df55bbbadf”,
“mode”: “0700”,
“owner”: “root”,
“size”: 278,
“src”: “/root/.ansible/tmp/ansible-tmp-1668512739.37-15535-5375277262467/source”,
“state”: “file”,
“uid”: 0
}
host4 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“backup_file”: “/tmp/1.txt.2460.2022-11-15@19:45:39~”,
“changed”: true,
“checksum”: “2dfe3f1859cc3bb5f215f3856f0d0ddf955cf624”,
“dest”: “/tmp/1.txt”,
“gid”: 1,
“group”: “bin”,
“md5sum”: “e97a57516cb4e1610caa25df55bbbadf”,
“mode”: “0700”,
“owner”: “root”,
“size”: 278,
“src”: “/root/.ansible/tmp/ansible-tmp-1668512739.36-15539-63576607620178/source”,
“state”: “file”,
“uid”: 0
}
host3 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“backup_file”: “/tmp/1.txt.2244.2022-11-15@19:45:39~”,
“changed”: true,
“checksum”: “2dfe3f1859cc3bb5f215f3856f0d0ddf955cf624”,
“dest”: “/tmp/1.txt”,
“gid”: 1,
“group”: “bin”,
“md5sum”: “e97a57516cb4e1610caa25df55bbbadf”,
“mode”: “0700”,
“owner”: “root”,
“size”: 278,
“src”: “/root/.ansible/tmp/ansible-tmp-1668512739.37-15537-219448169019574/source”,
“state”: “file”,
“uid”: 0
}


随机查看一台目标主机是否复制成功

[root@192 ~]# ll -d /tmp/*
-rwx------ 1 root bin 278 11月 15 19:45 /tmp/1.txt
-rwx------ 1 root bin 270 11月 15 19:03 /tmp/1.txt.2367.2022-11-15@19:45:39~
参数解释:
backup:当文件内容发生改变后,在覆盖之前把源文件备份,备份文件包含时间信息

**总结**:由于本次复制前,在文件内追加了新的内容,复制时会覆盖目标主机的源文件,这里使用backup参数,在覆盖前把源文件备份加上时间戳,然后进行复制,如果不使用backup参数,目标主机的源文件会被覆盖。

4.错误示范:这里backup后没有写yes/no,报错红色

[root@192 ~]# ansible webserver -m copy -a 'src=/etc/hosts  dest=/tmp/1.txt owner=root group=bin  mode=700 backup'

ERROR! this task ‘copy’ has extra params, which is only allowed in the following modules: ansible.builtin.raw, ansible.legacy.add_host, ansible.builtin.meta, ansible.legacy.include, ansible.legacy.import_role, script, ansible.legacy.raw, group_by, ansible.builtin.shell, ansible.legacy.win_command, include, shell, include_vars, ansible.builtin.import_tasks, add_host, ansible.builtin.include_vars, ansible.legacy.include_role, ansible.builtin.include_role, ansible.legacy.include_vars, ansible.legacy.win_shell, ansible.legacy.group_by, import_tasks, ansible.builtin.set_fact, ansible.builtin.command, ansible.builtin.include_tasks, include_tasks, ansible.builtin.script, ansible.builtin.include, raw, meta, ansible.legacy.set_fact, ansible.builtin.add_host, ansible.legacy.script, ansible.legacy.import_tasks, win_command, ansible.builtin.win_shell, include_role, win_shell, set_fact, ansible.legacy.shell, ansible.legacy.command, import_role, ansible.legacy.meta, ansible.builtin.import_role, ansible.legacy.include_tasks, ansible.builtin.group_by, ansible.builtin.win_command, command

用户模块user

1.查看用户模块的帮助

[root@ansible ~]# ansible-doc user 

2.利用ansible在4台目标主机创建用户

[root@ansible ~]# ansible webserver -m user -a 'name=qq state=present'
参数解释:
-m:调用模块 user
name:用户名
state:状态
pretent:创建

结果显示成功
host2 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“comment”: “”,
“create_home”: true,
“group”: 1000,
“home”: “/home/qq”,
“name”: “qq”,
“shell”: “/bin/bash”,
“state”: “present”,
“system”: false,
“uid”: 1000
}
host1 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“comment”: “”,
“create_home”: true,
“group”: 1000,
“home”: “/home/qq”,
“name”: “qq”,
“shell”: “/bin/bash”,
“state”: “present”,
“system”: false,
“uid”: 1000
}
host3 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“comment”: “”,
“create_home”: true,
“group”: 1000,
“home”: “/home/qq”,
“name”: “qq”,
“shell”: “/bin/bash”,
“state”: “present”,
“system”: false,
“uid”: 1000
}
host4 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“comment”: “”,
“create_home”: true,
“group”: 1000,
“home”: “/home/qq”,
“name”: “qq”,
“shell”: “/bin/bash”,
“state”: “present”,
“system”: false,
“uid”: 1000
}

3.给创建的用户生成加密密码

3.1生成密码

[root@ansible ~]# echo "512050951" | openssl passwd -1 -stdin
$1$7DoPbbqi$f6rUGYrXQ8J0/C40QWMih0

参数解释:
openssl:用来加密的命令,这里把管道符传递过来的密码进行加密
passwd -1:加密等级
-stdin:标准输入接收,不进行交互

3.2通过ansible给用户统一修改密码

[root@ansible ~]# ansible webserver -m user -a 'name=qq password=$1$7DoPbbqi$f6rUGYrXQ8J0/C40QWMih0'

结果显示成功,可以去4台主机上登录qq用户再次验证,我已经验证过了。
host2 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“append”: false,
“changed”: true,
“comment”: “”,
“group”: 1000,
“home”: “/home/qq”,
“move_home”: false,
“name”: “qq”,
“password”: “NOT_LOGGING_PASSWORD”,
“shell”: “/bin/bash”,
“state”: “present”,
“uid”: 1000
}
host4 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“append”: false,
“changed”: true,
“comment”: “”,
“group”: 1000,
“home”: “/home/qq”,
“move_home”: false,
“name”: “qq”,
“password”: “NOT_LOGGING_PASSWORD”,
“shell”: “/bin/bash”,
“state”: “present”,
“uid”: 1000
}
host1 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“append”: false,
“changed”: true,
“comment”: “”,
“group”: 1000,
“home”: “/home/qq”,
“move_home”: false,
“name”: “qq”,
“password”: “NOT_LOGGING_PASSWORD”,
“shell”: “/bin/bash”,
“state”: “present”,
“uid”: 1000
}
host3 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“append”: false,
“changed”: true,
“comment”: “”,
“group”: 1000,
“home”: “/home/qq”,
“move_home”: false,
“name”: “qq”,
“password”: “NOT_LOGGING_PASSWORD”,
“shell”: “/bin/bash”,
“state”: “present”,
“uid”: 1000
}

4.修改用户的登录shell

4.1查看4台主机创建qq用户的登录shell

[root@localhost ~]# tail -1 /etc/passwd
qq:x:1000:1000::/home/qq:/bin/bash
这里4个主机qq用户的登录shell都是/bin/bash,我其他三个就不写了。

4.2修改4台主机的用户qq登录sell

[root@ansible ~]# ansible webserver -m user -a 'name=qq shell=/sbin/nolgin append=yes'

参数解释:
append:追加,修改的意思

结果显示成功
host2 | SUCCESS => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“append”: true,
“changed”: false,
“comment”: “”,
“group”: 1000,
“home”: “/home/qq”,
“move_home”: false,
“name”: “qq”,
“shell”: “/sbin/nolgin”,
“state”: “present”,
“uid”: 1000
}
host1 | SUCCESS => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“append”: true,
“changed”: false,
“comment”: “”,
“group”: 1000,
“home”: “/home/qq”,
“move_home”: false,
“name”: “qq”,
“shell”: “/sbin/nolgin”,
“state”: “present”,
“uid”: 1000
}
host4 | SUCCESS => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“append”: true,
“changed”: false,
“comment”: “”,
“group”: 1000,
“home”: “/home/qq”,
“move_home”: false,
“name”: “qq”,
“shell”: “/sbin/nolgin”,
“state”: “present”,
“uid”: 1000
}
host3 | SUCCESS => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“append”: true,
“changed”: false,
“comment”: “”,
“group”: 1000,
“home”: “/home/qq”,
“move_home”: false,
“name”: “qq”,
“shell”: “/sbin/nolgin”,
“state”: “present”,
“uid”: 1000
}

4.3查看4台主机用户qq的登录shell,结果显示/sbin/nologin,修改成功,省略其他三个主机。

[root@localhost ~]# tail -1 /etc/passwd
qq:x:1000:1000::/home/qq:/sbin/nolgin

5.删除4 台主机的qq用户

5.1删除用户

[root@ansible ~]# ansible webserver -m user -a 'name=qq state=absent'

参数解释:
absent:删除

结果显示成功,可以利用id 命令再去4台主机查询用户qq是否存在
host2 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“force”: false,
“name”: “qq”,
“remove”: false,
“state”: “absent”
}
host3 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“force”: false,
“name”: “qq”,
“remove”: false,
“state”: “absent”
}
host1 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“force”: false,
“name”: “qq”,
“remove”: false,
“state”: “absent”
}
host4 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“force”: false,
“name”: “qq”,
“remove”: false,
“state”: “absent”
}

软件包管理模块yum

1.查询软件包管理模块帮助

[root@ansible ~]# ansible-doc yum

2.升级所有包

[root@ansible ~]# ansible webserver -m yum -a 'name=* state=latest'
由于升级所有包时间太久,这里就不操作,例子就是这样

2.1利用ansible给4台目标主机安装apache

ansible webserver -m yum -a 'name=httpd state=latest'
这个安装时间很慢,请耐心等待
显示结果黄色成功,命令执行完后结果太长,这里我就省略了,

参数解释:
latest:如果软件不是最新版就更新

2.2在目标主机上查看一下,安装结果,省略其他三个主机的查看结果

[root@localhost ~]# yum list | grep -w httpd
httpd.x86_64                          2.4.6-97.el7.centos.5        @updates 
httpd-tools.x86_64                        2.4.6-97.el7.centos.5        @updates 
httpd-devel.x86_64                        2.4.6-97.el7.centos.5        updates  
httpd-manual.noarch                       2.4.6-97.el7.centos.5        updates  
keycloak-httpd-client-install.noarch      0.8-1.el7                    base     
python2-keycloak-httpd-client-install.noarch

2.3卸载软件

[root@ansible ~]# ansible webserver -m yum -a 'name=httpd state=absent'

参数解释:
absent:removed卸载软件

服务模块service

1.查看服务模块的帮助

[root@ansible ~]# ansible-doc service

2.利用ansible打开4台主机的httpd服务

[root@ansible ~]# ansible webserver -m service -a 'name=httpd state=started'
结果显示黄色成功,命令执行结果太长,这里省略。
可以去4台主机上查询httpd状态

3.利用ansible打开4台主机httpd服务的开机自启动

[root@ansible ~]# ansible webserver -m service -a 'name=httpd state=started  enabled=yes'
结果显示黄色成功,命令执行结果太长,这里省略。
可以去4台主机上查询httpd开机是否自启动

参数解释:
name:服务名
enabled:是否开机自启动  yes/no
state:接各种参数(started,stopped,restarted,reloaded)

文件模块file

1.查看文件模块的帮助

[root@ansible ~]# ansible-doc file

2.利用ansible在4台主机上创建文件

[root@ansible ~]# ansible webserver -m file -a 'path=/tmp/88.jpg mode=771 state=touch '

host2 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“dest”: “/tmp/88.jpg”,
“gid”: 0,
“group”: “root”,
“mode”: “0771”,
“owner”: “root”,
“size”: 0,
“state”: “file”,
“uid”: 0
}


命令执行结果显示黄色成功,我这里值提取一个主机的执行结果z作为示例,其他三个省略了

参数解释:
owner:定义文件/目录的属主
group:定义文件/目录的属组
mode:定义文件/目录的权限
path:必选项,定义文件/目录的路径
recurse:递归的设置文件的属性,只对目录有效
src:链接(软/硬)文件的源文件路径,只应用于state=link的情况
dest:链接文件的路径,只应用于state=link的情况
state:各种选项如下
        directory 如果目录不存在,创建目录
        file 文件不存在,则不会被创建,存在则返回文件的信息 (常用于检查文件是否存在)
        link 创建软链接
        hard 创建硬链接
        touch 如果文件不存在,则会创建一个新的文件,如果文件或目录(已存在,则更新其最后修改时间)
         absent 删除目录、文件或者取消链接文件

3.利用ansible在4台主机上创建目录

[root@ansible ~]# ansible webserver -m file -a 'path=/tmp/88 mode=770 state=directory '

host2 | CHANGED => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: true,
“gid”: 0,
“group”: “root”,
“mode”: “0770”,
“owner”: “root”,
“path”: “/tmp/88”,
“size”: 6,
“state”: “directory”,
“uid”: 0
}

命令执行结果显示黄色成功,我这里值提取一个主机的执行结果z作为示例,其他三个省略了

收集模块setup

1.查看收集的帮助

[root@ansible ~]# ansible-doc setup

2.利用ansible查看4台主机的信息

[root@ansible ~]# ansible host1 -m setup
结果显示绿色收集成功,由于主机信息太多太多了,我这里省略了

2.利用ansible查看1台主机的信息,过滤出ip地址

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

参数解释:
filter:过滤

host1 | SUCCESS => {
“ansible_facts”: {
“ansible_all_ipv4_addresses”: [
“192.168.200.146”
],
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: false
}

shell模块

1.查看shell模块的帮助

[root@ansible ~]# ansible-doc shell

2.利用ansible调用4台主机的主机名

[root@ansible ~]# ansible webserver -m shell -a 'hostname' -o -f 2

参数解释:
-o:简洁执行
-f:指定线程数,让对方的主机开动几个进程来完成你的事务,当高并发的时候可以使用(这里可用可不用)

host2 | CHANGED | rc=0 | (stdout) 192.168.200.147
host3 | CHANGED | rc=0 | (stdout) 192.168.200.148
host4 | CHANGED | rc=0 | (stdout) 192.168.200.149
host1 | CHANGED | rc=0 | (stdout) 192.168.200.146

2.1yum安装程序

[root@ansible ~]# ansible webserver -m shell -a 'yum -y install vsftpd' -o

2.2查看磁盘挂载

[root@ansible ~]# ansible webserver -m shell -a 'df -hT' -o

2.3创建用户,删除用户

[root@ansible ~]# ansible webserver -m shell -a 'useradd aaa' -o
[root@ansible ~]# ansible webserver -m shell -a 'userdel aaa' -o

2.4创建文件

[root@ansible ~]# ansible webserver -m shell -a 'touch /tmp/test' -o

总结:通过这几个示例,已经能掌握shell模块的用法,shell模块可以执行shell的内置命令和特性如管道等

七.YAML非标记语言

概述

YAML(Yet Another Markup Language)不是标记语言,它是适用于所有编程语言的人类友好数据序列化标准

2.语法

列表型
字典型

示例:利用YAML编写一个简单的剧本,完成web的部署,配置,启动的全过程

3.1准备工作:

将之前目标主机上安装的httpd服务卸载,不然后面测试会报错.
[root@ansible ~]# ansible webserver -m yum -a 'name=httpd state=removed' -o
[root@ansible ~]# ansible webserver -m yum -a 'name=httpd-tools state=removed' -o

3.2在ansible服务器上操作

yum安装httpd服务
[root@ansible ~]# yum -y install httpd

创建目录
[root@ansible /]# mkdir apache

将httpd主配置文件拷贝到创建的目录里
[root@ansible /]# cp -rf /etc/httpd/conf/httpd.conf  /apache/

查看监听端口号,默认是80
[root@ansible /]# grep '^Listen' /apache/httpd.conf 
Listen 80

我们将监听端口号改为8080
[root@ansible /]# vim /apache/httpd.conf
Listen 8080
[root@ansible /]# grep '^Listen' /apache/httpd.conf 
Listen 8080

3.3准备剧本

进入创建的目录,编辑配置文件
[root@ansible apache]# cd /apache
[root@ansible apache]# vim apache.yaml
#针对哪个主机来执行剧本,主机名和主机组
- hosts: webserver
#任务,以列表形式来写
  tasks:
  - name: install apache packges
    yum: name=httpd state=present
  - name: copy apache conf
    copy: src=./httpd.conf dest=/etc/httpd/conf/httpd.conf
  - name: ensure apache is runing
    service: name=httpd state=started enabled=yes

注意:配置文件该空格要空格,该对齐的要对齐,严格按要求书写,不然会报错

3.4检查剧本配置文件有没有语法错误

[root@ansible apache]# ansible-playbook apache.yaml --syntax-check

playbook: apache.yaml

3.5列出任务

[root@ansible apache]# ansible-playbook apache.yaml --list-tasks

playbook: apache.yaml

  play #1 (webserver): webserver	TAGS: []
    tasks:
      install apache packges	TAGS: []
      copy apache conf	TAGS: []
      ensure apache is runing	TAGS: []

3.6列出主机

[root@ansible apache]# ansible-playbook apache.yaml --list-hosts

playbook: apache.yaml

  play #1 (webserver): webserver	TAGS: []
    pattern: [u'webserver']
    hosts (4):
      host4
      host3
      host2
      host1

3.7运行剧本

[root@ansible apache]# ansible-playbook apache.yaml 

PLAY [webserver] ***************************************************************

TASK [Gathering Facts] *********************************************************
ok: [host1]
ok: [host2]
ok: [host3]
ok: [host4]

TASK [install apache packges] **************************************************
changed: [host2]
changed: [host1]
changed: [host4]
changed: [host3]

TASK [copy apache conf] ********************************************************
changed: [host2]
changed: [host4]
changed: [host3]
changed: [host1]

TASK [ensure apache is runing] *************************************************
changed: [host3]
changed: [host1]
changed: [host4]
changed: [host2]

PLAY RECAP *********************************************************************
host1                      : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
host2                      : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
host3                      : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
host4                      : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

剧本运行结果显示成功,如果报错看一下是哪个任务报错,回过头挨个检查

3.8打开浏览器查看web页面

这里测试4台主机的web页面,端口号我们改为8080,要写上
http://192.168.200.146:8080
http://192.168.200.147:8080
http://192.168.200.148:8080
http://192.168.200.149:8080

4.请思考,如果/apache/httpd.conf配置文件发生变化,再次执行剧本是否会成功?

这里修改端口号看一下效果,将端口号改为9000
[root@ansible apache]# vim httpd.conf 
Listen 9000

再次运行剧本,这里运行剧本是成功的,结果省略。
[root@ansible apache]# ansible-playbook apache.yaml 

我们在剧本的配置文件写的是拷贝httpd.conf文件,所以当配置文件内容发生变化时,再次执行剧本是成功的,会覆盖掉之前的文件

但是这里有一个问题,运行剧本成功了,我四台主机的端口号仍然没有改变,查询4台主机端口号,结果还是原来的8080,这是为什么呢?

[root@192 ~]# ss -anp | grep httpd
tcp    LISTEN     0      128      :::8080 

是因为我在编辑剧本的配置文件时,这里写的是started,每次执行剧本都是打开htppd服务,并没有重启服务,所以刚才修改的端口号没有生效,但是还不能将started改为restarted,这样会丢失用户。那该怎么解决这个问题呢,往下看,需要用到handlers触发器。

service: name=httpd state=started enabled=yes

5.handlers触发器

5.1编辑剧本配置文件

[root@ansible apache]# vim apache.yaml 

#针对哪个主机来执行剧本,主机名和主机组
- hosts: webserver
  tasks:
  - name: install apache packges
    yum: name=httpd state=present
  - name: copy apache conf
    copy: src=./httpd.conf dest=/etc/httpd/conf/httpd.conf
#通知的意思,当这个模块产生改变时,通知handlers执行,所以名字要和handlers名字一样    
    notify: restart  apache service
  - name: ensure apache is runing
    service: name=httpd state=started enabled=yes
#handlers和tasks同级别,当触发时才执行
  handlers:
  - name: restart apache service
    service: name=httpd state=restarted
这里格式写对,一个字都不能错。

5.2运行剧本

先将修改端口号为9009,在运行剧本,不修改端口号运行剧本结果没变化,因为handlers是当有模块产生变化时触发。
[root@ansible apache]# ansible-playbook apache.yaml

查看4台主机端口号,端口号和我们修改的一样都是9009,剧本运行成功

[root@192 ~]# ss -anp | grep httpd
tcp    LISTEN     0      128      :::9009    

八.Role-角色扮演

简介

roles是在ansible中,playbooks的目录组织结构,将代码或文件进行模块化,成为roles的文件目录的组织结构,易读,代码可重用,层次清晰

目标

通过role远程部署nginx并配置

目录结构

1.目录结构是什么?

创建目录和文件
[root@ansible ~]# mkdir abc
[root@ansible ~]# mkdir abc/def
[root@ansible ~]# mkdir abc/hig
[root@ansible ~]# touch abc/def/111
[root@ansible ~]# touch abc/hig/222

通过tree命令查看目录结构,这就是目录结构,需要yum安装tree,3目录,2文件

[root@ansible ~]# tree abc
abc
├── def
│   └── 111
└── hig
    └── 222

1.2准备目录结构

在ansible服务器创建目录,名字是固定的
[root@ansible ~]# mkdir        roles/nginx/{files,handlers,tasks,templates,vars}  -p

[root@ansible ~]# touch roles/site.yaml roles/nginx/{handlers,tasks,vars}/main.yaml

准备nginx页面内容
[root@ansible ~]# echo "1234"  > roles/nginx/files/index.html

安装nginx并将配置文件拷贝到指定目录下,并改名
[root@ansible ~]# yum -y install nginx && cp /etc/nginx/nginx.conf  roles/nginx/templates/nginx.conf.j2

查看目录结构,准备完成。
[root@ansible ~]# tree roles/
roles/
├── nginx
│   ├── files
│   │   └── index.html
│   ├── handlers
│   │   └── main.yaml
│   ├── tasks
│   │   └── main.yaml
│   ├── templates
│   │   └── nginx.conf2
│   └── vars
│       └── main.yaml
└── site.yaml

编写任务

[root@ansible ~]# vim roles/nginx/tasks/main.yaml 
---
- name: install epel-release packge
  yum: name=epel-release state=latest
- name: install nginx packge
  yum: name=nginx state=latest
- name: copy index.html
  copy: src=index.html dest=/usr/share/nginx/html/index.html
- name: copy nginx.conf template
  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  notify: restart nginx 
- name: make sure nginx service running
  service: name=nginx state=started enabled=yes
  格式要对,一个字都不能错

准备配置文件,jinjia模板文件

1.配置文件是以.j2结尾的文件,在ansible中叫jinjia模板,这就是为什么前面备份文件时要以.j2结尾,就是为了这里使用变量

jinjia模板是在ansible中建立的一类模板文件,通常以.j2结尾标识。模板的内容含有多个变量,使原本固定的某个文件配置,通过参数的改变,变得可以复用,提高了使用效率。
可以使用ansible已有变量,也可以使用自定义变量

2.修改配置文件

[root@ansible ~]# vim roles/nginx/templates/nginx.conf.j2 
6 worker_processes auto;
把第6行的auto改为变量,查看cpu内核数,这个变量是ansible中有的变量
6 worker_processes {{ ansible_processor_cores }};

14     worker_connections 1024;
将14行的1024改为变量,这个变量自定义的,下面就去自定义一下
14     worker_connections {{ worker_connections }};

编写变量

1.变量的配置文件在roles/nginx/vars/main.yaml,上面我创建好的,可以把各种自定义变量写进去
2.开始编写变量,把刚才jinjia模板文件写的自定义变量,在这里定义一下

[root@ansible ~]# vim roles/nginx/vars/main.yaml 
worker_connections: 10240

编写处理程序

1.刚才编写任务时nofity没有写handlers在这里分开写

[root@ansible ~]# vim roles/nginx/handlers/main.yaml 

---
- name: restart nginx
  service: name=nginx state=restarted

编写剧本

让webserver主机组执行,任务就是nginx目录下的所有任务

[root@ansible ~]# vim roles/site.yaml 

- hosts: webserver
  roles:
  - nginx

运行剧本

1.检查语法

[root@ansible roles]# ansible-playbook site.yaml --syntax-check

playbook: site.yaml

最开始检查的时候发现语法报错,编写任务的时候格式不对,这里要注意写任务时一个字都不能错,现在是没问题的,接下来可以运行剧本

1.2开始运行剧本

注意:apache和nginx有冲突,之前的实验已经我把apache的端口改了,如果端口没有改把apache服务停止,再去运行剧本。

[root@ansible roles]# ansible-playbook site.yaml 

PLAY [webserver] ***************************************************************

TASK [Gathering Facts] *********************************************************
ok: [host2]
ok: [host4]
ok: [host3]
ok: [host1]

TASK [nginx : install epel-release packge] *************************************
changed: [host1]
changed: [host2]
changed: [host4]
changed: [host3]

TASK [install nginx packge] ****************************************************
changed: [host3]
changed: [host4]
changed: [host1]
changed: [host2]

TASK [nginx : copy index.html] *************************************************
changed: [host2]
changed: [host1]
changed: [host4]
changed: [host3]

TASK [copy nginx.conf template] ************************************************
changed: [host2]
changed: [host1]
changed: [host3]
changed: [host4]

TASK [make sure nginx service running] *****************************************
changed: [host3]
changed: [host1]
changed: [host2]
changed: [host4]

RUNNING HANDLER [restart nginx] ************************************************
changed: [host2]
changed: [host1]
changed: [host3]
changed: [host4]

PLAY RECAP *********************************************************************
host1                      : ok=7    changed=6    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
host2                      : ok=7    changed=6    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
host3                      : ok=7    changed=6    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
host4                      : ok=7    changed=6    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

结果显示成功,剧本运行完成

1.3在网页查看nginx提供的页面,显示1234,证明我这个实验已经完成并且全部成功

192.168.200.146
192.168.200.147
192.168.200.148

你可能感兴趣的:(运维,ansible,自动化)