Linux进阶:自动化运维之ANSIBLE(一)

运维自动化发展历程

1、本地部署(On-Premiss) 部署硬件+软件+操作系统+环境+服务
2、基础设施即服务(Iaas) 相当于只准备硬件
3、平台即服务(Paas) 相当于只准备服务
4、软件即服务(SaaS) 直接使用

企业实际应用场景分析

1、Dev开发环境

使用者:程序员
功能:程序员开发软件,测试BUG的环境
管理者:程序员

测试环境
使用者:QA测试工程师
功能:测试经过Dev环境测试通过的软件的功能
管理者:运维
说明:测试环境往往有多套,测试环境满足测试功能即可,不宜过多
1、测试人员希望测试环境有多套,公司的产品多产品线并发,即多个版本,意味着多个版本同步测试
2、通常测试环境有多少套和产品线数量保持一样

2、发布环境:代码发布机,有些公司为堡垒机(安全屏障)

使用者:运维
功能:发布代码至生产环境
管理者:运维(有经验)
发布机:往往需要有2台(主备)

3、生产环境

使用者:运维,少数情况开放权限给核心开发人员,极少数公司将权限完全开放给开发人员并其维护
功能:对用户提供公司产品的服务
管理者:只能是运维
生产环境服务器数量:一般比较多,且应用非常重要。往往需要自动工具协助部署配置应用

4、灰度环境(生产环境的一部分)

使用者:运维
功能:在全量发布代码前将代码的功能面向少量精准用户发布的环境,可基于主机或用户执行灰度发布
案例:共100台生产服务器,先发布其中的10台服务器,这10台服务器就是灰度服务器
管理者:运维
灰度环境:往往该版本功能变更较大,为保险起见特意先让一部分用户优化体验该功能,待这部分用户使用没有重大问题的时候,再全量发布至所有服务器

程序发布

1、程序发布要求:

不能导致系统故障或造成系统完全不可用
不能影响用户体验

2、预发布验证:

新版本的代码先发布到服务器(跟线上环境配置完全相同,只是未接入到调度器)

3、灰度发布:

基于主机,用户,业务

4、发布路径:放在同一个目录,通常用软连接直接指向新版本

/webapp/tuangou
/webapp/tuangou-1.1
/webapp/tuangou-1.2

5、发布过程:

在调度器上下线一批主机(标记为maintanance状态) -->
关闭服务 --> 
部署新版本的应用程序 -->
启动服务 -->
在调度器上启用这一批服务器

自动化灰度发布:脚本、发布平台

自动化运维应用场景

文件传输
应用部署
配置管理
任务流编排

常用的自动化运维工具

Ansible:python,Agentless,中小型应用环境
分为控制端,客户端。借助于ssh协议,可基于key,无代理,管理中小型

Saltstack:python,一般需部署agent,执行效率更高
被管理端需安装软件,需代理程序

ansible

创始人,Michael DeHaan( Cobbler 与 Func 的作者)
2012-03-09,发布0.0.1版,红帽收购
2015-10-17,Red Hat宣布收购 1.5亿美金

特性

模块化:调用特定的模块,完成特定任务
有Paramiko,PyYAML,Jinja2(模板语言)三个关键模块
支持自定义模块
基于Python语言实现
部署简单,基于python和SSH(默认已安装),agentless
安全,基于OpenSSH
支持playbook编排任务
幂等性:一个任务执行1遍和执行n遍效果一样,不因重复执行带来意外情况
无需代理不依赖PKI(无需ssl)
可使用任何编程语言写模块
YAML格式,编排任务,支持丰富的数据结构
较强大的多层解决方案

利用ansible实现管理的方式:
Ad-Hoc :ansible命令,主要用于临时命令使用场景
Ansible-playbook : 主要用于长期规划好的,大型项目的场景,需要有前提的规划

注意事项

执行ansible的主机一般称为主控端,中控,master或堡垒机
主控端Python版本需要2.6或以上
被控端Python版本小于2.4需要安装python-simplejson
被控端如开启SELinux需要安装libselinux-python
windows不能做为主控端

配置文件

1./etc/ansible/ansible.cfg 主配置文件,  
如下可变动,其他不用变动
#log_path = /var/log/ansible.log  生成日志文件
#host_key_checking = False        忽略登录yes no

