1. Ansible基础环境准备
1.1 安装Ansible核心组件
在控制节点上执行以下命令安装最新版Ansible(以RHEL/CentOS为例):
bash复制sudo yum install -y epel-release
sudo yum install -y ansible
验证安装是否成功:
bash复制ansible --version
# 应输出类似:ansible 2.9.27
注意:生产环境建议使用虚拟环境隔离Python依赖,避免与系统组件冲突。可通过
python3 -m venv ansible_env创建专属环境。
1.2 配置SSH免密登录
- 生成密钥对(如果尚未生成):
bash复制ssh-keygen -t rsa -b 4096 -C "ansible-control"
- 将公钥分发到目标主机(假设目标主机IP为192.168.1.101/102):
bash复制ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.1.101
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.1.102
- 测试SSH连接:
bash复制ssh root@192.168.1.101 "hostname"
# 应返回目标主机名而不提示输入密码
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 主机清单配置实战
2.1 静态Inventory文件编写
创建/etc/ansible/hosts文件(或项目目录下的inventory.ini):
ini复制[web_servers]
web1 ansible_host=192.168.1.101 ansible_user=root
web2 ansible_host=192.168.1.102 ansible_user=root
[db_servers]
db1 ansible_host=192.168.1.103 # 示例备用主机
[all:vars]
ansible_ssh_private_key_file=~/.ssh/id_rsa
ansible_python_interpreter=/usr/bin/python3
2.2 动态Inventory配置(可选)
对于云环境,可配置AWS/GCP等动态获取主机:
bash复制# 安装AWS插件
pip install boto3
创建dynamic_inventory.py:
python复制#!/usr/bin/env python
import boto3
import json
ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(Filters=[...])
print(json.dumps({
"web": {
"hosts": [i.public_ip for i in instances],
"vars": {"ansible_user": "ubuntu"}
}
}))
3. 首次连接验证与排错
3.1 基础连通性测试
执行ad-hoc命令验证:
bash复制ansible all -m ping
# 成功响应应包含:"ping": "pong"
3.2 常见连接问题排查
-
权限拒绝:
- 检查
/etc/ssh/sshd_config中PermitRootLogin设置 - 验证密钥权限:
chmod 600 ~/.ssh/id_rsa
- 检查
-
Python路径错误:
bash复制ansible web1 -m raw -a "which python3" # 若路径不同,需在inventory中设置ansible_python_interpreter -
主机密钥检查:
在ansible.cfg中禁用严格检查:ini复制[defaults] host_key_checking = False
4. 核心模块应用示范
4.1 文件分发示例
使用copy模块部署配置文件:
yaml复制- name: Deploy nginx config
hosts: web_servers
tasks:
- copy:
src: ./nginx.conf
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: '0644'
notify: restart nginx
handlers:
- name: restart nginx
service:
name: nginx
state: restarted
4.2 软件包管理示例
批量安装常用工具:
bash复制ansible web_servers -m yum -a "name=htop,vim,git state=present"
4.3 服务状态管理
检查所有主机SSH服务状态:
bash复制ansible all -m service -a "name=sshd state=started enabled=yes"
5. 安全加固实践
5.1 最小权限原则实施
- 创建专用Ansible用户:
bash复制ansible all -m user -a "name=ansible system=yes shell=/bin/bash"
- 配置sudo权限:
bash复制ansible all -m lineinfile -a "dest=/etc/sudoers line='ansible ALL=(ALL) NOPASSWD: ALL' validate='visudo -cf %s'"
5.2 敏感数据加密
使用Ansible Vault加密密码:
bash复制ansible-vault create secrets.yml
# 编辑后保存会自动加密
在playbook中调用:
yaml复制- hosts: db_servers
vars_files:
- secrets.yml
tasks:
- debug:
msg: "DB password is {{ db_password }}"
6. 性能优化技巧
6.1 并发控制配置
在ansible.cfg中调整:
ini复制[defaults]
forks = 20 # 并发进程数
poll_interval = 5
6.2 开启SSH管道加速
ini复制[ssh_connection]
pipelining = True
6.3 实测性能对比
测试50台主机的ping响应时间:
bash复制time ansible all -m ping
# 优化前:32.7s
# 优化后:8.2s
7. 扩展应用场景
7.1 跨平台混合管理
Windows主机配置示例:
ini复制[win_servers]
win1 ansible_host=192.168.1.201 ansible_user=admin ansible_password=Passw0rd ansible_connection=winrm ansible_winrm_transport=ntlm
7.2 与CI/CD集成
GitLab CI示例:
yaml复制deploy:
stage: deploy
script:
- mkdir -p ~/.ssh
- echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
- chmod 600 ~/.ssh/id_rsa
- ansible-playbook -i production deploy.yml
8. 监控与日志分析
8.1 执行日志记录
启用详细日志:
ini复制[defaults]
log_path = /var/log/ansible.log
8.2 性能分析插件
安装profile插件:
bash复制pip install ansible-profile
使用示例:
bash复制ANSIBLE_CALLBACK_WHITELIST=profile_tasks ansible-playbook site.yml
9. 高级调试技巧
9.1 交互式调试模式
使用debugger关键字:
yaml复制tasks:
- name: Debug task
debugger: on_failed
9.2 变量检查方法
查看所有可用变量:
bash复制ansible web1 -m setup
过滤特定信息:
bash复制ansible web1 -m setup -a "filter=ansible_distribution*"
10. 实际案例:Web集群部署
完整playbook示例(web_cluster.yml):
yaml复制- hosts: web_servers
vars:
nginx_version: 1.18.0
tasks:
- name: Install dependencies
yum:
name: ["gcc", "pcre-devel", "zlib-devel"]
state: present
- name: Download nginx
get_url:
url: "http://nginx.org/download/nginx-{{ nginx_version }}.tar.gz"
dest: "/tmp/nginx-{{ nginx_version }}.tar.gz"
- name: Compile nginx
command: >
./configure --prefix=/usr/local/nginx
chdir=/tmp/nginx-{{ nginx_version }}
args:
creates: "/usr/local/nginx/sbin/nginx"
- name: Add nginx service
template:
src: templates/nginx.service.j2
dest: /etc/systemd/system/nginx.service
notify:
- reload systemd
- start nginx
handlers:
- name: reload systemd
systemd:
daemon_reload: yes
- name: start nginx
systemd:
name: nginx
state: started
