最全Ansible学习总结

文章目录

Ansible学习

一、ansible的概述

1.1 ansible简介

Ansible是一款为类Unix系统开发的自由开源的配置和自动化工具。

ansible用Python写成,类似于saltstack和Puppet,ansible有一个不同和优点是我们不需要在节点中安装任何客户端。

ansible使用SSH来和节点进行通信。Ansible基于 Python paramiko 开发,分布式,无需客户端,轻量级,配置语法使用 YMAL 及 Jinja2模板语言,更强的远程命令执行操作。

Ansible是一款很简单也很容易入门的部署工具,作为一个配置管理和配置工具,它使用SSH连接到远程服务器并运行配置好的任务,远程服务器上不用安装任何多余的软件,只需要开启ssh,所有工作都交给client端的Ansible负责。

Ansible可以非常容易的将bash脚本转换为可执行任,使用者在使用时,在client端输入命令或者playbooks,会通过预定好的规则将playbook拆解为play,再组织成Ansible可以识别的任务,调用模块和插件,根据主机清单通过SSH将临时文件发给远程的客户端执行并返回结果,执行结束后自动删除。

Ansible是基于模块工作的,它只是提供了一种运行框架,它本身没有完成任务的能力,真正执行操作的是Ansible的模块, 比如copy模块用于拷贝文件到远程主机上,service模块用于管理服务的启动、停止、重启等。

Ansible的绝大多数模块都具备幂等性(idempotence)。所谓幂等性,指的是多次操作或多次执行对系统资源的影响是一致的。比如执行 systemctl stop xxx 命令来停止服务,当发现要停止的目标服务已经处于停止状态, 它什么也不会做,所以多次停止的结果仍然是停止,不会改变结果,它是幂等的,而 systemctl restart xxx 是非幂等的。

Ansible的很多模块在执行时都会先判断目标节点是否要执行任务,所以,可以放心大胆地让Ansible去执行任务,重复执行某个任务绝大多数时候不会产生任何副作用。

1.2 官方网站

https://www.ansible.com/

在这里插入图片描述

我们可以看到上面的红帽标志,红帽公司于2015年10月收购了ansible,而ansible成立于2013年。

1.3 ansible的特点
  • 部署简单,没有客户端,只需在主控端部署Ansible环境,被控端无需做任何操作;
  • 模块化:调用特定的模块,完成特定任务
  • 默认使用SSH协议对设备进行管理;
  • 主从集中化管理;
  • 配置简单、功能强大、扩展性强;
  • 支持API及自定义模块,可通过Python轻松扩展;
  • 通过Playbooks来定制强大的配置、状态管理
  • 对云计算平台、大数据都有很好的支持;
  • 具有幂等性:一个操作在一个主机上执行一遍和执行N遍的结果是一样的

ansible是基于模块工作的,本身没有批量部署的能力。真正具有批量部署的是ansible锁运行的模块,ansible只是提供一种框架。主要包括:

  • 连接插件connection plugins:负责和被监控端实现通信;
  • host inventory:指定操作的主机,是一个配置文件里面定义监控的主机;
  • 各种模块核心模块、command模块、自定义模块;
  • 借助于插件完成记录日志邮件等功能;
  • playbook:剧本执行多个任务时,非必需可以让节点一次性运行多个任务
1.4 ansible的功能

可以实现批量系统操作配置

可以实现批量软件服务部署

可以实现批量文件数据分支

可以实现批量系统信息收集

1.4 ansible的工作机制

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

在这里插入图片描述
此图可以看出Ansible的组成由一下模块组成:

Ansible: ansible的核心模块
Host Inventory:主机清单,也就是被管理的主机列表
Playbooks:ansible的剧本,可想象为将多个任务放置在一起,一块执行
Core Modules:ansible的核心模块
Custom Modules:自定义模块
Connection Plugins:连接插件,用于与被管控主机之间基于SSH建立连接关系
Plugins:其他插件,包括记录日志等

二、Ansible的安装

2.1 设置EPEL仓库

Ansible仓库默认不在yum仓库中,因此我们需要使用下面的命令启用epel仓库

yum install epel-release -y

cd /etc/yum.repos.d/  
wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum clean all
yum makecache
2.2 使用yum安装Ansible
yum install ansible
2.3 查看ansible的版本
ansible --version
2.4 ansible的命令参数

anisble命令语法: ansible [-i 主机文件][-f 批次] [组名][-m 模块名称] [-a 模块参数]

参数功能
-v详细模式,如果执行成功,输出详细结果
-i指定host文件路径,默认在/etc/ansible/hosts
-f,-forks=NUMNUM默认是整数5,指定fork开启同步进程的个数
-m指定使用的module名称,默认command模块
-a指定模块的参数
-k提示输入SSH密码,而不是使用基于ssh密钥认证
-sudo指定使用sudo获取root权限
-K提示输入sudo密码
-u指定移动端的执行用户
-C测试命令执行会改变什么内容,不会真正的去执行

ansible-doc 详细参数

ansible-doc -l 列出所有模块列表

指定查看某个模块的参数
ansible-doc -s 模块名字

[root@itlaoxin162 ~]# ansible-doc -s onyx_ospf 
- name: Manage OSPF protocol on Mellanox ONYX network devices
 onyx_ospf:
     interfaces:            # List of interfaces and areas. Required if `state=present'.
     ospf:                  # (required) OSPF instance number 1-65535
     router_id:             # OSPF router ID. Required if `state=present'.
     state:                 # OSPF state.


[root@itlaoxin162 ~]# ansible-doc -s service
- name: Manage services
 service:
     arguments:             # Additional arguments provided on the command line.
     enabled:               # Whether the service should start on boot. *At least one of
                              state and enabled are
                              required.*
     name:                  # (required) Name of the service.
     pattern:               # If the service does not respond to the status command,
                              name a substring to look
                              for as would be found in
                              the output of the `ps'
                              command as a stand-in for a
                              status result. If the
                              string is found, the
                              service will be assumed to
                              be started.
     runlevel:              # For OpenRC init scripts (e.g. Gentoo) only. The runlevel
                              that this service belongs
                              to.
     sleep:                 # If the service is being `restarted' then sleep this many
                              seconds between the stop


三、ansible的使用

3.1 基于端口,用户,密码定义主机

格式:

ansible基于ssh连接-i (inventory)参数后指定的远程主机时,也可以写端口,用户,密码。
如:
ansible_ssh_port: 指定ssh端口 ansible_ssh_user:指定 ssh 用户 ansible_ssh_pass: 指定 ssh 用户登录是认证密码(明文密码不安全) ansible_sudo_pass: 指明 sudo 时候的密码

添加内容如下:

[root@itlaoxin162 ~]# grep -v ^# /etc/ansible/hosts |grep -v ^$
[web-servers]
192.168.1.163 ansible_ssh_port=22  ansible_ssh_user=root ansible_ssh_pass=12345678
[root@itlaoxin16

直接添加到文件文末就可以。

测试主机的连通性:

[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m ping
[WARNING]: Invalid characters were found in group names but not replaced, us
see details
192.168.1.163 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

查看组下所有的ip:

[root@itlaoxin162 ~]# ansible all --list
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
  hosts (1):
    192.168.1.163
[root@itlaoxin162 ~]#
3.2 基于ssh密钥来访问定义主机清单
3.2.1 设置密钥

设置密钥:

[root@itlaoxin162 ~]# 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:CWdEZJbtzH4+ypeXe80jPnBr9UX/0yChZtX5DCjKckg root@itlaoxin162
The key's randomart image is:
+---[RSA 2048]----+
|       o*o       |
|       +. .      |
|      . o+   o . |
|      E+ .= + + .|
|     . oSo + . =.|
|      o + =.o...=|
|       o o oooo+*|
|         .  ==ooB|
|          ooo++oo|
+----[SHA256]-----+
[root@itlaoxin162 ~]# 
3.2.2 拷贝密钥并测试

拷贝密钥并测试

[root@itlaoxin162 ~]# ssh-copy-id root@192.168.1.163
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/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

root@192.168.1.163's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@192.168.1.163'"
and check to make sure that only the key(s) you wanted were added.

**登陆测试:**
[root@itlaoxin162 ~]# ssh 192.168.1.163

Last login: Wed Apr 21 08:13:14 2021 from 192.168.1.162

向另外服务器发送密钥

[root@itlaoxin162 ~]# ssh-copy-id root@192.168.1.71
3.2.3 修改hosts
vim /etc/ansible/hosts

查看配置文件中刚刚修改的内容

[root@itlaoxin162 ~]# grep -v "^#" /etc/ansible/hosts |grep -v "^$" 
[web-servers]
192.168.1.163
192.168.1.71
3.2.4 ansible远程执行命令测试

ping模块 主要用来检测网络的连通性
command模块,执行shell命令

使用ping检查‘web-servers’或者ansible节点的连通性。

[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts 'web-servers' -m ping
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.163 | SUCCESS => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": false, 
   "ping": "pong"
}
192.168.1.71 | SUCCESS => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": false, 
   "ping": "pong"
}
[root@itlaoxin162 ~]# 

这条命令我们也可以不指定hosts,效果是一样的,我们只要指定组即可

[root@itlaoxin162 ~]# ansible 'web-servers' -m ping
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | SUCCESS => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": false, 
   "ping": "pong"
}
192.168.1.163 | SUCCESS => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": false, 
   "ping": "pong"
}
[root@itlaoxin162 ~]# 

有时候我们为了方便阅读也把主机组名写在最后面
web-servers 这个组名,放在最后面

[root@itlaoxin162 ~]# ansible -m command -a "uptime" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
08:37:28 up 11 min,  3 users,  load average: 0.02, 0.15, 0.17
192.168.1.163 | CHANGED | rc=0 >>
08:37:28 up  1:58,  5 users,  load average: 0.00, 0.01, 0.05
[root@itlaoxin162 ~]# 
3.2.5 案例1:检查节点的内存情况
[root@itlaoxin162 ~]# ansible -m command -a "free -m " 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
             total        used        free      shared  buff/cache   available
Mem:           3770         826        2283          15         661        2709
Swap:          2047           0        2047
192.168.1.163 | CHANGED | rc=0 >>
             total        used        free      shared  buff/cache   available
Mem:           3770         892        1076          38        1802        2588
Swap:          2047           0        2047
[root@itlaoxin162 ~]# 
3.2.6 案例2:给节点增加用户
[root@itlaoxin162 ~]# ansible -m command -a "useradd itoldxin" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>

192.168.1.163 | CHANGED | rc=0 >>

[root@itlaoxin162 ~]# 

查看用户是否创建成功

[root@itlaoxin162 ~]# ansible -m command -a "id itoldxin" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
uid=1001(itoldxin) gid=1001(itoldxin)=1001(itoldxin)
192.168.1.163 | CHANGED | rc=0 >>
uid=1001(itoldxin) gid=1001(itoldxin)=1001(itoldxin)
[root@itlaoxin162 ~]# 

四、ansible的高级用法

4.1 ansible的常用模块
4.1.1 ansible的3个远程模块的区别
  • command : ansible的默认模块,不指定-m参数的时候,使用的就是command模块; 常见的命令都可以使用,但命令的执行不是通过shell来执行的,所以< > | and & z这些操作都不可以,不支持管道,没法批量执行命令
  • shell模块: 使用shell模块的时候默认是通过/bin/sh来执行的,所以在终端输入的各种命令都可以使用
  • scripts模块
    使用scripts模块可以在本地写一个脚本,在远程服务器上执行
4.1.1.1 案例1:使用shell模块的案例
[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts  web-servers -m shell -a "source ~/.bash_profile && df -h|head -n 1"
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
文件系统                           容量  已用  可用 已用% 挂载点
192.168.1.163 | CHANGED | rc=0 >>
文件系统                 容量  已用  可用 已用% 挂载点
[root@itlaoxin162 ~]# 

注意: shell也可以把一个脚本copy到远程端然后再执行,但这样的话就需要调用两次ansible,所以script的出现就解决了这个问题;

4.1.1.2 案例2:使用script模块

先写一个脚本:

[root@itlaoxin162 ~]# cat !$
cat /etc/ansible/test.sh
#!/bin/bash
date
hostname
echo "大家好,我是互联网老鑫,脚本执行成功"
[root@itlaoxin162 ~]# 

执行查看结果:

[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m script -a "/etc/ansible/test.sh" 
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED => {
   "changed": true, 
   "rc": 0, 
   "stderr": "Shared connection to 192.168.1.71 closed.\r\n", 
   "stderr_lines": [
       "Shared connection to 192.168.1.71 closed."
   ], 
   "stdout": "2022年 01月 21日 星期三 08:59:33 CST\r\nk8s-master\r\n大家好,我是互联网老鑫,脚本执行成功\r\n", 
   "stdout_lines": [
       "2022年 01月 21日 星期三 08:59:33 CST", 
       "k8s-master", 
       "大家好,我是互联网老鑫,脚本执行成功"
   ]
}
192.168.1.163 | CHANGED => {
   "changed": true, 
   "rc": 0, 
   "stderr": "Shared connection to 192.168.1.163 closed.\r\n", 
   "stderr_lines": [
       "Shared connection to 192.168.1.163 closed."
   ], 
   "stdout": "2022年 01月 21日 星期三 08:59:33 CST\r\nitlaoxin-163\r\n大家好,我是互联网老鑫,脚本执行成功\r\n", 
   "stdout_lines": [
       "2022年 01月 21日 星期三 08:59:33 CST", 
       "itlaoxin-163", 
       "大家好,我是互联网老鑫,脚本执行成功"
   ]
}
[root@itlaoxin162 ~]# 

可以看到已经执行成功

4.2 copy模块的使用
# Ansible copy模块主要用于文件或者目录拷贝,支持文件、目录、权限、用户组功能,copy模块使用详解:

# 常用参数
src		 	 	Ansible端源文件或者目录,空文件夹不拷贝;
content		 	用来替代src,用于将指定文件的内容,拷贝到远程文件内;
dest			    客户端目标目录或者文件,需要绝对路径;
backup			# 拷贝之前,先备份远程节点上的原始文件;backup=yes
directory_mode	用于拷贝文件夹,新建的文件会被拷贝,而老旧的不会被拷贝;
follow			支持link文件拷贝;
force			覆盖远程主机不一致的内容;
group		 	设定远程主机文件夹的组名;
mode		 	指定远程主机文件及文件及的权限;
owner		 	设定远程主机文件夹的用户名,拥有者。

copy模块:实现主控端向目标主机拷贝文件,类似scp功能

案例:把ansible主机的/etc/hosts拷贝到主机组机器中的/root/下

[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m copy -a "src=/etc/hosts dest=/root owner=root group=root mode=0777"
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": true, 
   "checksum": "700a03c76a37e929d448b3be6419f4289d9314e6", 
   "dest": "/root/hosts", 
   "gid": 0, 
   "group": "root", 
   "md5sum": "138004edd9d16f2818e20842fc1f273d", 
   "mode": "0777", 
   "owner": "root", 
   "secontext": "system_u:object_r:admin_home_t:s0", 
   "size": 183, 
   "src": "/root/.ansible/tmp/ansible-tmp-1618966980.44-20046-203314294949142/source", 
   "state": "file", 
   "uid": 0
}
192.168.1.163 | CHANGED => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": true, 
   "checksum": "700a03c76a37e929d448b3be6419f4289d9314e6", 
   "dest": "/root/hosts", 
   "gid": 0, 
   "group": "root", 
   "md5sum": "138004edd9d16f2818e20842fc1f273d", 
   "mode": "0777", 
   "owner": "root", 
   "secontext": "system_u:object_r:admin_home_t:s0", 
   "size": 183, 
   "src": "/root/.ansible/tmp/ansible-tmp-1618966980.45-20045-254958397204815/source", 
   "state": "file", 
   "uid": 0
}
[root@itlaoxin162 ~]# 

查看是否执行成功:

[root@itlaoxin162 ~]# ansible -m command -a "ls /root/hosts" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
/root/hosts
192.168.1.163 | CHANGED | rc=0 >>
/root/hosts
[root@itlaoxin162 ~]# 

注意: command 不能使用ll命令,但可以使用ls -l的命令

[root@itlaoxin162 ~]# ansible -m command -a "ls -l  /root/hosts" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
-rwxrwxrwx. 1 root root 183 421 09:03 /root/hosts
192.168.1.163 | CHANGED | rc=0 >>
-rwxrwxrwx. 1 root root 183 421 09:03 /root/hosts
[root@itlaoxin162 ~]# 
4.3 file模块(创建、删除、修改、权限属性的维护和管理)
# Ansible file模块主要用于对文件的创建、删除、修改、权限、属性的维护和管理,File模块使用详解:

# 常用参数介绍
src					   Ansible端源文件或者目录;
follow				   支持link文件拷贝;
force				   覆盖远程主机不一致的内容;
group				   设定远程主机文件夹的组名;
mode				   指定远程主机文件及文件及的权限;
owner				   设定远程主机文件夹的用户名;
path				   目标路径,也可以用dest,name代替;
state				  #状态包括:file、link、directory、hard、touch、absent;
attributes			   文件或者目录特殊属性。
4.3.1 在docker服务器上/usr/local目录下创建一个rivers目录
# 在 docker 服务器上 /usr/local 目录下面创建一个rivers的目录,名字为 rivers,属主为nginx
[root@ansible_server~]# ansible docker -m file -a "path=/usr/local/rivers state=directory mode=644 owner=nginx"
10.0.0.7 | CHANGED => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": true, 
   "gid": 0, 
   "group": "root", 
   "mode": "0644", 
   "owner": "nginx", 
   "path": "/usr/local/rivers", 
   "size": 6, 
   "state": "directory", 
   "uid": 998
}

# 查看常见的目录
[root@ansible_server~]# ansible docker -m command -a "ls /usr/local/rivers"
10.0.0.7 | FAILED | rc=2 >>

# path表示目录的名称和路径, state=directory表示创建目录
4.3.2 在docker服务器上远程创建一 脚本文件
#在/usr/local/rivers/script.sh文件
[root@ansible_server~]# ansible docker -m file -a "path=/usr/local/rivers/script.sh state=touch mode=777"
10.0.0.7 | CHANGED => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": true, 
   "dest": "/usr/local/rivers/script.sh", 
   "gid": 0, 
   "group": "root", 
   "mode": "0777", 
   "owner": "root", 
   "size": 0, 
   "state": "file", 
   "uid": 0
}
[root@ansible_server~]#

# path表示目录的名称和路径, state=touch 表示创建文件

案例:给文件设置权限

[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m file -a "path=/root/hosts mode=0755"
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": true, 
   "gid": 0, 
   "group": "root", 
   "mode": "0755", 
   "owner": "root", 
   "path": "/root/hosts", 
   "secontext": "system_u:object_r:admin_home_t:s0", 
   "size": 183, 
   "state": "file", 
   "uid": 0
}
192.168.1.163 | CHANGED => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": true, 
   "gid": 0, 
   "group": "root", 
   "mode": "0755", 
   "owner": "root", 
   "path": "/root/hosts", 
   "secontext": "system_u:object_r:admin_home_t:s0", 
   "size": 183, 
   "state": "file", 
   "uid": 0
}
[root@itlaoxin162 ~]# 

查看权限:

[root@itlaoxin162 ~]# ansible -m command -a "ls -l  /root/hosts" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
-rwxr-xr-x. 1 root root 183 421 09:03 /root/hosts
192.168.1.163 | CHANGED | rc=0 >>
-rwxr-xr-x. 1 root root 183 421 09:03 /root/hosts
[root@itlaoxin162 ~]# 
4.4 stat模块获取远程文件信息

案例:获取文件信息

[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m stat -a "path=/root/hosts"
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | SUCCESS => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": false, 
   "stat": {
       "atime": 1618966982.400622, 
       "attr_flags": "", 
       "attributes": [], 
       "block_size": 4096, 
       "blocks": 8, 
       "charset": "us-ascii", 
       "checksum": "700a03c76a37e929d448b3be6419f4289d9314e6", 
       "ctime": 1618967480.9315438, 
       "dev": 64768, 
       "device_type": 0, 
       "executable": true, 
       "exists": true, 
       "gid": 0, 
       "gr_name": "root", 
       "inode": 78337, 
       "isblk": false, 
       "ischr": false, 
       "isdir": false, 
       "isfifo": false, 
       "isgid": false, 
       "islnk": false, 
       "isreg": true, 
       "issock": false, 
       "isuid": false, 
       "mimetype": "text/plain", 
       "mode": "0755", 
       "mtime": 1618966981.7806218, 
       "nlink": 1, 
       "path": "/root/hosts", 
       "pw_name": "root", 
       "readable": true, 
       "rgrp": true, 
       "roth": true, 
       "rusr": true, 
       "size": 183, 
       "uid": 0, 
       "version": "693378940", 
       "wgrp": false, 
       "woth": false, 
       "writeable": true, 
       "wusr": true, 
       "xgrp": true, 
       "xoth": true, 
       "xusr": true
   }
}
192.168.1.163 | SUCCESS => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": false, 
   "stat": {
       "atime": 1618966982.6472814, 
       "attr_flags": "", 
       "attributes": [], 
       "block_size": 4096, 
       "blocks": 8, 
       "charset": "us-ascii", 
       "checksum": "700a03c76a37e929d448b3be6419f4289d9314e6", 
       "ctime": 1618967481.0644567, 
       "dev": 64768, 
       "device_type": 0, 
       "executable": true, 
       "exists": true, 
       "gid": 0, 
       "gr_name": "root", 
       "inode": 33662547, 
       "isblk": false, 
       "ischr": false, 
       "isdir": false, 
       "isfifo": false, 
       "isgid": false, 
       "islnk": false, 
       "isreg": true, 
       "issock": false, 
       "isuid": false, 
       "mimetype": "text/plain", 
       "mode": "0755", 
       "mtime": 1618966982.176287, 
       "nlink": 1, 
       "path": "/root/hosts", 
       "pw_name": "root", 
       "readable": true, 
       "rgrp": true, 
       "roth": true, 
       "rusr": true, 
       "size": 183, 
       "uid": 0, 
       "version": "1103139934", 
       "wgrp": false, 
       "woth": false, 
       "writeable": true, 
       "wusr": true, 
       "xgrp": true, 
       "xoth": true, 
       "xusr": true
   }
}
4.5 get_url模块

