Ansible: 基本操作
2025-02-17
Inventory 配置
创建 Inventory 文件
Inventory 文件用于定义 Ansible 要管理的主机列表。默认路径为 /etc/ansible/hosts。
# 创建基本 inventory
cat > /etc/ansible/hosts <<EOL
192.168.50.66
192.168.50.110
192.168.50.111
192.168.50.112
EOF基本命令
# 测试连通性
ansible all -m ping
# 执行命令
ansible all -a "/bin/echo hello"
# 单行显示结果
ansible servers -m ping -o
# 执行 shell 命令
ansible servers -m shell -a 'uptime'SSH 配置
禁用 known_hosts 检查
# 方法一:配置文件
cat > ~/.ansible.cfg <<EOF
[defaults]
host_key_checking = False
EOF
# 方法二:环境变量
export ANSIBLE_HOST_KEY_CHECKING=False
# Inventory 文件格式主机组定义
# 基本格式
[nameserver]
192.168.50.66
192.168.50.110
[dbserver]
192.168.50.111
192.168.50.112主机变量
# 指定连接参数
jumper ansible_ssh_port=5555 ansible_ssh_host=192.168.50.66
# 指定连接类型和用户
[targets]
localhost ansible_connection=local
other1.example.com ansible_connection=ssh ansible_ssh_user=root主机模式
# 使用范围表达式
[webserver]
www[01:50].example.com
# 使用字母范围
[dbserver]
db-[a:f].example.com最佳实践
配置建议
- 使用组织良好的目录结构
- 合理使用主机组
- 善用变量文件
安全建议
- 使用密钥认证
- 限制主机访问
- 定期更新配置
注意:
- 注意文件权限设置
- 避免明文存储密码
- 及时更新 inventory
参考资料: