linRichielinRichie
前端
Python
Linux
ChatGPT
  • B 站
  • 500px
前端
Python
Linux
ChatGPT
  • B 站
  • 500px
  • Ansible

    • Ansible: 基本操作
    • Ansible: 安装
    • Ansible: 简介
    • YAML: 文件格式
    • Playbook

      • Playbook: 介绍
      • Playbook: 操作
    • 模块

      • Yum模块常用参数
    • 实战

      • Ansible 实战
  • Anaconda

    • Anaconda命令
  • Iptables

    • Iptable: 防火墙
    • iptables 用法
  • Systemd

    • 系统服务配置
    • 系统服务启动文件
    • 性能优化

      • Linux 系统监控
      • Linux 系统性能优化
      • Linux 系统故障诊断
      • Linux 系统日志管理
  • Network

    • 用一张图解释 8 种流行的网络协议
    • 反子网掩码
    • 交换机端口模式
    • eNSP 软件
    • 华为交换机配置命令
    • eNSP静态路由实验
  • Commands

    • 命令别名:alias
    • 多类型资源统计工具: dstat
    • history配置
    • unzip命令
    • Linux用户到期登录时间和随机密码
    • 常用 Command
    • ssh

      • ssh-keygen
      • linux ssh命令
  • CI/CD

    • Jenkins CI/CD 管道
  • Kubernetes

    • Docker系列学习

      • 01. 什么是Docker
      • 02. Docker安装
      • 03. 使用Docker镜像
      • 04. 利用commit理解镜像构成
      • 05. 操作Docker容器
      • 06. 使用Dockerfile定制镜像
      • 07. Dockerfile指令详解
      • 08. Dockerfile多阶段创建
      • 09. 访问仓库
      • 10. 修改docker的启动项
      • 11. Nexus3.x的私有仓库
      • 12. docker-hub加速器
      • 13. 数据管理
      • 14. 使用网络
  • Shell编程

    • Shell 编程基础
    • Shell 脚本执行消耗的时间
    • Shell 自动生成简介

Ansible: 基本操作

  • Inventory 配置
    • 创建 Inventory 文件
    • 基本命令
  • SSH 配置
    • 禁用 known_hosts 检查
  • 主机组定义
    • 主机变量
    • 主机模式
  • 最佳实践

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

最佳实践

  1. 配置建议

    • 使用组织良好的目录结构
    • 合理使用主机组
    • 善用变量文件
  2. 安全建议

    • 使用密钥认证
    • 限制主机访问
    • 定期更新配置

注意:

  • 注意文件权限设置
  • 避免明文存储密码
  • 及时更新 inventory

参考资料:

  • Ansible Inventory 指南
  • Ansible 最佳实践
Next
Ansible: 安装