实现远程主机下载指定的url地址,支持sha256sum文件校验

案例:

ansible -i /etc/ansible/hosts web-servers -m get_url -a "url=https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm  dest=/tmp/ mode=0440 force=yes"

注:url=https://xxx 的等号=前后不能有空格
扩展:查看force=yes的作用

4.6 yum模块
#Ansible yum 模块主要用于软件的安装、升级、卸载,支持红帽.rpm软件的管理,YUM模块使用详解:
# 常用参数
conf_file					    设定远程yum执行时所依赖的yum配置文件
disable_gpg_check			    安装软件包之前是否坚持gpg  key;
name						    需要安装的软件名称,支持软件组安装;
update_cache				    安装软件前更新缓存;
enablerepo					    指定repo源名称;
skip_broken      			    跳过异常软件节点;
state						    #软件包状态,包括:installed、present、latest、absent、removed。
4.6.1 ansible服务器上 远程在服务器安装 启动 卸载 httpd

yum模块linux平台软件包管理。
yum模块可以提供的status状态: latest ,present,installed #这三个代表安装;removed, absent #这两个是卸载

案例:使用yum模块安装httpd

# 远程在 10.0.0.6 服务器上安装 httpd 服务
[root@ansible_server~]# ansible -i /etc/ansible/hosts 10.0.0.6 -m yum -a "name=httpd state=installed"

# 远程启动 httpd 服务
[root@ansible_server~]# ansible -i /etc/ansible/hosts 10.0.0.6 -m command -a "systemctl start httpd"
10.0.0.6 | CHANGED | rc=0 >>


# 远程查看http服务进程
[root@ansible_server~]# ansible -i /etc/ansible/hosts 10.0.0.6 -m shell -a "ps -ef|grep httpd"
10.0.0.6 | CHANGED | rc=0 >>
root      10924      1  0 16:11 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    10925  10924  0 16:11 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    10926  10924  0 16:11 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    10928  10924  0 16:11 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    10929  10924  0 16:11 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    10930  10924  0 16:11 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
root      11066  11061  0 16:12 pts/0    00:00:00 /bin/sh -c ps -ef|grep httpd
root      11068  11066  0 16:12 pts/0    00:00:00 grep httpd


# 停止 httpd 服务
[root@ansible_server~]# ansible -i /etc/ansible/hosts 10.0.0.6 -m command -a "systemctl stop httpd"
10.0.0.6 | CHANGED | rc=0 >>

# 远程卸载 httpd
[root@ansible_server~]# ansible -i /etc/ansible/hosts 10.0.0.6 -m yum -a "name=httpd state=removed"
4.6.2 将组服务器中的所有yum进程都杀掉
# 停止正在工作的yum进程   www组
[root@ansible_server~]# ansible www -m shell -a "pkill -yum"

# 查看进程
[root@ansible_server~]# ansible www -m shell -a "ps -ef|grep yum"
10.0.0.6 | CHANGED | rc=0 >>
root      12032  12027  0 09:12 pts/1    00:00:00 /bin/sh -c ps -ef|grep yum
root      12034  12032  0 09:12 pts/1    00:00:00 grep yum
10.0.0.5 | CHANGED | rc=0 >>
root      12260  12255  0 09:12 pts/0    00:00:00 /bin/sh -c ps -ef|grep yum
root      12262  12260  0 09:12 pts/0    00:00:00 grep yum
[root@ansible_server~]# 
4.7 cron模块远程管理主机crontab配置
# Ansible cron模块主要用于添加、删除、更新操作系统Crontab任务计划,Cron模块使用详解:

# 常用参数
name      					任务计划名称;
cron_file 					替换客户端该用户的任务计划的文件;
minute    					分( 0-59**/2 );
hour      					时( 0-23**/2 );
day       					日( 1-31**/2 );
month     					月( 1-12**/2 );
weekday   					周( 0-61-7* );
job       					任何计划执行的命令,state要等于present;
backup    					是否备份之前的任务计划;
user      					新建任务计划的用户;
state     					指定任务计划present、absent。
案例9: 增加每30分钟执行 echo"我是互联网老鑫"
ansible -i /etc/ansible/hosts web-servers -m cron -a “name=‘list dir’ minute=*/30’ job=‘echo 我是互联网老鑫”’”
4.7.1 利用cron模块创建/删除计划任务—时间同步(阿里云)

基本同步用法

# docker 服务器 自动同步 阿里云
[root@ansible_server~]# ansible 10.0.0.7 -m cron -a "minute=0 hour=2 job='/usr/sbin/ntpdate ntp1.aliyun.com >/dev/null 2>&1'" 
[DEPRECATION WARNING]: The 'name' parameter will be required in future releases.. This 
feature will be removed in version 2.12. Deprecation warnings can be disabled by setting
 deprecation_warnings=False in ansible.cfg.
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "None"
    ]
}

# 如何删除定时任务
[root@ansible_server~]# ansible docker -m cron -a "name='#Ansible' state=absent"
4.7.2 给定时任务设置注释信息

添加定时任务 名称注释

# 添加注释信息
[root@ansible_server~]# ansible 10.0.0.6 -m cron -a "name='time sync' minute=0 hour=2 job='/usr/sbin/ntpdate ntp1.aliyun.com >/dev/null 2>&1'"
10.0.0.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "time sync"
    ]
}

#如何查看10.0.0.6这台服务器上的定时任务
[root@ansible_server~]# ansible 10.0.0.6 -m shell -a "cat /var/spool/cron/root"
10.0.0.6 | CHANGED | rc=0 >>
#time sync by lidao at 2017-03-08
*/5 * * * * /usr/sbin/ntpdate ntp.aliyun.com >/dev/null 2>&1
#Ansible: time sync
0 2 * * * /usr/sbin/ntpdate ntp1.aliyun.com >/dev/null 2>&1
4.8 service远程管理主机系统服务模块

service模块常用参数:
(1)、name参数:此参数用于指定需要操作的服务名称,比如 nginx,httpd。
(2)、state参数:此参数用于指定服务的状态

比如,我们想要启动远程主机中的httpd,则可以将 state 的值设置为 started;
如果想要停止远程主机中的服务,则可以将 state 的值设置为 stopped。
此参数的可用值有 started、stopped、restarted(重启)、reloaded。

enabled参数:此参数用于指定是否将服务设置为开机 启动项,设置为 yes 表示将对应服务设置为开机启动,设置为 no 表示不会开机启动。

注:想使用service模块启动服务,被启动的服务,必须可以使用service 命令启动或关闭

# Ansible service模块主要用于远程客户端各种服务管理,包括启动、停止、重启、重新加载等,service模块使用详解:

# 常用参数
enabled				是否开启启动服务;
name				服务名称;
runlevel			    服务启动级别;
arguments			服务命令行参数传递;
state				    服务操作状态,状态包括started, stopped, restarted, reloaded。

案例:使用service模块重启httpd

