运维笔记 - Ansible - 多机管理与 Apache2 批量下发

Ansible 实验环境总览

目录


环境说明

1
2
3
4
5
6
管理机
- Manage-ansible:Ubuntu 22.04

受管控机器
- 192.168.246.138:Ubuntu 22.04
- 192.168.246.145:Ubuntu 22.04

说明:下文示例中的 inventory 组名请根据实际环境替换。本文统一使用 webservers 组。


ansible-doc 帮助输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
usage: ansible-doc [-h] [--version] [-v] [-M MODULE_PATH] [--playbook-dir BASEDIR]
[-t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,vars,module,strategy}]
[-j] [-F | -l | -s | --metadata-dump]
[plugin ...]

插件文档工具

位置参数:
plugin 插件

选项:
--metadata-dump **仅供内部测试使用** 导出所有插件的 JSON 元数据。
--playbook-dir BASEDIR
由于此工具不使用 playbook,可将此作为 playbook 目录的替代。这会设置许多功能的相对路径,包括 roles/、group_vars/ 等。
--version 显示程序版本号、配置文件位置、已配置的模块搜索路径、模块位置、可执行文件位置并退出
-F, --list_files 显示插件名称及其源文件,但不显示摘要(隐含 --list)。提供的参数将用于过滤,可以是命名空间或完整集合名称。
-M MODULE_PATH, --module-path MODULE_PATH
将冒号分隔的路径前缀添加到模块库
(默认值=~/.ansible/plugins/modules:/usr/share/ansible/plugins/modules)
-h, --help 显示此帮助消息并退出
-j, --json 将输出更改为 json 格式。
-l, --list 列出可用插件。提供的参数将用于过滤,可以是命名空间或完整集合名称。
-s, --snippet 显示指定插件的 playbook 片段
-t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,vars,module,strategy}, --type {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,vars,module,strategy}
选择插件类型(默认为 "module")。可用插件类型为:('become',
'cache', 'callback', 'cliconf', 'connection', 'httpapi', 'inventory', 'lookup', 'netconf',
'shell', 'vars', 'module', 'strategy')
-v, --verbose 详细模式(-vvv 更详细,-vvvv 启用连接调试)

有关 Ansible CLI 选项,请参阅 man 手册页;有关教程,请访问:
https://docs.ansible.com

通过 Ansible 下发 Apache2

第一步:编写主机清单

在安装 Ansible 的 Ubuntu 管理机上创建工作目录,并编写 inventory 文件:

1
2
3
mkdir -p ~/ansible-apache
cd ~/ansible-apache
vim inventory.ini

写入以下内容,将两台机器放入 webservers 组:

1
2
3
4
5
6
7
8
9
[webservers]
192.168.246.138
192.168.246.145

[webservers:vars]
ansible_user=root
ansible_connection=ssh
# 如果已配置 SSH 免密登录,无需设置 ansible_password
# ansible_password=your_password

如果使用 root 用户且已配置 SSH 免密登录,Ansible 会默认使用 SSH 密钥认证,不需要设置 ansible_password。


第二步:测试连通性

正式安装前,先使用 ping 模块确认 Ansible 能连接两台机器:

1
ansible -i inventory.ini webservers -m ping

如果返回结果中每台机器都显示 "ping": "pong",说明 SSH 免密认证和 inventory 配置正确。

ping 模块连通性测试


第三步:编写 Playbook 安装 Apache2

创建 install_apache.yml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
---
- name: Install and start Apache2 on Ubuntu
hosts: webservers
become: yes
tasks:
- name: Update apt cache
apt:
update_cache: yes
cache_valid_time: 3600 # 一小时内不重复更新

- name: Install Apache2 package
apt:
name: apache2
state: present

- name: Ensure Apache2 service is running and enabled
service:
name: apache2
state: started
enabled: yes

