第一节:ansible入门

Ansible 学习

一、Ansible 概述

1.什么是Ansible

Ansible是一个自动化统一配置管理工具,自动化主要体现在Ansible集成了丰富模块以及功能组件,可以通过一个命令完成一系列的操作,进而能减少重复性的工作和维护成本,可以提高工作效率。

2.自动化工具

1.puppet 学习难,安装ruby环境难,没有远程执行功能
2.ansible 轻量级,大规模环境下只通过ssh会很慢,串行的
3.saltstack 一般选择salt会使用C/S结构的模式,salt-master和salt-minion,并行的,大规模批量操作的情况下,会比Ansible速度快一些,底层使用的是zero-MQ消息队列

3.自动化运维相较于手动运维

1.提高工作效率
2.提高了工作的准确度
3.减少人员成本
4.减少了重复的工作

4.Ansible的功能及优点

1.远程执行
批量执行远程命令,可以对多台主机进行远程操作

2.配置管理
批量配置软件服务,可以进行自动化方式配置,服务的统一配置管理,和启停

3.事件驱动
通过Ansible的模块,对服务进行不同的事件驱动
比如:
    1)修改配置后重启
    2)只修改配置文件,不重启
    3)修改配置文件后,重新加载
    4)远程启停服务管理

4.管理公有云
通过API接口的方式管理公有云,不过这方面做的不如saltstack.
saltstack本身可以通过saltcloud管理各大云厂商的云平台。

5.二次开发
因为语法是Python,所以便于运维进行二次开发。

6.任务编排
可以通过playbook的方式来统一管理服务,并且可以使用一条命令,实现一套架构的部署

7.跨平台,跨系统
几乎不受到平台和系统的限制,比如安装apache和启动服务

    在Ubuntu上安装apache服务名字叫apache2
    在CentOS上安装apache服务名字叫httpd

    在CentOS6上启动服务器使用命令:/etc/init.d/nginx start
    在CentOS7上启动服务器使用命令:systemctl start nginx

1608189257109

二、Ansible 构成

1.组成部分

1.连接插件connection plugins用于连接主机 用来连接被管理端
2.核心模块core modules连接主机实现操作, 它依赖于具体的模块来做具体的事情
3.自定义模块custom modules根据自己的需求编写具体的模块
4.插件plugins完成模块功能的补充
5.剧本playbookansible的配置文件,将多个任务定义在剧本中,由ansible自动执行
6.主机清单inventor定义ansible需要操作主机的范围

最重要的一点是 ansible是模块化的 它所有的操作都依赖于模块

1608189420746

2.Ansible执行流程

1.Ansible读取playbook剧本,剧本中会记录对哪些主机执行哪些任务。   #web 安装nginx
2.首先Ansible通过主机清单找到要执行的主机,然后调用具体的模块。    #web 是谁
3.其次Ansible会通过连接插件连接对应的主机并推送对应的任务列表。    #使用yum模块安装nginx
4.最后被管理的主机会将Ansible发送过来的任务解析为本地Shell命令执行。   #受控端执行yum install -y nginx

三、Ansible使用

1.环境准备

主机 外网IP 内网IP 身份
m01 10.0.0.61 172.16.1.61 控制端
web01 10.0.0.7 172.16.1.7 受控端
web02 10.0.0.8 172.16.1.8 受控端

2.控制端安装ansible

#1.安装epel源
[root@m01 ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo

#2.安装Ansible
[root@m01 ~]# yum install -y ansible

3.ansible参数

# ansible <host-pattern> [options]
#不常用参数
--version   #ansible版本信息
-v          #显示详细信息
-i          #主机清单文件路径,默认是在/etc/ansible/hosts
-k          #提示输入ssh密码,而不使用基于ssh的密钥认证
-C          #模拟执行测试,但不会真的执行
-T          #执行命令的超时

#常用参数
-m          #使用的模块名称,默认使用command模块
-a          #使用的模块参数,模块的具体动作
--syntax-check      #验证语法

[root@m01 ~]# ansible --version
ansible 2.9.15
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]

4.ansible配置文件

[root@m01 ~]# vim /etc/ansible/ansible.cfg
# nearly all parameters can be overridden in ansible-playbook
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first

[root@m01 ~]# rpm -ql ansible
[root@m01 ~]# zcat /usr/share/man/man1/ansible-config.1.gz