[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m service -a "name=httpd state=restarted"
4.8.1 远程重启web服务器上的防火墙 服务
# 远程重启10.0.0.5 服务器上的 firewalld 服务器
[root@ansible_server~]# ansible 10.0.0.5  -m service -a "name=firewalld state=restarted"
10.0.0.5 | CHANGED => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": true, 
   "name": "firewalld", 
   "state": "started", 
   "status": {
       "ActiveEnterTimestampMonotonic": "0", 
       "ActiveExitTimestampMonotonic": "0", 
       "ActiveState": "inactive", 
     ……
[root@ansible_server~]# 
# 远程关闭防火墙
[root@ansible_server~]# ansible 10.0.0.5  -m service -a "name=firewalld state=stopped"
4.8.2 远程重启eht0网卡(平滑启动)
# 远程启动 eht0 网卡
[root@ansible_server~]# ansible 10.0.0.5 -m service -a "name=network args=eth0 state=restarted"
[WARNING]: Ignoring "args" as it is not used in "systemd"
10.0.0.5 | CHANGED => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": true, 
   "name": "network", 
   "state": "started", 
   "status": {
       "ActiveEnterTimestamp": "Fri 2021-08-27 16:30:41 CST", 
       ……
4.8.3 远程设置nfs 开启自启动,启动级别3,5级别
# 远程开机启动nfs服务,设置3,5级别自动启动
root@ansible_server~]# ansible -k all -m service  -a  "name=nfs  enabled=yes  runlevel=3,5"
SSH password: 
[WARNING]: Ignoring "runlevel" as it is not used in "systemd"
[WARNING]: Ignoring "runlevel" as it is not used in "systemd"
[WARNING]: Ignoring "runlevel" as it is not used in "systemd"
4.9 user模块 管理远程主机的用户
# Ansible user模块主要用于操作系统用户、组、权限、密码等操作,user模块使用详解:
system          				    默认创建为普通用户,为yes则创建系统用户;
append							    添加一个新的组;
comment 						    新增描述信息;
createhome 						    给用户创建家目录;
force							    用于删除强制删除用户;
group							    创建用户主组;
groups							    将用户加入组或者附属组添加;
home							    指定用户的家目录;
name							    表示状态,是否create、remove、modify;
password						    指定用户的密码,此处为加密密码;
remove							    删除用户;
shell							    设置用户的shell登录环境;
uid								    设置用户id;
update_password 				    修改用户密码;
state           				    用户状态,默认为present表示新建用户。absent表示删除
4.9.1 给docker服务器创建一个用户名称 dock普通管理用户
# 在docker 服务器上创建一个普通用户 nidaye。name=用户名,home=用户家目录
[root@ansible_server~]# ansible docker -m user -a "name=nidaye home=/home/admin"
10.0.0.7 | CHANGED => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": true, 
   "comment": "", 
   "create_home": true, 
   "group": 1001, 
   "home": "/home/admin", 
   "name": "nidaye", 
   "shell": "/bin/bash", 
   "state": "present", 
   "system": false, 
   "uid": 1001
}

# 查看刚新建的用户 nidaye
[root@ansible_server~]# ansible docker -m shell -a "id nidaye"
10.0.0.7 | CHANGED | rc=0 >>
uid=1001(nidaye) gid=1001(nidaye) groups=1001(nidaye)
[root@ansible_server~]# 
4.9.2 给web服务器上的apache服务创建/删除一个apache用户
# 在10.0.0.5 服务器上 创建一个 名字apache ,shell /sbin/nologin 家目录为/opt
[root@ansible_server~]# ansible 10.0.0.5 -m user -a "name=apache home=/opt shell=/sbin/nologin"
10.0.0.5 | CHANGED => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": true, 
   "comment": "", 
   "create_home": true, 
   "group": 1001, 
   "home": "/opt", 
   "name": "apache", 
   "shell": "/sbin/nologin", 
   "state": "present", 
   
# 删除apache用户
[root@ansible_server~]# ansible 10.0.0.5 -m user -a "name=apache state=absent force=yes"
10.0.0.5 | CHANGED => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": true, 
   "force": true, 
   "name": "apache", 
   "remove": false, 
   "state": "absent"
}
[root@ansible_server~]# 
4.10 ping模块实战

Ansible最基础的模块为ping模块,主要用于判断远程客户端是否在线,用于ping本身服务器,返回值为changed、ping。

自己管理自己:

# ansible基于ssh连接-i (inventory)参数后指定的远程主机时,也可以写端口,用户,密码。
格式:ansible_ssh_port:指定ssh端口   ansible_ssh_user:指定 ssh 用户 ansible_ssh_pass:指定 ssh 用户登录是认证密码(明文密码不安全)  ansible_sudo_pass:指明 sudo 时候的密码

[root@ansible_server~]# cat /etc/ansible/hosts
[www]
10.0.0.5
10.0.0.6

[docker]
10.0.0.7

[manager]
10.0.0.61  ansible_ssh_port=22  ansible_ssh_user=root  ansible_ssh_pass=123456
[root@ansible_server~]# 


# 同时还可以基于SSH 免密登录,2种方式选一种。
# 将自己的密钥拷贝到本地,然后ssh 连接一下即可。

[root@web01_server~]# ssh-copy-id root@10.0.0.61

ansiblepip一个网段机器进行管理,ping网段的连通性:

# ping 某一个网段
[root@ansible_server~]# ansible 10.0.0.* -m ping

# 路径是可以省略的  -i ,因为默认路径就是 /etc/ansible/hosts
[root@ansible_server~]# ansible -i /etc/ansible/hosts "docker" -m ping
10.0.0.7 | SUCCESS => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   }, 
   "changed": false, 
   "ping": "pong"
}
[root@ansible_server~]# 
4.11 shell模块使用
Ansible shell模块主要用于远程客户端上执行各种Shell命令或者运行脚本,远程执行命令通过/bin/sh环境来执行,支持比command更多的指令,Shell模块使用详解:

**常用参数**

chdir					执行命令前,切换到目录;
creates					当该文件存在时,则不执行该步骤;
executable				换用shell环境执行命令;
free_form				需要执行的脚本;
removes					当该文件不存在时,则不执行该步骤;
warn					如果在ansible.cfg中存在告警,如果设定了False,不会警告此行。
4.11.1 通过ansible在docker服务器上创建/查看目录
# 在docker服务器上 ,在/opt 目录下创建一个名字为rivers+当前时间的目录
[root@ansible_server~]# ansible docker -m shell -a "mkdir /opt/rivers`date +%F`;ls /opt"
[WARNING]: Consider using the file module with state=directory rather than
running 'mkdir'.  If you need to use command because file is insufficient you
can add 'warn: false' to this command task or set 'command_warnings=False' in
ansible.cfg to get rid of this message.
10.0.0.7 | CHANGED | rc=0 >>
rivers2021-09-16

# 通过ls 查看是否创建
[root@ansible_server~]# ansible docker -m shell -a "ls /opt"
10.0.0.7 | CHANGED | rc=0 >>
rivers2021-09-16
[root@ansible_server~]# 
4.11.2 通过ansible shell 模块远程查看Nginx服务是否启动
# 远程查看docker服务器上nginx 进程信息
[root@ansible_server~]# ansible docker -m shell -a "ps -ef|grep nginx"
10.0.0.7 | CHANGED | rc=0 >>
root      11711      1  0 15:25 ?        00:00:00 nginx: master process nginx
nginx     11712  11711  0 15:25 ?        00:00:00 nginx: worker process
root      11775  11770  3 15:26 pts/0    00:00:00 /bin/sh -c ps -ef|grep nginx
root      11777  11775  0 15:26 pts/0    00:00:00 grep nginx
[root@ansible_server~]# 
4.11.3 通过ansible shell模块远程查看防护墙状态
# ansible 服务器上远程查看 dockerf 服务器行的防火墙状态是否运行