关键点说明:

  • become: yes:显式声明提权,确保 apt 和 service 模块以最高权限运行。
  • apt 模块:name: apache2 和 state: present 是安装软件包的标准写法。
  • service 模块:state: started 确保服务立即启动,enabled: yes 确保开机自启。

第四步:执行 Playbook

1
ansible-playbook -i inventory.ini install_apache.yml

执行过程中会显示每个任务的状态,例如 ok、changed、failed。如果一切顺利,最后会显示 PLAY RECAP,两台机器的 changed 计数应不为 0,表示发生了变更。


第五步:验证安装结果

方式一:使用 Ansible 的 command 模块远程检查

1
ansible -i inventory.ini webservers -m command -a "systemctl is-active apache2"

预期每台机器都返回:

1
active

方式二:使用 curl 测试

在控制节点或任意能访问目标机器的设备上执行:

1
2
curl http://192.168.246.138
curl http://192.168.246.145

如果返回 Apache2 默认欢迎页面的 HTML 内容,说明 Web 服务已正常运行。


Ansible 常用模块

一、ping 模块

使用 ping 模块测试主机连通性:

1
ansible -i inventory.ini webservers -m ping

参数说明:

  • -i:指定 inventory 文件。
  • -m:指定要使用的模块。

ping 模块输出


二、command 模块

command 模块用于在远程主机上执行命令,并将结果返回本机。

1
ansible -i inventory.ini webservers -m command -a "ip a"

command 模块执行 ip a

命令模块接受命令名称,后面是空格分隔的参数列表。给定命令会在所有选定节点上执行。

注意:command 模块不会通过 shell 处理命令,因此 $HOME、<、>、|、;、& 等 shell 特性不可用。如果需要管道等 shell 功能,请使用 shell 模块。

常用参数:

参数 说明
chdir 执行命令前先切换到指定目录
executable 指定执行命令的 shell,需使用绝对路径
free_form 要执行的 Linux 指令,一般使用 -a 参数代替
creates 指定文件名,文件存在时不执行命令
removes 指定文件名,文件不存在时不执行命令

示例:切换目录后执行 ls:

1
ansible -i inventory.ini webservers -m command -a "chdir=/etc/ ls"

command 模块 chdir 示例

示例:判断 /etc/flag 是否存在,不存在时执行 ls:

1
ansible -i inventory.ini webservers -m command -a "creates=/etc/flag ls"

command 模块 creates 参数示例


三、shell 模块

shell 模块在远程主机上调用 shell 解释器运行命令,支持管道等 shell 功能。

1
ansible -i inventory.ini webservers -m shell -a "cat /etc/passwd | grep 'root'"

shell 模块管道示例


四、file 模块

file 模块主要用于设置文件属性,例如创建文件、创建链接文件、删除文件等。

常用参数:

参数 说明
force 强制创建软链接,或在目标软链接已存在时先取消再创建。可选 yes / no
group 定义文件/目录的属组
owner 定义文件/目录的属主
path 定义文件/目录路径
recurse 递归设置文件属性,仅对目录有效
src 被链接的源文件路径,仅用于 state=link
dest 被链接到的路径,仅用于 state=link
mode 定义文件/目录权限
state 状态,常用值见下表

state 常用值:

值 说明
directory 目录不存在时创建目录
file 文件不存在时不会创建
link 创建软链接
hard 创建硬链接
touch 文件不存在时创建新文件;已存在时更新最后修改时间
absent 删除目录、文件或取消链接

示例:创建目录:

1
ansible -i inventory.ini webservers -m file -a "path=~/data/ state=directory"

五、fetch 模块

fetch 模块用于从远程主机获取文件并复制到本地。

常用参数:

参数 说明
src 远程主机上要拉取的文件,必须是文件而非目录
dest 本地保存路径

示例:

1
ansible -i inventory.ini webservers -m fetch -a "src=~/data/flag dest=~/data/"

fetch 模块拉取文件


六、apt / yum 模块

