文章目录
-
- [1. Ansible 概述和运行机制](#1. Ansible 概述和运行机制)
-
- [1.1 Ansible 概述](#1.1 Ansible 概述)
- [1.2 Ansible 工作机制](#1.2 Ansible 工作机制)
- [1.3 Ansible 角色 (Role)](#1.3 Ansible 角色 (Role))
- [2. Ansible 环境安装部署](#2. Ansible 环境安装部署)
- [3. Ansible 基础命令及模块操作](#3. Ansible 基础命令及模块操作)
-
- 命令格式
- 常用模块示例
- [3.1 **command 模块**](#3.1 command 模块)
- [3.2 **shell 模块**](#3.2 shell 模块)
- [3.3 **cron 模块**](#3.3 cron 模块)
- [3.4 **user 模块**](#3.4 user 模块)
- [**3.5 group 模块**](#3.5 group 模块)
- [**3.6 copy 模块**](#3.6 copy 模块)
- [**3.7 file 模块**](#3.7 file 模块)
- [**3.8 hostname 模块**](#3.8 hostname 模块)
- [3.9 **ping 模块**](#3.9 ping 模块)
- [3.10 **yum 模块**](#3.10 yum 模块)
- [3.11 service/systemd 模块](#3.11 service/systemd 模块)
- [3.12 script 模块](#3.12 script 模块)
- [3.13 setup 模块](#3.13 setup 模块)
- [4. Inventory 主机清单与变量配置](#4. Inventory 主机清单与变量配置)
1. Ansible 概述和运行机制
1.1 Ansible 概述
Ansible 是一款面向类 Unix 系统的自由开源配置和自动化工具,由 Python 编写。与 SaltStack、Puppet、Chef 相似,但具有以下优势:
- 无需在被管理节点安装客户端,轻量级。
- 通过 SSH 协议与节点通信。
- 使用 YAML 和 Jinja2 模板语言进行配置和自动化任务编排。
官方网站: https://www.ansible.com/
行业事件:
- 2015 年 10 月,红帽(Red Hat)收购 Ansible,交易金额约 1--1.5 亿美元。
- Ansible 成立于 2013 年,总部位于北卡罗来纳州达勒姆,联合创始人 aïd Ziouani 与 Todd Barr 均为红帽前员工。
Ansible 特点:
- 部署简单,管理端安装即可,被控端无需操作;
- 默认使用 SSH 协议管理设备;
- 集中化管理,支持主从模式;
- 配置简洁、功能强大、扩展性高;
- 支持 API 和自定义模块,可通过 Python 扩展;
- Playbook 可实现复杂任务配置和状态管理;
- 对云计算和大数据平台支持良好。
1.2 Ansible 工作机制
Ansible 通过 SSH 将模块推送到被管理节点执行,执行完后自动删除。可结合 SVN 等工具管理自定义模块及任务编排。
Ansible 核心组成:
- Ansible:核心引擎
- Modules:内置核心模块和自定义模块
- Plugins:补充模块功能,如连接插件、邮件插件等
- Playbooks:剧本,定义多任务操作
- Inventory:主机清单
1.3 Ansible 角色 (Role)
随着数据中心环境复杂化,Playbook 会变得庞大且难以维护。角色提供了对复杂任务的模块化管理:
- 将任务组织为独立、可复用的剧本和文件
- 提供从外部加载任务、处理程序、变量的机制
- 可关联静态文件和模板
- 满足通用需求,可重复使用
- 严格的目录结构要求
2. Ansible 环境安装部署
环境示例:
类型 | IP |
---|---|
管理端 | 192.168.10.23 |
被管理端 | 192.168.10.14 |
被管理端 | 192.168.10.15 |
管理端安装 Ansible:
bash
yum install -y epel-release # 安装 EPEL 源
yum install -y ansible
目录结构:
tree /etc/ansible/
├── ansible.cfg # 配置文件,一般无需修改
├── hosts # 主机清单
└── roles/ # 公共角色目录
配置主机清单:
ini
vim /etc/ansible/hosts
取消注释或者自己加
[webservers] #配置组名 可以自定义
192.168.10.14 #组里包含的被管理的主机IP地址或主机名(主机名需要先修改/etc/hosts文件)
[dbservers] #配置组名 可以自定义
192.168.10.15
配置免密 SSH 登录:
bash
在ansible上生成
ssh-keygen -t rsa # 生成密钥
sshpass -p '123456' ssh-copy-id root@192.168.10.14
sshpass -p '123456' ssh-copy-id root@192.168.10.15
[root@zk01 ansible]# ssh-keygen -t rsa
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:pdbCbdmgDUQxq6U05KQfe+/5pohIqe3oRN3JXh8YD84 root@zk01
The key's randomart image is:
+---[RSA 2048]----+
| o.=. |
| = . o |
| . = * o |
| . = % & + |
| . . O E O . |
| . o + = . |
| . o . o |
| . = . . o .. |
| .+.+ . . ++. |
+----[SHA256]-----+
[root@zk01 ansible]# sshpass -p 'root' ssh-copy-id root@192.168.10.9
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
[root@zk01 ansible]# sshpass -p 'root' ssh-copy-id root@192.168.10.10
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
如果这种情况,说明不行,那就手动添加
[root@zk01 ansible]# ssh-copy-id root@192.168.10.9
/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.10.9's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.10.9'"
and check to make sure that only the key(s) you wanted were added.
[root@zk01 ansible]# ssh-copy-id root@192.168.10.10
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.10.10 (192.168.10.10)' can't be established.
ECDSA key fingerprint is SHA256:y/H/kgBGYCETCe4waV/f/JKnPg8atzVnwaTbHemM1KQ.
ECDSA key fingerprint is MD5:06:aa:d9:6b:86:dd:51:60:f2:ec:5e:5b:5b:b2:9c:3a.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.10.10's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.10.10'"
and check to make sure that only the key(s) you wanted were added.
3. Ansible 基础命令及模块操作
命令格式
bash
ansible <组名> -m <模块> -a <参数>
常用模块示例
3.1 command 模块
远程执行命令,不支持管道/重定向
bash
//在远程主机执行命令,不支持管道,重定向等shell的特性。
ansible-doc -s command #-s 列出指定模块的描述信息和操作动作
ansible 192.168.10.14 -m command -a 'date' #指定 ip 执行 date
ansible webservers -m command -a 'date' #指定组执行 date
ansible webservers -m command -a 'date' #指定组执行 date
ansible dbservers -m command -a 'date'
ansible all -m command -a 'date' #all 代表所有 hosts 主机
ansible all -a 'ls /' #如省略 -m 模块,则默认运行 command 模块
//常用的参数:
chdir:在远程主机上运行命令前提前进入目录
creates:判断指定文件是否存在,如果存在,不执行后面的操作
removes:判断指定文件是否存在,如果存在,执行后面的操作
ansible all -m command -a "chdir=/home ls ./"
3.2 shell 模块
支持管道和 shell 特性
bash
//在远程主机执行命令,相当于调用远程主机的shell进程,然后在该shell下打开一个子shell运行命令(支持管道符号等功能)
ansible-doc -s shell
ansible dbservers -m shell -a 'echo 123456 | passwd --stdin test'
ansible dbservers -m shell -a 'echo $(ifconfig ens33 | awk "NR==2 {print $2}") | cut -d " " -f2'
ansible dbservers -m shell -a 'echo $(ifconfig ens33 | awk "NR==2 {print \$2}")'
3.3 cron 模块
管理计划任务
bash
//在远程主机定义任务计划。其中有两种状态(state):present表示添加(可以省略),absent表示移除。
ansible-doc -s cron #按 q 退出
//常用的参数:
minute/hour/day/month/weekday:分/时/日/月/周
job:任务计划要执行的命令
name:任务计划的名称
ansible webservers -m cron -a 'minute="*/1" job="/bin/echo helloworld" name="test crontab"'
ansible webservers -a 'crontab -l'
ansible webservers -m cron -a 'name="test crontab" state=absent' #移除计划任务,假如该计划任务没有取名字,name=None即可,与手动执行crontab -e删除该任务的效果一致
3.4 user 模块
用户管理
bash
//用户管理的模块
ansible-doc -s user
//常用的参数:
name:用户名,必选参数
state=present|absent:创建账号或者删除账号,present表示创建,absent表示删除
system=yes|no:是否为系统账号
uid:用户uid
group:用户基本组
shell:默认使用的shell
move_home=yse|no:如果设置的家目录已经存在,是否将已经存在的家目录进行移动
password:用户的密码,建议使用加密后的字符串
comment:用户的注释信息
remove=yes|no:当state=absent时,是否删除用户的家目录
ansible dbservers -m user -a 'name="test01"' #创建用户test01
ansible dbservers -m command -a 'tail /etc/passwd'
ansible dbservers -m user -a 'name="test01" state=absent' #删除用户test01
3.5 group 模块
用户组管理
bash
//用户组管理的模块
ansible-doc -s group
ansible dbservers -m group -a 'name=mysql gid=306 system=yes' #创建mysql组
ansible dbservers -a 'tail /etc/group'
ansible dbservers -m user -a 'name=test01 uid=306 system=yes group=mysql' #将test01用户添加到mysql组中
ansible dbservers -a 'tail /etc/passwd'
ansible dbservers -a 'id test01'
3.6 copy 模块
复制文件或内容
bash
//用于复制指定主机文件到远程主机的
ansible-doc -s copy
//常用的参数:
dest:指出复制文件的目标及位置,使用绝对路径,如果是源目录,指目标也要是目录,如果目标文件已经存在会覆盖原有的内容
src:指出源文件的路径,可以使用相对路径或绝对路径,支持直接指定目录,如果源是目录则目标也要是目录,这个是ansible本机的路径
mode:指出复制时,目标文件的权限
owner:指出复制时,目标文件的属主
group:指出复制时,目标文件的属组
content:指出复制到目标主机上的内容,不能与src一起使用
ansible dbservers -m copy -a 'src=/etc/fstab dest=/opt/fstab.bak owner=root mode=640'
ansible dbservers -a 'ls -l /opt'
ansible dbservers -a 'cat /opt/fstab.bak'
ansible dbservers -m copy -a 'content="helloworld" dest=/opt/hello.txt' #将helloworld写入/opt/hello.txt文件中
ansible dbservers -a 'cat /opt/hello.txt'
3.7 file 模块
文件管理
bash
//设置文件属性
ansible-doc -s file
ansible dbservers -m file -a 'owner=test01 group=mysql mode=644 path=/opt/fstab.bak' #修改文件的属主属组权限等
ansible dbservers -m file -a 'path=/opt/fstab.link src=/opt/fstab.bak state=link' #设置/opt/fstab.link为/opt/fstab.bak的链接文件,必须要有源文件,前面的没有会自动创建,src必须在遥控的目标机器上有
ansible dbservers -m file -a "path=/opt/abc.txt state=touch" #创建一个文件
ansible dbservers -m file -a "path=/opt/abc.txt state=absent" #删除一个文件
3.8 hostname 模块
修改主机名
bash
//用于管理远程主机上的主机名
ansible dbservers -m hostname -a "name=mysql01"
3.9 ping 模块
检测主机连通性
bash
ansible all -m ping
3.10 yum 模块
管理软件包
bash
//在远程主机上安装与卸载软件包
ansible-doc -s yum
ansible webservers -m yum -a 'name=httpd' #安装服务
ansible webservers -m yum -a 'name=httpd state=absent' #卸载服务
3.11 service/systemd 模块
服务管理
bash
//用于管理远程主机上的管理服务的运行状态
ansible-doc -s service
//常用的参数:
name:被管理的服务名称
state=started|stopped|restarted:动作包含启动关闭或者重启
enabled=yes|no:表示是否设置该服务开机自启
runlevel:如果设定了enabled开机自启去,则要定义在哪些运行目标下自启动
ansible webservers -a 'systemctl status httpd' #查看web服务器httpd运行状态
ansible webservers -m service -a 'enabled=true name=httpd state=started' #启动httpd服务
3.12 script 模块
执行本地脚本
bash
//实现远程批量运行本地的 shell 脚本
ansible-doc -s script
vim test.sh
#!/bin/bash
echo "hello ansible from script" > /opt/script.txt
chmod +x test.sh
ansible webservers -m script -a 'test.sh'
ansible webservers -a 'cat /opt/script.txt'
script 模块的作用是在控制节点(本机)读取脚本文件,将其传输到目标节点,然后在目标节点上执行该脚本,并返回执行结果
3.13 setup 模块
收集节点信息
bash
//facts 组件是用来收集被管理节点信息的,使用 setup 模块可以获取这些信息
ansible-doc -s setup
ansible webservers -m setup #获取mysql组主机的facts信息
ansible dbservers -m setup -a 'filter=*ipv4' #使用filter可以筛选指定的facts信息
# 内存信息
ansible all -m setup -a "filter=ansible_memory_mb*"
# 具体内存信息
ansible all -m setup -a "filter=ansible_memory_mb"
ansible all -m setup -a "filter=ansible_swaptotal_mb"
# 磁盘信息
ansible all -m setup -a "filter=ansible_devices*"
ansible all -m setup -a "filter=ansible_mounts*"
# 具体磁盘信息
ansible all -m setup -a "filter=ansible_devices"
ansible all -m setup -a "filter=ansible_mounts"
ansible all -m setup -a "filter=ansible_device_links"
# 网络信息
ansible all -m setup -a "filter=ansible_*ipv4*"
ansible all -m setup -a "filter=ansible_default_ipv4*"
# 具体 IP 信息
ansible all -m setup -a "filter=ansible_default_ipv4"
ansible all -m setup -a "filter=ansible_all_ipv4_addresses"
4. Inventory 主机清单与变量配置
4.1 Inventory支持对主机进行分组
/Inventory支持对主机进行分组,每个组内可以定义多个主机,每个主机都可以定义在任何一个或多个主机组内。
//如果是名称类似的主机,可以使用列表的方式标识各个主机。
vim /etc/ansible/hosts
[webservers]
192.168.10.14:2222 #冒号后定义远程连接端口,默认是 ssh 的 22 端口
192.168.10.1[2:5]
[dbservers]
db-[a:f].example.org #支持匹配 a~f
4.2 常用 Inventory 变量
变量名 | 含义 |
---|---|
ansible_host | 节点 IP |
ansible_port | SSH 端口,默认 22 |
ansible_user | SSH 用户 |
ansible_password | SSH 密码(未使用密钥时) |
ansible_ssh_private_key_file | 私钥文件 |
ansible_become | 提升权限 |
ansible_become_method | 提升方式(sudo/su/runas) |
ansible_become_user | 提升为指定用户 |
ansible_become_password | 提升密码 |
基本示例:
(1)主机变量
ini
[webservers]
192.168.10.14 ansible_port=22 ansible_user=root ansible_password=abc1234
这个root和abc1234都是14主机的用户名和密码
如果
192.168.10.14 | FAILED | rc=-1 >>
Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host.
那就手动
ssh root@192.168.10.14 连接一下
(2)组变量
[webservers:vars]
ansible_user=root
ansible_password=abc1234
[all:vars]
ansible_port=22
(3) 组嵌套
ini
[nginx]
192.168.10.20
192.168.10.21
192.168.10.22
[apache]
192.168.10.30
192.168.10.31
192.168.10.32
192.168.10.33
[webs:children]
nginx
apache
使用所有主机的时候
示例:
ansible webs -m yum -a "name=wget state=present"