[关闭]
@xushengkai 2023-02-22T05:35:45.000000Z 字数 32831 阅读 430

Ansible自动化运维实战

自动化运维

一.Ansible简介

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

二.工作原理

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

三.install部署

环境:准备五台其全新centos 7虚拟机,一台为ansible,四台为主机,配置域名解析

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

1.添加

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

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

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

3.install ansible,安装ansible

  1. [root@localhost ~]# yum -y install epel-release
  2. [root@localhost ~]# yum -y install ansible
  3. #检查yum是否安装成功
  4. [root@localhost ~]# rpm -qc ansible
  5. /etc/ansible/ansible.cfg
  6. /etc/ansible/hosts

2.ssh-key(可选)

1.生成密钥

  1. [root@localhost ~]# ssh-keygen
  2. Generating public/private rsa key pair.
  3. Enter file in which to save the key (/root/.ssh/id_rsa):
  4. Created directory '/root/.ssh'.
  5. Enter passphrase (empty for no passphrase):
  6. Enter same passphrase again:
  7. Your identification has been saved in /root/.ssh/id_rsa.
  8. Your public key has been saved in /root/.ssh/id_rsa.pub.
  9. The key fingerprint is:
  10. SHA256:U7JxuQLNdLymGGwCOkXD2dPJqppwtsgQUpTYxPI+c6s root@192.168.200.145
  11. The key's randomart image is:
  12. +---[RSA 2048]----+
  13. | O=+ o .... |
  14. |o X.o ++ ... |
  15. | * . +. = +. |
  16. |= . o +. *o. |
  17. |.+ . o oSo. |
  18. |o B . . .o |
  19. |+* = . |
  20. |+.. . |
  21. | E. |
  22. +----[SHA256]-----+

2.生成两个密钥文件

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

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

  1. [root@localhost ~]# ssh-copy-id 192.168.200.146
  2. /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
  3. The authenticity of host '192.168.200.146 (192.168.200.146)' can't be established.
  4. ECDSA key fingerprint is SHA256:zwhKo1o7AJBSuXoO9N/AP4GSbVQsKvfGQrgl8EqMbW8.
  5. ECDSA key fingerprint is MD5:8b:6c:0d:c0:80:6a:68:8c:e9:2d:5a:21:77:f2:b4:7c.
  6. Are you sure you want to continue connecting (yes/no)? **yes**
  7. /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
  8. /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
  9. root@192.168.200.146's password: **输入目标服务器的密码**
  10. Number of key(s) added:
  11. Now try logging into the machine, with: "ssh '192.168.200.146'"
  12. and check to make sure that only the key(s) you wanted were added.

三.ansible基础

1.定义主机清单

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

  1. [root@localhost ~]# vim /etc/ansible/hosts
  2. host1
  3. host2
  4. host3
  5. host4

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

  1. [root@localhost ~]# ansible localhost -m ping
  2. localhost | SUCCESS => {
  3. "changed": false,
  4. "ping": "pong"
  5. }`
  6. 参数说明:
  7. loaclhost 本机
  8. -m 调用模块
  9. ping 调用的模块

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

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

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

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

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

  1. [root@localhost ~]# ansible host2 -m ping -u root -k -o
  2. SSH password: **隐式输入2号主机的密码**
  3. host3 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
  4. >参数说明:
  5. -ussh连接时使用用户
  6. -k:交互式输入密码
  7. -o:简洁显示结果

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

  1. [root@localhost ~]# ansible host3 -m ping
  2. The authenticity of host 'host3 (192.168.200.148)' can't be established.
  3. ECDSA key fingerprint is SHA256:MoZUnS5n8wsVFKJiBxIbN1W9eaFUxwRs+U+uxQZ7sE0.
  4. ECDSA key fingerprint is MD5:7c:24:f1:36:44:7c:9d:96:24:b1:e6:9a:0c:23:fd:b2.
  5. Are you sure you want to continue connecting (yes/no)? **yes**
  6. host3 | UNREACHABLE! => {
  7. "changed": false,
  8. "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).",
  9. "unreachable": true
  10. }

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

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

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

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

重启ssh服务

  1. [root@localhost ~]# systemctl restart sshd`

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

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

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

  1. [root@localhost ~]# ansible host5 -m ping
  2. [WARNING]: Could not match supplied host pattern, ignoring: host5
  3. [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.增加主机组

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

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

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

  1. [root@localhost ~]# ansible webserver -m ping -o
  2. host2 | UNREACHABLE!: Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
  3. host3 | UNREACHABLE!: Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
  4. host4 | UNREACHABLE!: Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
  5. host1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}