#要查看完整列表,请访问https://docs.ansibe.com/或使用ansibe-config命令。
For a full list check \fI\%https://docs.ansible.com/\fP\&. or use the \fIansible\-config\fP command.

#/etc/ansible/ansible.cfg 配置文件,如果存在则使用
/etc/ansible/ansible.cfg \-\- Config file, used if present

#~/.ansible.cfg 用户配置文件,覆盖默认配置(如果存在)
~/.ansible.cfg \-\- User config file, overrides the default config if present

#\&/ansible.cfg 本地配置文件(在当前工作目录中)假定为(aqproject-specific)(aq,如果存在,则重写其余文件)。
\&./ansible.cfg \-\- Local config file (in current working directory) assumed to be \(aqproject specific\(aq and overrides the rest if present.

#如上所述,ANSIBLE_CONFIG环境变量将覆盖所有其他环境变量。
As mentioned above, the ANSIBLE_CONFIG environment variable will override all others.

5.ansible配置文件解释

[root@m01 ~]# cat /etc/ansible/ansible.cfg 
#inventory      = /etc/ansible/hosts      #主机列表配置文件
#library        = /usr/share/my_modules/  #库文件存放目录
#remote_tmp     = ~/.ansible/tmp          #临时py文件存放在远程主机目录
#local_tmp      = ~/.ansible/tmp          #本机的临时执行目录
#forks          = 5                       #默认并发数
#sudo_user      = root                    #默认sudo用户
#ask_sudo_pass = True                     #每次执行是否询问sudo的ssh密码
#ask_pass      = True                     #每次执行是否询问ssh密码
#remote_port    = 22                      #远程主机端口
host_key_checking = False                 #跳过检查主机指纹
log_path = /var/log/ansible.log           #ansible日志

#普通用户提权操作
[privilege_escalation]
#become=True
#become_method=sudo
#become_user=root
#become_ask_pass=False 

四、主机清单配置

1.基于密码的方式

1)单主机配置

#方式一: ip + 端口 + 用户名 + 用户密码
[root@m01 ~]# vim /etc/ansible/hosts 
[web01]
10.0.0.7 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='1'
[web02]
10.0.0.8 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='1'

#测试
[root@m01 ~]# ansible web01 -m ping
10.0.0.7 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
#方式二: ip + 用户密码
[root@m01 ~]# vim /etc/ansible/hosts 
[web01]
10.0.0.7 ansible_ssh_pass='1'
[web02]
10.0.0.8 ansible_ssh_pass='1'

[root@m01 ~]# ansible web02 -m ping
10.0.0.8 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
#方式三: ip + 变量密码
[root@m01 ~]# vim /etc/ansible/hosts 
[web01]
10.0.0.7
[web02]
10.0.0.8 ansible_ssh_pass='1'

[web01:vars]
ansible_ssh_pass='1'

2)多主机配置

[root@m01 ~]# vim /etc/ansible/hosts 
[web_group]
10.0.0.7 ansible_ssh_pass='1'
10.0.0.8 ansible_ssh_pass='1'

[root@m01 ~]# ansible 'web_group' -m ping
10.0.0.8 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
10.0.0.7 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

2.基于秘钥的方式

1)生成密钥对

1.生成密钥对
[root@m01 ~]# ssh-keygen

2.推送公钥
[root@m01 ~]# ssh-copy-id 10.0.0.7
[root@m01 ~]# ssh-copy-id 10.0.0.8

2)配置主机清单

[root@m01 ~]# vim /etc/ansible/hosts 
[web_group]
10.0.0.7
10.0.0.8

3)修改hosts配置主机清单

#配置主机清单
[root@m01 ~]# vim /etc/ansible/hosts 
[web_group]
web01
web02

#配置hosts
[root@m01 ~]# vim /etc/hosts
10.0.0.7 web01
10.0.0.8 web02

#测试
[root@m01 ~]# ansible 'web_group' -m ping
web02 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
web01 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

3.定义整合组

1)定义整合组

[root@m01 ~]# vim /etc/ansible/hosts 
[web_group]
web01
web02
[nfs_server]
nfs ansible_ssh_pass='1'
[rsync_server]
backup ansible_ssh_pass='1'
[db_server]
db01 ansible_ssh_pass='1'
#定义整合组,下面包含多个组
[www:children]
web_group
nfs_server
rsync_server