[root@ansible_server~]# ansible docker -m shell -a "firewall-cmd --state"
10.0.0.7 | CHANGED | rc=0 >>
running
[root@ansible_server~]# 
4.11.4 通过ansible批量修改 用户密码
# 通通过shell 远程批量修改密码
[root@ansible_server~]# ansible www -m shell -a "echo 123456|passwd --stdin root"
10.0.0.5 | CHANGED | rc=0 >>
Changing password for user root.
passwd: all authentication tokens updated successfully.
10.0.0.6 | CHANGED | rc=0 >>
Changing password for user root.
passwd: all authentication tokens updated successfully.
4.12 command模块使用
# Ansible command模块为ansible默认模块,主要用于执行Linux基础命令,可以执行远程服务器命令执行、任务执行等操作。Command模块使用详解:

Chdir					执行命令前,切换到目录;
Creates					当该文件存在时,则不执行该步骤;
Executable				换用shell环境执行命令;
Free_form				需要执行的脚本;
Removes					当该文件不存在时,则不执行该步骤;
Warn					如果在ansible.cfg中存在告警,如果设定了False,不会警告此行。
4.12.1 通过ansible使用df -h 查看磁盘空间使用情况
# 使用df -h 查看 docker组中机器的磁盘使用情况
[root@ansible_server~]# ansible -i /etc/ansible/hosts 10.0.0.7 -m command -a "df -h"
10.0.0.7 | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        99G  1.7G   97G   2% /
devtmpfs        442M     0  442M   0% /dev
tmpfs           453M     0  453M   0% /dev/shm
tmpfs           453M  7.2M  446M   2% /run
tmpfs           453M     0  453M   0% /sys/fs/cgroup
/dev/sda1       197M  105M   93M  54% /boot
tmpfs            91M     0   91M   0% /run/user/0
[root@ansible_server~]# 

# 简便方式写(效果一样的)
[root@ansible_server~]# ansible docker -m command -a "df -h"


# 能否使用shell 查看呢 ?
[root@ansible_server~]# ansible docker -m shell -a "df -h"

# 答案:可以查看,shell 本质上和command 区别不大,知识支持的命令更多
4.12.2 通过ansible远程查看系统时间
# 查看docker 服务器上的时间
[root@ansible_server~]# ansible docker -m command -a "date %F"
10.0.0.7 | FAILED | rc=1 >>
date: invalid date ‘%F’non-zero return code
[root@ansible_server~]# 
4.12.3 ansible远程执行下载http安装包
# 先远程查看docker服务器上有没有httpd安装包
[root@ansible_server~]# ansible docker -m command -a "ls"
10.0.0.7 | CHANGED | rc=0 >>
anaconda-ks.cfg

# 在docker 服务器上远程下载httpd-2.4.46.tar.bz2
[root@ansible_server~]# ansible docker -m command -a "wget https://downloads.apache.org/httpd/httpd-2.4.46.tar.bz2"
4.13 synchronize模块使用
# Ansible synchronize模块主要用于目录、文件同步,基于Rsync命令同步目录,Synchronize模块使用详解:

# 常用参数
compress        			    开启压缩,默认为开启;
archive         				是否采用归档模式同步,保证源和目标文件属性一致;
checksum        			    是否效验;
dirs            				以非递归的方式传输目录;
links           				同步链接文件;
recursive       				是否递归yes/no;
rsync_opts      				使用rsync 的参数;
copy_links      				同步的时候是否复制连接;
delete          				删除源中没有而目标存在的文件;
src                          源目录及文件;
dest	        				目标目录及文件;
dest_port       				目标接受的端口;
rsync_path      				服务的路径,指定 rsync 命令来在远程服务器上运行;
rsync_timeout   				指定rsync操作的IP超时时间;
set_remote_user 			    设置远程用户名;
--exclude=.log  				忽略同步.log结尾的文件;
mode            			同步的模式,rsync同步的方式PUSH、PULL,默认都是推送push。
4.13.1 将源目录同步至目标目录(增量同步)
# 将本地/tmp 目录远程同步到 docker服务器上(增量同步)
[root@ansible_server~]# ansible docker -m synchronize  -a 'src=/tmp/ dest=/tmp/'
10.0.0.7 | CHANGED => {
   "changed": true, 
   "cmd": "/usr/bin/rsync --delay-updates -F --compress --archive --rsh=/usr/bin/ssh -S none -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null --out-format=<<CHANGED>>%i %n%L /tmp/ 10.0.0.7:/tmp/", 
   "msg": ".d..t...... ./\n<f+++++++++ xxx.xx\ncd+++++++++ ansible_synchronize_payload_Bxuy_S/\n<f+++++++++ ansible_synchronize_payload_Bxuy_S/ansible_synchronize_payload.zip\ncd+++++++++ vmware-root_6044-692160431/\n", 
   "rc": 0, 
   "stdout_lines": [
       ".d..t...... ./", 
       "<f+++++++++ xxx.xx", 
       "cd+++++++++ ansible_synchronize_payload_Bxuy_S/", 
       "<f+++++++++ ansible_synchronize_payload_Bxuy_S/ansible_synchronize_payload.zip", 
       "cd+++++++++ vmware-root_6044-692160431/"
   ]
}
[root@ansible_server~]# 
4.13.2 将源目录同步至目标目录(完全同步)
# 完全同步,尾巴后添加 delete=yes
[root@ansible_server/tmp]# ansible docker -m synchronize  -a 'src=/tmp/ dest=/tmp/ delete=yes'

五、ansible批量管理服务

5.1 ansible剧本介绍
5.1.1 ansible playbook剧本介绍和基础使用说明

剧本介绍:

# 通过Playbook任务,能够集中管理多个任务,将多个任务关联起来,从而实现更加复杂工作,满足生产环境的各个需求,提高运维人员管理服务器效率

# Playbook剧本的产物YAML文件,类似XML接口(Tomcat)文件,内部有固定语法、参数等,要掌握常用的YAML语法编写,掌握满足运维管理方向的语法即可

playbook语法:

# yaml 格式语法

# Playbook是以YAML格式编写的文本文件,通常使用扩展名yml保存。Playbook使用空格字符缩进来表示其数据结构。YAML对用于缩进的空格数量没有严格的要求,但有两个基本的规则:

	处于层次结构中同一级别的数据元素(例如同一列表中的项目)必须具有相同的缩进量。
	如果项目属于其他项目的子项,其缩进量必须大于父项
# 只有空格字符可用于缩进,不允许使用tab键。约定俗成的缩进量一般是一级2个空格。
# Playbook开头的一行由三个破折号(---)组成,这是文档开始标记。其末尾可能使用三个圆点(...)作为文档结束标记,尽管在实践中这通常会省略。

playbook运行/语法检查

# 运行 lnmp文件
[root@ansible_server~]# ansible-playbook lnmp.yml

# 检查lnmp 语法
[root@ansible_server~]# ansible-playbook --syntax-check lnmp.yml



playbook是一个不同于使用ansible命令行执行方式的模式,功能更强大更灵活。
1、在playbooks 中常见的定义任务:
	name: task description     #任务描述信息
	module_name: module_args    #需要使用的模块名字:  模块参数
   files:存放需要同步到异地服务器的源码文件及配置文件; 
	handlers:当服务的配置文件发生变化时需要进行的操作,比如:重启服务,重新加载配置文件,		 	 handlers 
	meta:角色定义,可留空; 
	tasks:需要进行的执行的任务; 
	templates:用于执行lamp安装的模板文件,一般为脚本
	vars:本次安装定义的变量

#playbook是由一个或多个"play"组成的列表。play的主要功能在于将事先归为一组的主机装扮成事先通过ansible中的task定义好的角色。
#github上提供了大量的实例供大家参考  https://github.com/ansible/ansible-examples
5.1.2 playbook常见的组件及作用

playbook组件

  • Target定义playbook的远程主机组:
  • 常用参数:
    • hosts定义远程主机组
    • user执行该任务的用户
    • sudo设置为yes的时候,执行任务的时候使用root权限
    • sudo_user指定sudo普通用户
    • connection默认基于SSH连接客户端
    • gather_facks获取远程主机facts基础信息
  • Variable定义playbook使用的变量:
  • 常用参数:
    • vars定义格式,变量名:变量值
    • vars_files指定变量文件
    • vars_prompt用户交互模式自定义变量
    • setup模块去远程主机的值
  • Task定义远程主机上执行的任务列表
  • 常用参数
    • name任务显示名称也即屏幕显示信息
    • action定义执行的动作
    • copy复制本地文件到远程主机
    • template复制本地文件到远程主机,可以引用本地变量
    • service定义服务的状态
  • Handler当服务的配置文件发送变化时需要进行的操作,比如:重启服务,重新加载配置
5.1.3 远程主机安装httpd-2.4.46.tar.bz2 web服务案例演示
# 通过ansible 给www组服务器里面的 10.0.0.5 这台服务器安装httpd-2.4.46.tar.bz2服务
[root@ansible_server~]# cat httpd_install.yaml 
#author rivers
---
- hosts: 10.0.0.5
 remote_user: root

 tasks:
   - name: install httpd-2.4.tar.bz2
     yum: name=apr,apr-devel,apr-util,apr-util-devel,gcc-c++,bzip2  state=installed
 - name: apache httpd-2.4 install process
     shell: cd /opt/; rm -rf httpd-2.4.46.tar.bz2; wget https://downloads.apache.org/httpd/httpd-2.4.46.tar.bz2; tar xjf httpd-2.4.46.tar.bz2 -C /usr/local/; cd /usr/local/httpd-2.4.46/; ./configure --prefix=/usr/local/apache  --with-pmp=worker; make -j4; make install;
...

检查httpd_install.yaml语法文件

# 检查 httpd_install.yaml 语法,下面是正确通过的
[root@ansible_server~]# ansible-playbook --syntax-check httpd_install.yaml 

playbook: httpd_install.yaml

# 常见报错提示
[root@ansible_server~]# ansible-playbook --syntax-check httpd_install.yaml 
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: No JSON object could be decoded
 
Syntax Error while loading YAML.
 mapping values are not allowed in this context

The error appears to be in '/root/httpd_install.yaml': line 8, column 10, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

   -name: install httpd-2.4.tar.bz2
     yum: name=apr apr-devel apr-util apr-util-devel gcc-c++ bzip2  state=installed
        ^ here
5.2 playbook企业案例实战
5.2.1 使用ansible playbook安装nginx WEB服务,安装完并启动Nginx实战

playbook局本

# 判断是否安装有安装后的nginx目录,如果有直接启动,如果没有安装nginx
#author rivershosts: 10.0.0.7
remote_user: root
tasks:

 - name: install yum_package
   yum: name=pcre-devel,openssl,openssl-devel,gd-devel,gcc,gcc-c++ state=installed
 - name: echo -e "\033[44;37m 判断是否存在nginx安装目录 \033[0m"
   file: path=/usr/local/nginx state=directory
   notify:
     - nginx start
     - nginx install

handlers:

 - name: nginx install
   shell: cd /opt/; rm -rf nginx-1.20.1.tar.gz; wget http://nginx.org/download/nginx-1.20.1.tar.gz; tar xf nginx-1.20
     .1.tar.gz -C /usr/local/; useradd -M -s /sbin/nologin nginx; mkdir -p /var/log/nginx;cd /usr/local/nginx-1.20.1; ./confi
     gure --user=nginx --prefix=/usr/local/nginx --with-http_ssl_module --with-http_realip_module --with-http_image_filter_mo
     dule --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/ng
     inx/access.log --error-log-path=/var/log/nginx/error.log --without-http_rewrite_module; make && make install; /usr/local
     /nginx/sbin/nginx  -t;

 - name: nginx start
   shell: /usr/local/nginx/sbin/nginx
5.2.2 使用ansible playbook批量创建系统用户
 # 使用 user 模块批量创建rivers01、0203用户
# author rivers
- hosts: 10.0.0.7
 remote_user: root
 tasks:
 - name: Add User list.
   user: name={{ item }} state=present
   with_items:
      - rivers01
      - rivers02
      - rivers03

 - name: check system user
   shell: num= `tail -3 /etc/passwd|grep -c rivers`; if [ $num ge 3 ]; then echo is ok!; fi

六、ansible实战案例

playbooks的介绍
1) 在playbooks 中定义任务:

​ — name: task description #任务描述信息
​ module_name: module_args #需要使用的模块名字: 模块参数

2)ansible-playbook 执行 命令:
​ ansible-playbook site.yml

3)playbook是由一个或多个"play"组成的列表。play的主要功能在于将事先归为一组的主机装扮成事先通过ansible中的task定义好的角色。
github上提供了大量的实例供大家参考: https://github.com/ansible/ansible-examples

6.1 实战1:使用ansible部署k8s及集群
6.1.1 安装git命令
[root@itlaoxin162 ~]# yum install git
6.1.2 使用git下载相应的ansible-k8s-install包:
[root@itlaoxin162 ~]# git clone https://github.com/lizhenliang/ansible-install-k8s
正克隆到 'ansible-install-k8s'...
remote: Enumerating objects: 157, done.
remote: Counting objects: 100% (157/157), done.
remote: Compressing objects: 100% (123/123), done.
remote: Total 157 (delta 46), reused 114 (delta 20), pack-reused 0
接收对象中: 100% (157/157), 150.68 KiB | 110.00 KiB/s, done.
处理 delta 中: 100
6.1.3 修改hosts文件

进入到ansbile-install-k8s目录
修改hosts文件,根据规划修改对应IP和名称。

cd ansible-install-k8s
[root@itlaoxin162 ansible-install-k8s]# vim hosts
[root@itlaoxin162 ansible-install-k8s]# vim group_vars/all.yml 
6.1.4 部署命令

单Master版:

ansible-playbook -i hosts single-master-deploy.yml -uroot -k

多Master版:

ansible-playbook -i hosts multi-master-deploy.yml -uroot -k
6.2 ansible—部署Inmp架构
6.2.1 使用ansible playbook搭建一键部署Inmp架构
#编写 ansible-playbook lnmp.yaml 剧本
[root@ansible_server~]# cat lnmp_install.yaml 
# author 
# 任务1:安装nginx
- hosts: 10.0.0.5
 remote_user: root
 tasks:
   - name: 修改主机名,判断、安装/启动nginx
     shell: hostnamectl set-hostname Hosts-01
   - name: install yum_package
     yum: name=pcre-devel,openssl,openssl-devel,gd-devel,gcc,gcc-c++ state=installed
   - name: echo -e "\033[44;37m 判断是否存在nginx安装目录 \033[0m"
     file: path=/usr/local/nginx state=directory
     notify: 
       - nginx start
       - nginx install
 
 handlers:
   - name: nginx install
     shell: cd /opt/; rm -rf nginx-1.20.1.tar.gz; wget http://nginx.org/download/nginx-1.20.1.tar.gz; tar xf nginx-1.20.1.tar.gz -C /usr/local/; useradd -M -s /sbin/nologin nginx; mkdir -p /var/log/nginx;cd /usr/local/nginx-1.20.1; ./configure --user=nginx --prefix=/usr/local/nginx --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --without-http_rewrite_module; make && make install; /usr/local/nginx/sbin/nginx  -t;

   - name: nginx start
     shell: /usr/local/nginx/sbin/nginx
 
