Ansible
Ansible 是一个由美国程序员 Michael DeHaan 使用 Python 语言开发的系统管理工具, 首个版本于 2012 年发布,使用 GPL3 许可;
2015 年,美国公司 Red Hat 收购了 Ansible,并继续作为正式赞助商和主要开发者支持该项目。
概述
编按:如果将实例的配置文件和状态统一抽象为状态,可理解 ansible 为实例状态管理工具。 如将 host a b c 的 /etc/hosts 修改为同一个内容,即 ansible 管理 a b c 保持 /etc/hosts 文件内容为某个结果状态,hash 一致。
安装 Python 命令行包
macOS: brew install ansible
Ubuntu: sudo python3 -mpip install ansible -I
后以版本 2.x 为例。
常用配置
主配置文件 ansible.cfg ini 格式,默认按以下顺序识别处理:
- 环境变量
$ANSIBLE_CONFIG - 当前目录 ansible.cfg
$HOME/.ansible.cfg- Linux
/etc/ansible/ansible.cfg或 macOS/opt/homebrew/etc/ansible/ansible.cfg
从模板生成 ansible.cfg 文件 ansible-config init --disabled > ansible.cfg
inventory 配置文件默认从 /etc/ansible/hosts 路径加载,可通过修改主配置 ansible.cfg 来自定义:
[defualts]
inventory=/path/to/ansible.hosts.cfg在实践中,一般手动执行环境中新建 $HOME/.ansible.cfg 作为全局默认配置, 另外在对应项目源码根目录新建 ansible.cfg,并自定义相关 inventory ansible.hosts.cfg 配置路径:
ansible-config init --disabled > $HOME/.ansible.cfg
cd path/to/my/project
cat << EOF > ansible.cfg
[defaults]
inventory=ansible.hosts.cfg
interpreter_python=auto_legacy_silent
remote_port=22
EOF
cat << EOF > ansible.hosts.cfg
[web]
10.0.0.1
10.0.0.2
[db]
10.0.0.3
10.0.0.4
EOF管理节点
命令格式 ansible [一个实例IP或一组目标] [-m 模块名] [模块参数]
示例:
在本机执行 ping ansible localhost -m ping ;
(需在 inventory 配置中提前定义)在 web 组实例中执行 ping ansible web -m ping ;
(需在 inventory 配置中提前定义)在所有实例中执行 ping ansible all -m ping ;
常用命令
复制本地文件到远程机器(需在 inventory 配置中提前定义 web 组,或指定一个实例 hostname/IP 代替)
ansible web \
-m copy \
-a "src=/tmp/foo dest=/data/bar" \
-s在本地执行命令 ansible all -i "127.0.0.1," -c local -m command -a 'uptime'
在远程执行命令 ansible 10.0.0.1 -a 'uptime' -s
打印所有调试日志 ansible -vvv all 'uptime'
任务编排
ansible-playbook 支持将所有需要执行的指令编排写到一个 yaml 配置文件,然后依次执行。
命令格式 ansible-playbook <playbook YAML 配置文件] [--extra=... 额外动态变量传给配置文件]
示例:
在 init-web.yml 定义的实例组中执行 init-web.yml 定义的编排任务: ansible-playbook init-web.yml --extra="host=web user=bot"
仅在 init-web.yml 定义的实例组中某个特定实例,执行编排任务:ansible-playbook init-web.yml --extra="target=10.0.0.1 user=bot"
Updated 2024-12-07.
Created 2019-12-22.