yum 模块适用于 RedHat 系列系统;本文环境为 Ubuntu,因此使用 apt 模块。

常用参数:

参数 说明
name 软件包名称
state present 安装;latest 安装最新版;absent 卸载
update_cache 强制更新缓存
conf_file 指定远程安装时依赖的配置文件
disable_pgp_check 是否禁止 GPG 检查,仅用于 present 或 latest
disablerepo 临时禁用 yum 库,仅用于安装或更新
enablerepo 临时启用 yum 库,仅用于安装或更新

示例:安装最新版 htop:

1
ansible -i inventory.ini webservers -m apt -a "name=htop state=latest"

apt 模块安装 htop


七、service 模块

service 模块用于管理服务程序。

常用参数:

参数 说明
arguments 为命令行提供额外参数
enabled 设置开机启动
name 服务名称
runlevel 开机启动级别,一般不用指定
sleep 重启服务过程中是否等待
state started 启动;stopped 停止;restarted 重启;reloaded 重载配置

示例:安装 Apache2:

1
ansible -i inventory.ini webservers -m apt -a "name=apache2 state=latest"

示例:启动 Apache2 并设置开机自启:

1
ansible -i inventory.ini webservers -m service -a "name=apache2 state=started enabled=true"

service 模块启动 Apache2


八、user 模块

常用参数:

参数 说明
comment 用户描述信息
createhome 是否创建家目录
force 使用 state=absent 时,行为与 userdel --force 一致
group 指定基本组
groups 指定附加组;groups= 表示删除所有附加组
home 指定用户家目录
move_home 设置 home= 时,尝试将用户主目录移动到指定目录
name 指定用户名
non_unique 允许改变非唯一 UID
password 指定用户密码
remove 使用 state=absent 时,行为与 userdel --remove 一致
shell 指定默认 shell
state 不指定时为创建;absent 表示删除
system 创建系统用户,不能更改现有用户
uid 指定用户 UID

示例:创建用户并指定 UID、描述信息和密码:

1
ansible -i inventory.ini webservers -m user -a 'uid=6666 name=catcat comment="测试用户" password=297210'

注意:上述密码为明文示例,仅用于演示。生产环境建议使用加密后的密码哈希。


九、group 模块

group 模块用于创建、删除和管理用户组。

常用参数:

参数 说明
gid 设置组 GID
name 指定组名称
state 默认创建;absent 表示删除
system 设置为 yes 时创建系统组

示例:创建 GID 为 8888 的组 cat:

1
ansible -i inventory.ini webservers -m group -a "name=cat gid=8888"

十、script 模块

script 模块用于将本机脚本在被管理端机器上运行。直接指定脚本路径即可。

首先创建脚本 HelloWorld:

1
2
3
#!/bin/bash

echo "Hello World"

为脚本添加执行权限:

1
chmod +x HelloWorld

使用 script 模块执行:

1
ansible -i inventory.ini webservers -m script -a "./HelloWorld"

十一、setup 模块

setup 模块主要用于收集被管理机器的信息,通过调用 facts 组件实现。

facts 是 Ansible 用于采集被管理机器设备信息的功能。可以使用 setup 模块查看机器所有 facts 信息,也可以通过 filter 查看指定信息。facts 信息以 JSON 格式返回,最上层键为 ansible_facts。

facts 本质上就是变量,包括 CPU 颗数、内存大小等信息。后续操作中可以根据不同信息执行不同逻辑,例如 RedHat 系列使用 yum 安装,Debian 系列使用 apt 安装。

查看 CPU 信息:

1
ansible -i inventory.ini webservers -m setup -a 'filter="*cpu*"'

查看内存信息:

1
ansible -i inventory.ini webservers -m setup -a 'filter="*mem*"'

将收集到的数据记录到管理机本地目录:

1
ansible -i inventory.ini webservers -m setup -a 'filter="*mem*"' --tree ./list/trees

使用 --tree 时,请确保目标目录存在,或提前创建目录。