2.增加用户名和密码

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

  1. [root@localhost ~]# vim /etc/ansible/hosts
  2. [webserver]
  3. host1 ansible_ssh_user='root' ansible_ssh_pass='666666'
  4. host2 ansible_ssh_user='root' ansible_ssh_pass='666666'
  5. host3 ansible_ssh_user='root' ansible_ssh_pass='666666'
  6. host4 ansible_ssh_user='root' ansible_ssh_pass='666666'

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

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

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

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

3.增加端口

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

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

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

2.重启sshd服务

  1. [root@192 ~]# systemctl restart sshd

3.查看端口

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

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

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

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

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

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

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

4.组:变量

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号主机端口和其他三个不一样,这里得单独写出来,修改完成保存退出

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

3.测试webserver组连通性

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

5.子分组

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

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

  1. [root@localhost ~]# vim /etc/ansible/hosts
  2. [apache]
  3. host[1:2]
  4. [nginx]
  5. host[3:4]`
  6. [webserver:children]
  7. apache
  8. nginx
  9. 变量:
  10. [webserver:vars]
  11. ansible_ssh_user='root'
  12. ansible_ssh_pass='666666
  13. 这里webserver是一个父亲,下面还有儿子,就是子分组:apache;nginx,ansible控制webserver就是控制他的组成员

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

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

6.自定义主机列表

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

  1. [root@192 ~]# vim hostlist
  2. [dockers]
  3. host1
  4. host2
  5. [dockers:vars]
  6. ansible_ssh_user='root'
  7. ansible_ssh_pass='666666'

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

  1. [root@192 ~]# ansible **-i hostlist dockers** -m ping -o
  2. host2 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
  3. host1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
  4. 参数解释:
  5. -i:链接外部主机清单,后面跟需要链接的文件绝对路径,主机名

五.Ad-Hoc-点对点模式

1.简介

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

2.复制模块copy

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

  1. [root@192 ~]# ansible -doc copy

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

  1. [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
}

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

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

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

  1. [root@192 ~]# echo "welcome" >> /etc/hosts
  2. [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
}


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

  1. [root@192 ~]# ll -d /tmp/*
  2. -rwx------ 1 root bin 278 11月 15 19:45 /tmp/1.txt
  3. -rwx------ 1 root bin 270 11月 15 19:03 /tmp/1.txt.2367.2022-11-15@19:45:39~
  1. 参数解释:
  2. backup:当文件内容发生改变后,在覆盖之前把源文件备份,备份文件包含时间信息
  3. **总结**:由于本次复制前,在文件内追加了新的内容,复制时会覆盖目标主机的源文件,这里使用backup参数,在覆盖前把源文件备份加上时间戳,然后进行复制,如果不使用backup参数,目标主机的源文件会被覆盖。

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

  1. [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

3.用户模块user

1.查看用户模块的帮助

  1. [root@ansible ~]# ansible-doc user

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

  1. [root@ansible ~]# ansible webserver -m user -a 'name=qq state=present'
  2. 参数解释:
  3. -m:调用模块 user
  4. name:用户名
  5. state:状态
  6. 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生成密码

  1. [root@ansible ~]# echo "512050951" | openssl passwd -1 -stdin
  2. $1$7DoPbbqi$f6rUGYrXQ8J0/C40QWMih0
  3. 参数解释:
  4. openssl:用来加密的命令,这里把管道符传递过来的密码进行加密
  5. passwd -1:加密等级
  6. -stdin:标准输入接收,不进行交互

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

  1. [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

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

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

  1. [root@ansible ~]# ansible webserver -m user -a 'name=qq shell=/sbin/nolgin append=yes'
  2. 参数解释:
  3. 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,修改成功,省略其他三个主机。

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

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

5.1删除用户

  1. [root@ansible ~]# ansible webserver -m user -a 'name=qq state=absent'
  2. 参数解释:
  3. 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"
}

4.软件包管理模块yum

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

  1. [root@ansible ~]# ansible-doc yum

2.升级所有包

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

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

  1. ansible webserver -m yum -a 'name=httpd state=latest'
  2. 这个安装时间很慢,请耐心等待
  3. 显示结果黄色成功,命令执行完后结果太长,这里我就省略了,
  4. 参数解释:
  5. latest:如果软件不是最新版就更新

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

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

2.3卸载软件

  1. [root@ansible ~]# ansible webserver -m yum -a 'name=httpd state=absent'
  2. 参数解释:
  3. absentremoved卸载软件

5.服务模块service

1.查看服务模块的帮助

  1. [root@ansible ~]# ansible-doc service

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

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

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

  1. [root@ansible ~]# ansible webserver -m service -a 'name=httpd state=started enabled=yes'
  2. 结果显示黄色成功,命令执行结果太长,这里省略。
  3. 可以去4台主机上查询httpd开机是否自启动
  4. 参数解释:
  5. name:服务名
  6. enabled:是否开机自启动 yes/no
  7. state:接各种参数(started,stopped,restarted,reloaded

6.文件模块file

1.查看文件模块的帮助

  1. [root@ansible ~]# ansible-doc file

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

  1. [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作为示例,其他三个省略了

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

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

  1. [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作为示例,其他三个省略了

7.收集模块setup

1.查看收集的帮助

  1. [root@ansible ~]# ansible-doc setup

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

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

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

  1. [root@ansible ~]# ansible host1 -m setup -a 'filter=ansible_all_ipv4_addresses'
  2. 参数解释:
  3. filter:过滤

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

8.shell模块

1.查看shell模块的帮助

  1. [root@ansible ~]# ansible-doc shell

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

  1. [root@ansible ~]# ansible webserver -m shell -a 'hostname' -o -f 2
  2. 参数解释:
  3. -o:简洁执行
  4. -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安装程序

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

2.2查看磁盘挂载

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

2.3创建用户,删除用户

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

2.4创建文件

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

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

六.YAML非标记语言

1.概述

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

2.语法

  1. 列表型
  2. 字典型

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

3.1准备工作:

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

3.2在ansible服务器上操作

  1. yum安装httpd服务
  2. [root@ansible ~]# yum -y install httpd
  3. 创建目录
  4. [root@ansible /]# mkdir apache
  5. httpd主配置文件拷贝到创建的目录里
  6. [root@ansible /]# cp -rf /etc/httpd/conf/httpd.conf /apache/
  7. 查看监听端口号,默认是80
  8. [root@ansible /]# grep '^Listen' /apache/httpd.conf
  9. Listen 80
  10. 我们将监听端口号改为8080
  11. [root@ansible /]# vim /apache/httpd.conf
  12. Listen 8080
  13. [root@ansible /]# grep '^Listen' /apache/httpd.conf
  14. Listen 8080

3.3准备剧本

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

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

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

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

3.5列出任务

  1. [root@ansible apache]# ansible-playbook apache.yaml --list-tasks
  2. playbook: apache.yaml
  3. play #1 (webserver): webserver TAGS: []
  4. tasks:
  5. install apache packges TAGS: []
  6. copy apache conf TAGS: []
  7. ensure apache is runing TAGS: []

3.6列出主机

  1. [root@ansible apache]# ansible-playbook apache.yaml --list-hosts
  2. playbook: apache.yaml
  3. play #1 (webserver): webserver TAGS: []
  4. pattern: [u'webserver']
  5. hosts (4):
  6. host4
  7. host3
  8. host2
  9. host1

3.7运行剧本

  1. [root@ansible apache]# ansible-playbook apache.yaml
  2. PLAY [webserver] ***************************************************************
  3. TASK [Gathering Facts] *********************************************************
  4. ok: [host1]
  5. ok: [host2]
  6. ok: [host3]
  7. ok: [host4]
  8. TASK [install apache packges] **************************************************
  9. changed: [host2]
  10. changed: [host1]
  11. changed: [host4]
  12. changed: [host3]
  13. TASK [copy apache conf] ********************************************************
  14. changed: [host2]
  15. changed: [host4]
  16. changed: [host3]
  17. changed: [host1]
  18. TASK [ensure apache is runing] *************************************************
  19. changed: [host3]
  20. changed: [host1]
  21. changed: [host4]
  22. changed: [host2]
  23. PLAY RECAP *********************************************************************
  24. host1 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
  25. host2 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
  26. host3 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
  27. host4 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

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

3.8打开浏览器查看web页面

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

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

  1. 这里修改端口号看一下效果,将端口号改为9000
  2. [root@ansible apache]# vim httpd.conf
  3. Listen 9000
  4. 再次运行剧本,这里运行剧本是成功的,结果省略。
  5. [root@ansible apache]# ansible-playbook apache.yaml

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

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

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

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

  1. service: name=httpd state=started enabled=yes

5.handlers触发器

5.1编辑剧本配置文件

  1. [root@ansible apache]# vim apache.yaml
  2. #针对哪个主机来执行剧本,主机名和主机组
  3. - hosts: webserver
  4. tasks:
  5. - name: install apache packges
  6. yum: name=httpd state=present
  7. - name: copy apache conf
  8. copy: src=./httpd.conf dest=/etc/httpd/conf/httpd.conf
  9. #通知的意思,当这个模块产生改变时,通知handlers执行,所以名字要和handlers名字一样
  10. notify: restart apache service
  11. - name: ensure apache is runing
  12. service: name=httpd state=started enabled=yes
  13. #handlers和tasks同级别,当触发时才执行
  14. handlers:
  15. - name: restart apache service
  16. service: name=httpd state=restarted
  17. 这里格式写对,一个字都不能错。

5.2运行剧本

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

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

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

七.Role-角色扮演

1.简介

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

2.目标

通过role远程部署nginx并配置

3.目录结构

1.目录结构是什么?

  1. 创建目录和文件
  2. [root@ansible ~]# mkdir abc
  3. [root@ansible ~]# mkdir abc/def
  4. [root@ansible ~]# mkdir abc/hig
  5. [root@ansible ~]# touch abc/def/111
  6. [root@ansible ~]# touch abc/hig/222

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

  1. [root@ansible ~]# tree abc
  2. abc
  3. ├── def
  4.    └── 111
  5. └── hig
  6. └── 222

1.2准备目录结构

  1. ansible服务器创建目录,名字是固定的
  2. [root@ansible ~]# mkdir roles/nginx/{files,handlers,tasks,templates,vars} -p
  3. [root@ansible ~]# touch roles/site.yaml roles/nginx/{handlers,tasks,vars}/main.yaml
  4. 准备nginx页面内容
  5. [root@ansible ~]# echo "1234" > roles/nginx/files/index.html
  6. 安装nginx并将配置文件拷贝到指定目录下,并改名
  7. [root@ansible ~]# yum -y install nginx && cp /etc/nginx/nginx.conf roles/nginx/templates/nginx.conf.j2
  8. 查看目录结构,准备完成。
  9. [root@ansible ~]# tree roles/
  10. roles/
  11. ├── nginx
  12.    ├── files
  13.       └── index.html
  14.    ├── handlers
  15.       └── main.yaml
  16.    ├── tasks
  17.       └── main.yaml
  18.    ├── templates
  19.       └── nginx.conf2
  20.    └── vars
  21.    └── main.yaml
  22. └── site.yaml

4.编写任务

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

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

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

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

2.修改配置文件

  1. [root@ansible ~]# vim roles/nginx/templates/nginx.conf.j2
  2. 6 worker_processes auto;
  3. 把第6行的auto改为变量,查看cpu内核数,这个变量是ansible中有的变量
  4. 6 worker_processes {{ ansible_processor_cores }};
  5. 14 worker_connections 1024;
  6. 14行的1024改为变量,这个变量自定义的,下面就去自定义一下
  7. 14 worker_connections {{ worker_connections }};

编写变量

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

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

编写处理程序

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

  1. [root@ansible ~]# vim roles/nginx/handlers/main.yaml
  2. ---
  3. - name: restart nginx
  4. service: name=nginx state=restarted

编写剧本

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

  1. [root@ansible ~]# vim roles/site.yaml
  2. - hosts: webserver
  3. roles:
  4. - nginx

运行剧本

1.检查语法

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

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

1.2开始运行剧本

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

  1. [root@ansible roles]# ansible-playbook site.yaml
  2. PLAY [webserver] ***************************************************************
  3. TASK [Gathering Facts] *********************************************************
  4. ok: [host2]
  5. ok: [host4]
  6. ok: [host3]
  7. ok: [host1]
  8. TASK [nginx : install epel-release packge] *************************************
  9. changed: [host1]
  10. changed: [host2]
  11. changed: [host4]
  12. changed: [host3]
  13. TASK [install nginx packge] ****************************************************
  14. changed: [host3]
  15. changed: [host4]
  16. changed: [host1]
  17. changed: [host2]
  18. TASK [nginx : copy index.html] *************************************************
  19. changed: [host2]
  20. changed: [host1]
  21. changed: [host4]
  22. changed: [host3]
  23. TASK [copy nginx.conf template] ************************************************
  24. changed: [host2]
  25. changed: [host1]
  26. changed: [host3]
  27. changed: [host4]
  28. TASK [make sure nginx service running] *****************************************
  29. changed: [host3]
  30. changed: [host1]
  31. changed: [host2]
  32. changed: [host4]
  33. RUNNING HANDLER [restart nginx] ************************************************
  34. changed: [host2]
  35. changed: [host1]
  36. changed: [host3]
  37. changed: [host4]
  38. PLAY RECAP *********************************************************************
  39. host1 : ok=7 changed=6 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
  40. host2 : ok=7 changed=6 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
  41. host3 : ok=7 changed=6 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
  42. host4 : ok=7 changed=6 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

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

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

  1. 192.168.200.146
  2. 192.168.200.147
  3. 192.168.200.148
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注