#配置hosts
[root@m01 ~]# vim /etc/hosts
10.0.0.7 web01
10.0.0.8 web02
10.0.0.31 nfs
10.0.0.41 backup
10.0.0.51 db01

2)查看整合组下面的主机组

[root@m01 ~]# ansible www --list-host
  hosts (4):
    web01
    web02
    nfs
    backup

4.测试

#单主机
[root@m01 ~]# ansible 'web01' -m ping

#所有主机
[root@m01 ~]# ansible '*' -m ping

#所有主机
[root@m01 ~]# ansible 'all' -m ping

#主机组
[root@m01 ~]# ansible 'web_group' -m ping

#整合组
[root@m01 ~]# ansible 'www' -m ping

Ansible ad-hoc

一、ad-hoc概述

1.什么ad-hoc

ad-hoc简而言之就是"临时命令",执行完即结束,并不会保存

2.使用场景

比如在多台机器上查看某个进程是否启动,或拷贝指定文件到本地,等等
临时使用的命令,一次使用

3.ad-hoc模式的命令使用

1608196995680

[root@m01 ~]# ansible web01 -m command -a 'df -h'
web01 | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        18G  1.6G   17G   9% /
devtmpfs        476M     0  476M   0% /dev
tmpfs           487M     0  487M   0% /dev/shm
tmpfs           487M  7.7M  479M   2% /run
tmpfs           487M     0  487M   0% /sys/fs/cgroup
/dev/sda1      1014M  127M  888M  13% /boot
tmpfs            98M     0   98M   0% /run/user/0

[root@m01 ~]# ansible web_group -m command -a 'free -m'
web01 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:            972         128         481           7         362         658
Swap:          1023           0        1023
web02 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:            972         111         551           7         309         691
Swap:          1023           0        1023

4.ad-hoc结果返回颜色

绿色: 代表被管理端主机没有被修改
黄色: 代表被管理端主机发现变更
红色: 代表出现了故障,注意查看提示

5.ad-hoc常用模块

command             # 执行shell命令(不支持管道等特殊字符)
shell               # 执行shell命令
scripts             # 执行shell脚本
yum_repository      # 配置yum仓库
yum                 # 安装软件
copy                # 变更配置文件
file                # 建立目录或文件
service             # 启动与停止服务
systemd             # 启动与停止服务
mount               # 挂载设备
cron                # 定时任务
get_url             #下载软件
firewalld           #防火墙
selinux             #selinux
setup               #获取主机信息

6.ansible帮助

#1.查看所有模块
[root@m01 ~]# ansible-doc -l

#2.查看指定模块的用法
[root@m01 ~]# ansible-doc yum

#3.查看模块参数
[root@m01 ~]# ansible-doc -s yum

二、Ansible 命令模块

1.command 模块(不识别特殊符号)

#不加参数时默认使用的就是 command 模块
[root@m01 ~]# ansible web01 -m command -a 'free -m'
web01 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:            972         128         480           7         363         658
Swap:          1023           0        1023

#不识别特殊符号
[root@m01 ~]# ansible web01 -m command -a 'ps -ef | grep nginx'
web01 | FAILED | rc=1 >>
error: garbage option
Usage:
 ps [options]

 Try 'ps --help <simple|list|output|threads|misc|all>'
  or 'ps --help <s|l|o|t|m|a>'
 for additional help text.
For more details see ps(1).non-zero return code

2.shell 模块

#支持特殊符号
[root@m01 ~]# ansible web01 -m shell -a 'ps -ef | grep nginx'
web01 | CHANGED | rc=0 >>
root      12680  12675  0 17:51 pts/0    00:00:00 /bin/sh -c ps -ef | grep nginx
root      12682  12680  0 17:51 pts/0    00:00:00 grep nginx

#获取主机信息,使用变量加转义符号
[root@m01 ~]# ansible web01 -m shell -a "ifconfig eth0 | awk 'NR==2 {print $2}'"
web01 | CHANGED | rc=0 >>
        inet 10.0.0.7  netmask 255.255.255.0  broadcast 10.0.0.255

[root@m01 ~]# ansible web01 -m shell -a "ifconfig eth0 | awk 'NR==2 {print \$2}'"
web01 | CHANGED | rc=0 >>
10.0.0.7
[root@m01 ~]# 
上一篇
下一篇
Copyright © 2022 Egon的技术星球 egonlin.com 版权所有 帮助IT小伙伴学到真正的技术