跳到主要内容

Ansible

  • ansible 是什么?
    • GPL-3.0, Python
    • 自动化 服务开通、配置管理、应用部署 工具
    • 实现 Infrastructure as code - 基础设施即代码
    • 支持 Linux、Windows 及 网络设备
    • 包含大量的插件和三方集成
  • 系统要求
    • 控制节点 - python linix/windows
    • 管理节点 - python sftp/scp
  • 注意 ⚠️
    • 分组名包含 - 会告警
      • force_valid_group_names=ignore 可关闭
    • docker_container 模块网络有所调整 - 之后默认不会添加 default 网络 - 与 docker 保持一直
      • 建议 networks_cli_compatible=yes 提前与 docker 网络保持一致
    • 建议使用 yaml 写 inventory - 比 ini 的模式好管理 - 结构也更加清晰
    • 相同 set_fact 不能互相依赖 #40239
  • 参考
  • 学习
  • 界面
  • 环境变量
    • ANSIBLE_INVENTORY - 逗号分隔的仓库源
    • DEFAULT_HOST_LIST - 默认仓库源 - inventory 配置
# ping 所有节点
ansible all -m ping
# -i 指定仓库
ansible all -m ping -i hosts
# ping 本地 - 指定解释器
ansible localhost -m ping -e 'ansible_python_interpreter=/usr/bin/python3'
# 执行命令
ansible all -a date -i hosts

# ansible_facts 内容
ansible localhost -m setup

# 节点上本地设置的内容 - 文件为 ini 格式
# /etc/ansible/facts.d/preferences.fact
ansible hostname -m setup -a "filter=ansible_local"

# docker 启动环境
docker run --rm -it \
-e TZ=Asia/Shanghai \
-v $HOME/.ansible:/root/.ansible \
-v $PWD:/host -w /host \
--name ansible wener/ansible
CommandDesc
ansible执行 AdHoc 命令
ansible-config查看当前所有配置
ansible-connection连接到远程设备
ansible-consoleREPL 方式执行 Ansible Task
ansible-doc文档查询
ansible-galaxyRole 和 Collection 依赖管理
ansible-inventory查询机器清单
ansible-playbook执行 Playbook
ansible-pull配合 cron 从 VSC 拉取 playbook 然后本地执行 - 适用于大规模周期性任务执行
ansible-testRole 和 Collection 开发的测试工具
ansible-vaultAnsible 加密数据操作

安装

# macOS
CFLAGS=-Qunused-arguments CPPFLAGS=-Qunused-arguments pip install --user ansible

# 2.10
pip uninstall ansible
pip install ansible

ansible.cfg

# 缓存 facts
[defaults]
gathering = smart
# 缓存时间 - 秒
fact_caching_timeout = 86400
# 缓存到 redis
# pip install redis
fact_caching = redis
# 缓存到 json 文件
fact_caching = jsonfile
fact_caching_connection = /path/to/cachedir

# 兼容 docker network - 如果指定了网络不添加默认网络
networks_cli_compatible=yes
# 不校验分组名字 允许包含 `-'
force_valid_group_names=ignore
  • ansible_sudo_pass

变量查找路径

最佳实践

Tips