# 任务2 安装mysql
- hosts: 10.0.0.6
 remote_user: root
 tasks:
   - name: install yum_package
     yum: name=pcre-devel,openssl,openssl-devel,gd-devel,gcc,gcc-c++,ncurses-devel state=installed
   - name: 下载安装包、并解压
     shell: cd /opt/; tar -xf mysql-5.1.63.tar.gz -C /usr/local/
   - name: 开始编译安装
     shell: cd /usr/local/mysql-5.1.63/; ./configure --prefix=/usr/local/mysql --enable-assembler; make -j8&&make -j8 install; \cp /usr/local/mysql/share/mysql/my-medium.cnf /etc/my.cnf; \cp /usr/local/mysql/share/mysql/mysql.server  /etc/rc.d/init.d/mysqld;
   - name: 配置启动/重启
     shell: chkconfig --add mysqld;chkconfig --level 35 mysqld on; service  mysqld  restart


# 任务3 安装php
- hosts: 10.0.0.5
 remote_user: root

 tasks:
   - name: install php_package
     yum: name=libxml2,libxml2-devel,openssl,openssl-devel,bzip2,bzip2-devel,libcurl,libcurl-devel,libjpeg,libjpeg-devel,libpng,libpng-devel,freetype,freetype-devel,gmp,gmp-devel,libmcrypt,libmcrypt-devel,readline,readline-devel,libxslt,libxslt-devel,pcre-devel,ncurses,ncurses-devel,bison,cmake state=installed
   - name: 下载安装包、并解压
     shell: cd /opt/; wget http://mirrors.sohu.com/php/php-7.2.10.tar.gz; tar xf php-7.2.10.tar.gz -C /usr/local/; cd /usr/local/php-7.2.10/; ./configure --prefix=/usr/local/php --disable-fileinfo --enable-fpm --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-openssl --with-zlib --with-curl --enable-ftp --with-gd --with-xmlrpc --with-jpeg-dir --with-png-dir --with-freetype-dir --enable-gd-native-ttf --enable-mbstring --with-mcrypt=/usr/local/libmcrypt --enable-zip --enable-mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-mysql-sock=/var/lib/mysql/mysql.sock --without-pear --enable-bcmath; make && make install; ln -s /usr/local/php/bin/* /usr/local/bin/; \cp php.ini-production /etc/php.ini; \cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf; \cp /usr/local/php/etc/php-fpm.d/www.conf.default /usr/local/php/etc/php-fpm.d/www.conf; \cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm; chmod +x /etc/init.d/php-fpm; chkconfig --add php-fpm 
  
   - name: 启动php服务
     shell: systemctl start php-fpm
6.2.2 整合Inmp架构,进行测试
# 修改 /usr/local/nginx/conf/nginx.conf 文件 

# 1.将user 改为 nginx
# 2.添加一下内容
location / {
		root   html;
		index  index.php index.html index.htm;
}

location ~ \.php$ {
       root           html;
       fastcgi_pass   127.0.0.1:9000;
       fastcgi_index  index.php;
       fastcgi_param  SCRIPT_FILENAME  /usr/local/nginx/html$fastcgi_script_name; 
       include        fastcgi_params;
}

# 设置php 网站文件
vim /usr/local/nginx/html/index.php
[root@hosts-01/usr/local/nginx/html]# cat index.php 
<?php
       phpinfo();
?>
[root@hosts-01/usr/local/nginx/html]# 

# 重启nginx 服务
/usr/local/nginx/sbin/nginx

浏览器输入10.0.0.5访问测试

七、ansible调优

7.1 ansible配置文件详解
# Ansible默认配置文件为/etc/ansible/ansible.cfg,配置文件中可以对ansible进行各项参数的调整,包括并发线程、用户、模块路径、配置优化等,如下为Ansible.cfg常用参数详解:

[defaults]   								通用默认配置段;
inventory      = /etc/ansible/hosts     	    被控端IP或者DNS列表;
library        = /usr/share/my_modules/ 	    Ansible默认搜寻模块的位置;
remote_tmp     = $HOME/.ansible/tmp       Ansible远程执行临时文件;
pattern        = *    				    对所有主机通信;
forks          = 5    					并行进程数;
poll_interval  = 15    					    回频率或轮训间隔时间;
sudo_user      = root   					sudo远程执行用户名;
ask_sudo_pass = True   					使用sudo,是否需要输入密码;
ask_pass      = True    					是否需要输入密码;
transport      = smart   				    通信机制;
remote_port    = 22    					远程SSH端口;
module_lang    = C   					模块和系统之间通信的语言;
gathering = implicit   					    控制默认facts收集(远程系统变量);
roles_path= /etc/ansible/roles 			    用于playbook搜索Ansible roles;
host_key_checking = False    				检查远程主机密钥;
#sudo_exe = sudo     					    sudo远程执行命令;
#sudo_flags = -H							传递sudo之外的参数;
timeout = 10								SSH超时时间;
remote_user = root   					    远程登陆用户名;
log_path = /var/log/ansible.log     		    日志文件存放路径;
module_name = command 				    Ansible命令执行默认的模块;
#executable = /bin/sh     				    执行的Shell环境,用户Shell模块;
#hash_behaviour = replace    				特定的优先级覆盖变量;
#jinja2_extensions	    				    允许开启Jinja2拓展模块;
#private_key_file = /path/to/file       	    私钥文件存储位置;
#display_skipped_hosts = True     			显示任何跳过任务的状态;
#system_warnings = True    				禁用系统运行ansible潜在问题警告;
#deprecation_warnings = True 				Playbook输出禁用“不建议使用”警告;
#command_warnings = False    			    command模块Ansible默认发出警告;
#nocolor = 1  							输出带上颜色区别,开启/关闭:0/1; 
pipelining = False							开启pipe SSH通道优化;
[accelerate]								accelerate缓存加速。
accelerate_port = 5099
accelerate_timeout = 30
accelerate_connect_timeout = 5.0
accelerate_daemon_timeout = 30
accelerate_multi_key = yes
7.2 ansible常见优化介绍
7.2.1 关闭ssh密钥检测
# 在ansible 配置文件中加入以下代码:
host_key_checking = False
7.2.2 openssh连接优化

关闭DNS解析

# 使用OpenSSH服务时,默认服务器端配置文件UseDNS=YES状态,该选项会导致服务器根据客户端的IP地址进行DNS PTR反向解析,得到客户端的主机名,然后根据获取到的主机名进行DNS正向A记录查询,并验证该IP是否与原始IP一致。关闭DNS解析

sed  -i  '/^GSSAPI/s/yes/no/g;/UseDNS/d;/Protocol/aUseDNS no' /etc/ssh/sshd_config
/etc/init.d/sshd restart
7.2.3 加速ansible优化

SSH pipelining 加速Ansible

# SSH pipelining是一个加速 Ansible 执行速度的简单方法,SSH pipelining 默认是关闭的,关闭是为了兼容不同的 sudo 配置,主要是requiretty 选项。
如果不使用Sudo建议开启该选项,打开此选项可以减少Ansible 执行没有文件传输时,SSH在被控机器上执行任务的连接数。使用Sudo操作的时候, 必须在所有被管理的主机上将配置文件/etc/sudoers中requiretty选项禁用。


sed    -i    '/^pipelining/s/False/True/g'    /etc/ansible/ansible.cfg
  • 7
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值