Ansible 配置文件/etc/ansible/ansible.cfg (一般保持默认)
[defaults]
#inventory = /etc/ansible/hosts # 主机列表配置文件
#library = /usr/share/my_modules/ # 库文件存放目录
#remote_tmp = $HOME/.ansible/tmp #临时py命令文件存放在远程主机目录
#local_tmp = $HOME/.ansible/tmp # 本机的临时命令执行目录
#forks = 5 # 默认并发数
#sudo_user = root # 默认sudo 用户
#ask_sudo_pass = True #每次执行ansible命令是否询问ssh密码
#ask_pass = True
#remote_port = 22
#host_key_checking = False # 检查对应服务器的host_key,建议取消注释
#log_path=/var/log/ansible.log #日志文件

2./etc/ansible/hosts 主机清单
3./etc/ansible/roles/ 存放角色的目录

程序
/usr/bin/ansible 主程序,临时命令执行工具
/usr/bin/ansible-doc 查看配置文档,模块功能查看工具
/usr/bin/ansible-galaxy 下载/上传优秀代码或Roles模块的官网平台
/usr/bin/ansible-playbook 定制自动化任务,编排剧本工具/usr/bin/ansible-pull 远程执行命令的工具
/usr/bin/ansible-vault 文件加密工具
/usr/bin/ansible-console 基于Console界面与用户交互的执行工具

ansible-doc: 显示模块帮助

ansible-doc 
-a 显示所有模块的文档
-l, --list 列出可用模块
-s, --snippet显示指定模块的playbook片段
示例:
ansible-doc –l 列出所有模块
ansible-doc ping 查看指定模块帮助用法
ansible-doc –s ping 查看指定模块帮助用法

ansible命令执行过程

1. 加载自己的配置文件 默认/etc/ansible/ansible.cfg
2. 加载自己对应的模块文件,如command
3. 通过ansible将模块或命令生成对应的临时py文件,并将该 文件传输至远程服务器的对应执行用户$HOME/.ansible/tmp/ansible-tmp-数字/XXX.PY文件
4. 给文件+x执行
5. 执行并返回结果
6. 删除临时py文件,sleep 0退出

执行状态:
绿色:执行成功并且不需要做改变的操作
黄色:执行成功并且对目标主机做变更
红色:执行失败

如何使用ansible

1、安装ansible---基于epel源

[root@centos7 yum.repos.d]#yum install ansible

2、配置主机清单 (非默认ssh协议,后面跟端口号)

[root@centos7 ~]#vim /etc/ansible/hosts
# Ex 2: A collection of hosts belonging to the 'webservers' group

## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110

# If you have multiple hosts following a pattern you can specify
# them like this:

## www[001:006].example.com

# Ex 3: A collection of database servers in the 'dbservers' group

## [dbservers]
## 
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57

# Here's another example of host ranges, this time there are no
# leading 0s:

## db-[99:101]-node.example.com               
[websrv]                                
192.168.32.17
192.168.32.6
[appsrv]
192.168.32.[1:2]7

3、基本用法
ansible [-m module_name] [-a args]
跟主机ip或分组名(支持通配符)+模块名+模块参数 +-a+需要执行的命令

--version 显示版本
-m module 指定模块,默认为command
-v 详细过程 –vv -vvv更详细
--list-hosts 显示主机列表,可简写 --list
-k, --ask-pass 提示输入ssh连接密码,默认Key验证
-K, --ask-become-pass 提示输入sudo时的口令
-C, --check 检查,并不执行
-T, --timeout=TIMEOUT 执行命令的超时时间,默认10s
-u, --user=REMOTE_USER 执行远程执行的用户
-b, --become 代替旧版的sudo 切换


直接输入ip地址     基于密码验证
[root@centos7 ~]#ansible 192.168.32.6 -m ping -k
SSH password: 
192.168.32.6 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
直接输入组名       基于密码验证
[root@centos7 ~]#ansible websrv -m ping -k            
SSH password: 
192.168.32.6 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.32.17 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
通配符
ansible "*" -m ping
ansible 192.168.1.* -m ping
ansible "*srv" -m ping

逻辑或
ansible "websrvs:appsrvs" -m ping
ansible "192.168.1.10:192.168.1.20" -m ping

逻辑与
ansible "websrv:&dbsrv" –m ping
在websrvs组并且在dbsrvs组中的主机

逻辑非
ansible 'websrv:!dbsrv' –m ping
在websrvs组,但不在dbsrvs组中的主机
注意:此处为单引号

综合逻辑
ansible 'websrv:dbsrv:&appsrv:!ftpsrv' –m ping

