Ansible基本使用

一、Ansible概述和安装

Ansible 是一款功能强大的 IT 自动化工具,通过无代理机制实现高效的配置管理、应用部署、任务执行以及多节点间的 IT 编排。其主要特点包括:

  1. 无代理:无需在目标节点上安装任何额外的代理服务。
  2. 易于学习:基于简单的 YAML 语法定义任务。
  3. 模块化设计:提供丰富的模块库,适配多种任务需求。
  4. 高效安全:基于 SSH 进行通信,无需额外开放端口。
1.安装指南

在安装时,需根据使用环境选择适配方案:

  • CentOS 7

CentOS 7 在生产环境中依然应用广泛,使用 yum 进行安装:

bash 复制代码
yum install epel-release -y
yum install ansible -y
  • CentOS 9

CentOS 9 为官方维护版本,推荐使用 dnf 进行安装:

bash 复制代码
dnf install epel-release -y
dnf install ansible -y
  • Ubuntu

Ubuntu 系统上可通过 APT 包管理安装:

bash 复制代码
sudo apt update
sudo apt install ansible -y
2.验证安装正确性

安装完成后,可以运行下列命令确认:

bash 复制代码
ansible --version
二、Inventory 文件的配置和解释

Inventory 文件是用于定义目标节点和管理节点组的核心文件。

1.基本格式

Inventory 文件默认位置为 /etc/ansible/hosts,其格式如下:

ini 复制代码
[group1]
host1 ansible_host=192.168.1.10 ansible_user=root
host2 ansible_host=192.168.1.11 ansible_user=admin

[group2]
host3 ansible_host=192.168.1.12 ansible_port=2222
  • group1group2:节点分组。
  • ansible_host:目标节点的 IP 地址。
  • ansible_user:用于连接的用户。
  • ansible_port:指定目标节点的 SSH 端口,默认为 22。
2.高级配置
  • 公共变量

    公共变量可以为全局或指定组设定默认值:

ini 复制代码
[all:vars]
ansible_python_interpreter=/usr/bin/python3
  • 分组维护

    通过分组进行节点的根据配置:

ini 复制代码
[group1:children]
subgroup1
subgroup2
三、动态配置 Inventory 文件

动态 Inventory 的优点在于能够根据实时环境生成节点清单,避免手动维护带来的繁琐和错误。以下为动态配置的步骤和注意事项:

1.从简单脚本入手

以下是一个简单的 Python 脚本示例,用于生成动态 Inventory 文件:

python 复制代码
import argparse
import json

def lists():
    r = {}
    h = ['192.168.119.13' + str(i) for i in range(1, 3)]
    hosts = {'hosts': h}
    r['mysql'] = hosts
    return json.dumps(r, indent=4)

def hosts(name):
    cpis = {
        'ansible_ssh_port': 22,
        'ansible_ssh_user': 'root',
        'ansible_ssh_pass': '123456'
    }
    return json.dumps(cpis)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-l',
        '--list',
        help="hosts list",
        action='store_true'
    )
    parser.add_argument(
        '-H',
        '--host',
        help='hosts vars'
    )
    args = vars(parser.parse_args())
    if args['list']:
        print(lists())
    elif args['host']:
        print(hosts(args['host']))
    else:
        print(parser.print_help())
2.如何使用动态脚本

将上述脚本保存为 dynamic_inventory.py,并赋予执行权限:

bash 复制代码
chmod +x dynamic_inventory.py

运行以下命令验证脚本功能:

  • 获取主机列表:
bash 复制代码
./dynamic_inventory.py --list
  • 获取单个主机的变量信息:
bash 复制代码
./dynamic_inventory.py --host <hostname>

在 Ansible 中使用动态 Inventory:

bash 复制代码
ansible -i ./dynamic_inventory.py all -m ping
3.扩展到结合工具

在实际生产中,可以结合工具如 JumpServer 动态生成 Inventory。以下是基于 JumpServer 数据库的 Python 示例:

python 复制代码
import pymysql

connection = pymysql.connect(
    host='jumpserver_db_host',
    user='db_user',
    password='db_password',
    database='jumpserver_db'
)

try:
    with connection.cursor() as cursor:
        cursor.execute("SELECT ip, username FROM assets")
        hosts = cursor.fetchall()

    with open('/etc/ansible/hosts', 'w') as inventory:
        inventory.write('[dynamic]\n')
        for host in hosts:
            inventory.write(f"{host[0]} ansible_user={host[1]}\n")
finally:
    connection.close()

此脚本适用于需要与 JumpServer 或其他外部系统集成的场景。

4.动态 Inventory 的注意事项
  • 确保脚本输出符合 JSON 格式,并且结构正确。
  • 在复杂环境中,脚本需处理异常以保证健壮性。
  • 对于大规模节点,测试脚本性能和兼容性至关重要。
四、常用 Ad-Hoc 命令

Ad-Hoc 命令是 Ansible 最基础的操作工具,能够快速执行临时任务。以下是详细使用方法和常用模块介绍:

1.Ad-Hoc 的基本用法

Ad-Hoc 命令格式如下:

bash 复制代码
ansible <pattern> -m <module> -a <arguments>
  • <pattern>:目标主机模式(如 all 或指定组)。
  • <module>:执行任务的模块。
  • <arguments>:模块的参数。
2.常用命令示例
  • 检查节点连通性
bash 复制代码
ansible all -m ping
  • 执行命令
bash 复制代码
ansible all -a "df -h"
  • 上传文件
bash 复制代码
ansible all -m copy -a "src=/local/file dest=/remote/path"
  • 删除文件
bash 复制代码
ansible all -m file -a "path=/remote/file state=absent"
  • 安装软件
bash 复制代码
ansible all -m yum -a "name=httpd state=present"
  • 启动服务
bash 复制代码
ansible all -m service -a "name=httpd state=started"
3.常用模块
  • ping:测试节点是否可用。
  • command:执行简单命令。
  • shell:执行复杂 Shell 命令。
  • copy:复制文件到目标节点。
  • file:管理文件和目录的属性。
  • yum / apt:管理软件包。
  • service:管理系统服务。
  • user:管理用户账户。
  • cron:管理计划任务。

通过 Ad-Hoc 命令与模块的灵活组合,Ansible 能够快速响应多样化的管理需求。

相关推荐
风清再凯1 天前
自动化工具ansible,以及playbook剧本
运维·自动化·ansible
IT乌鸦坐飞机1 天前
ansible部署数据库服务随机启动并创建用户和设置用户有完全权限
数据库·ansible·centos7
遇见火星14 天前
如何使用Ansible一键部署MinIO集群?
ansible
粥周粥14 天前
ANSIBLE
ansible
码农101号14 天前
Linux中ansible模块补充和playbook讲解
linux·运维·ansible
码农101号14 天前
Linux的Ansible软件基础使用讲解和ssh远程连接
ansible
烟雨书信16 天前
ANSIBLE运维自动化管理端部署
运维·自动化·ansible
碎碎-li16 天前
ANSIBLE(运维自动化)
运维·自动化·ansible
@donshu@19 天前
Linux运维-ansible-python开发-获取inventroy信息
linux·运维·ansible
Kendra91922 天前
Ansible
ansible