正则表达式
ansible "websrv.dadda.com:&dbsrv.dadda.com" –m ping
转换:~ 代表后面要跟的正则表达式
ansible "~(web|db).*\.dadda\.com" –m ping

注:多台机器管理基于key验证
如何基于key验证:

[root@centos7 ~]#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:nIQnThJNBzY0pm14bxLNDjaKvnY2CU9NYYkdFjocVgI root@centos7
The key's randomart image is:
+---[RSA 2048]----+
|  E.=B&=.        |
|   o.%*B         |
|    B.%.=        |
|   . X.@ .       |
|  . .oo S        |
| .. . .o         |
|  .+ .           |
|  ..*            |
| ..o .           |
+----[SHA256]-----+
[root@centos7 ~]#cd .ssh
[root@centos7 .ssh]#ls
id_rsa  id_rsa.pub  known_hosts
[root@centos7 .ssh]#ssh-copy-id 192.168.32.6    多台可利用脚本
/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
[email protected]'s password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '192.168.32.6'"
and check to make sure that only the key(s) you wanted were added.
[root@centos7 .ssh]#ssh 192.168.32.6
Last login: Sat Sep 22 22:17:40 2018 from 192.168.32.27
[root@centos7 .ssh]#ansible all -m ping
192.168.32.17 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.32.6 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.32.27 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

使用举例

1、以本机shine用户执行ping存活检测
注意:不是基于key的验证了需输入shine的密码,需带选项-k

[root@centos7 ~]#ansible all -m ping -u shine -k
SSH password:
192.168.32.17 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.32.27 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.32.6 | UNREACHABLE! => {
"changed": false,
"msg": "Authentication failure.",
"unreachable": true
}

2、以shine sudo至root执行ping存活检测
注意:sudo需带选项-b -K ,sudo免口令可不加-K

[root@centos7 ~]#ansible 192.168.32.17 -m ping -u shine -b -K -k
SUDO password:
192.168.32.17 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\r\n",
"unreachable": true
}
失败是因为未做sudo授权

授权:切换到(最简单的是加到配置文件组内)
```bash
[root@centos7-17 ~]#vim /etc/sudoers
...
## Allows people in group wheel to run all commands
#%wheel ALL=(ALL)       ALL              需输口令
## Same thing without a password
 %wheel ALL=(ALL)       NOPASSWD: ALL    此行免输口令
...

[root@centos7-17 ~]#getent passwd shine
shine:x:1000:1000:Shine:/home/shine:/bin/bash    
[root@centos7-17 ~]#id shine
uid=1000(shine) gid=1000(shine) groups=1000(shine)

[root@centos7-17 ~]#usermod -aG wheel shine
[root@centos7 ~]#ansible 192.168.32.17 -m ping -u shine -b -K -k   
SSH password: 
SUDO password[defaults to SSH password]: 
192.168.32.17 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

[root@centos7 ~]#ansible 192.168.32.17 -m ping -u shine -b  -k  
SSH password: 
192.168.32.17 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

3、以shine sudo至root用户执行ls
sudo授权过可以

[root@centos7 ~]#ansible 192.168.32.17 -m command -u shine --become-user=root -a 'ls /root' -b -k -K   
SSH password: 
SUDO password[defaults to SSH password]: 
192.168.32.17 | SUCCESS | rc=0 >>
anaconda-ks.cfg
Desktop
Documents
Downloads
initial-setup-ks.cfg
Music
Pictures
Public
Templates
Videos

没有sudo授权不可以

[root@centos7-17 ~]#usermod -G '' shine
[root@centos7-17 ~]#id shine
uid=1000(shine) gid=1000(shine) groups=1000(shine)

[root@centos7 ~]#ansible 192.168.32.17 -m command -u shine --become-user=root -a 'ls /root' -b -k -K
SSH password: 
SUDO password[defaults to SSH password]: 
192.168.32.17 | FAILED! => {
    "changed": false, 
    "module_stderr": "Shared connection to 192.168.32.17 closed.\r\n", 
    "module_stdout": "\r\nshine is not in the sudoers file.  This incident will be reported.\r\n", 
    "msg": "MODULE FAILURE", 
    "rc": 1
}

最好还是用root身份基于key最方便

[root@centos7 ~]#ansible 192.168.32.17 -m command -a 'ls /root'
192.168.32.17 | SUCCESS | rc=0 >>
anaconda-ks.cfg
Desktop
Documents
Downloads
initial-setup-ks.cfg
Music
Pictures
Public
Templates
Videos

常用模块

1、Command:在远程主机执行命令,默认模块,可忽略-m选项

[root@centos7 ~]#ansible all -a 'useradd test' 同时创建
192.168.32.17 | SUCCESS | rc=0 >>


192.168.32.27 | SUCCESS | rc=0 >>


192.168.32.6 | SUCCESS | rc=0 >>

[root@centos7 ~]#ansible all -a 'getent passwd test' 同时查看
192.168.32.6 | SUCCESS | rc=0 >>
test:x:502:502::/home/test:/bin/bash

192.168.32.17 | SUCCESS | rc=0 >>
test:x:1001:1001::/home/test:/bin/bash

192.168.32.27 | SUCCESS | rc=0 >>
test:x:1001:1001::/home/test:/bin/bash

[root@centos7 ~]#ansible all -a 'userdel -r test' 同时删除账户及家目录
192.168.32.17 | SUCCESS | rc=0 >>


192.168.32.27 | SUCCESS | rc=0 >>


192.168.32.6 | SUCCESS | rc=0 >>

此命令不支持 $VARNAME < > | ; & 等,用shell模块实现

2、Shell:和command相似,用shell执行命令

用command模块修改密码:只是输出内容
[root@centos7 ~]#ansible all -a 'echo dadda |passwd --stdin shine'         
192.168.32.6 | SUCCESS | rc=0 >>
dadda |passwd --stdin shine

192.168.32.17 | SUCCESS | rc=0 >>
dadda |passwd --stdin shine

192.168.32.27 | SUCCESS | rc=0 >>
dadda |passwd --stdin shine

用shell模块修改密码:成功
[root@centos7 ~]#ansible all -m shell -a 'echo dadda |passwd --stdin shine'  
192.168.32.17 | SUCCESS | rc=0 >>
Changing password for user shine.
passwd: all authentication tokens updated successfully.

192.168.32.27 | SUCCESS | rc=0 >>
Changing password for user shine.
passwd: all authentication tokens updated successfully.

192.168.32.6 | SUCCESS | rc=0 >>
Changing password for user shine.
passwd: all authentication tokens updated successfully.

更改默认command更换成shell

[root@centos7 ~]#vim /etc/ansible/ansible.cfg 
...
# default module name for /usr/bin/ansible
module_name = shell

[root@centos7 ~]#ansible all -a 'echo dadda |passwd --stdin shine'         
192.168.32.17 | SUCCESS | rc=0 >>
Changing password for user shine.
passwd: all authentication tokens updated successfully.

192.168.32.27 | SUCCESS | rc=0 >>
Changing password for user shine.
passwd: all authentication tokens updated successfully.

192.168.32.6 | SUCCESS | rc=0 >>
Changing password for user shine.
passwd: all authentication tokens updated successfully.

调用bash执行命令 类似 cat /tmp/stanley.md | awk -F‘|’ ‘{print $1,$2}’ &> /tmp/example.txt 这些复杂命令,即使使用shell也可能会失败,解决办法:写到脚本时,copy到远程,执行,再把需要的结果拉回执行命令的机器

3、Script:运行脚本
注意执行的是本机所在的脚本

[root@centos7 ~]#cat >test.sh
echo ansible
[root@centos7 ~]#cat test.sh 
echo ansible
[root@centos7 ~]#chmod +x test.sh 
[root@centos7 ~]#ansible 192.168.32.17 -m script -a '/root/test.sh' 
192.168.32.17 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.32.17 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.32.17 closed."
    ], 
    "stdout": "ansible\r\n", 
    "stdout_lines": [
        "ansible"
    ]

常用参数
creates 如文件存在,则不执行脚本

[root@centos7 ~]#ansible all -m script -a 'creates=/etc/fstab /root/test.sh' 
192.168.32.27 | SKIPPED
192.168.32.17 | SKIPPED
192.168.32.6 | SKIPPED

removes 如文件存在,则执行脚本

[root@centos7 ~]#ansible 192.168.32.17 -m script -a 'removes=/etc/fstab /root/test.sh' 
192.168.32.17 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.32.17 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.32.17 closed."
    ], 
    "stdout": "ansible\r\n", 
    "stdout_lines": [
        "ansible"
    ]
}

猜你喜欢

转载自blog.csdn.net/weixin_40001704/article/details/82819647
今日推荐