【自动化部署】Ansible循环

文章目录

  • Ansible循环
    • [1. `with_items`](#1. with_items)
    • [2. `with_list`](#2. with_list)
    • [3. `with_flattened`](#3. with_flattened)
    • [4. `with_together`](#4. with_together)
    • [5. `with_cartesian` 和 `with_nested`](#5. with_cartesianwith_nested)
  • [Ansible 配置模板与效率优化](#Ansible 配置模板与效率优化)
    • 一、配置模板
      • [1. 准备配置模板文件](#1. 准备配置模板文件)
      • [2. 修改 inventory 主机清单配置文件](#2. 修改 inventory 主机清单配置文件)
      • [3. 编写 playbook](#3. 编写 playbook)
    • [二、Ansible 执行效率优化](#二、Ansible 执行效率优化)
      • [1. 加大 forks 值](#1. 加大 forks 值)
      • [2. 修改执行策略](#2. 修改执行策略)
      • [3. 开启 SSH 长连接](#3. 开启 SSH 长连接)
      • [4. 开启 Pipelining 特性](#4. 开启 Pipelining 特性)
      • [5. 关闭 Facts 信息收集](#5. 关闭 Facts 信息收集)
      • [6. 使用 Ansible 异步执行任务](#6. 使用 Ansible 异步执行任务)

Ansible循环

1. with_items

  • 用法:用于遍历一个简单的列表或字典列表。

  • 行为:当处理嵌套列表时,会将嵌套列表"拉平"并逐个处理元素。

  • 示例

    yaml 复制代码
    - debug:
        msg: "{{item}}"
      with_items:
      - 1
      - 2
      - 3

    yaml 复制代码
    - debug:
        msg: "{{item.test1}}"
      with_items:
      - { test1: a, test2: b }
      - { test1: c, test2: d }

2. with_list

  • 用法:用于遍历列表。

  • 行为 :只处理最外层的列表项,不会"拉平"嵌套列表。在Ansible 2.5及以后的版本中,推荐使用loop代替with_list

  • 示例

    yaml 复制代码
    - debug:
        msg: "{{item}}"
      with_list:
      - [1, 2, 3]
      - [a, b]  # 这个嵌套列表不会被拉平

3. with_flattened

  • 用法:用于遍历列表,包括嵌套列表。

  • 行为:会将所有嵌套列表"拉平"并逐个处理元素。

  • 示例

    yaml 复制代码
    - debug:
        msg: "{{item}}"
      with_flattened:
      - [1, 2, 3]
      - [a, b]  # 这个嵌套列表会被拉平

4. with_together

  • 用法:用于将两个列表的元素"对齐合并"。

  • 行为 :第一个列表的每个元素会与第二个列表中相同位置的元素合并输出。如果第二个列表的元素不足,则输出null

  • 示例

    yaml 复制代码
    - debug:
        msg: "{{item}}"
      with_together:
      - [1, 2, 3]
      - [a, b, c]

5. with_cartesianwith_nested

  • 用法:用于生成两个或多个列表的笛卡尔积(所有可能的组合)。

  • 行为with_cartesianwith_nested功能相同,可以互换使用。

  • 示例

    yaml 复制代码
    - debug:
        msg: "{{item}}"
      with_cartesian:
      - [a, b, c]
      - [test1, test2]

    yaml 复制代码
    - debug:
        msg: "{{item[0]}},{{item[1]}}"
      with_nested:
      - "{{test}}"
      - "{{demo}}"
  • with_itemswith_flattened在处理嵌套列表时有不同行为,前者拉平,后者不拉平。

  • with_list只处理最外层列表,建议使用loop代替。

  • with_together用于对齐合并两个列表。

  • with_cartesianwith_nested用于生成笛卡尔积。

Ansible 配置模板与效率优化

一、配置模板

1. 准备配置模板文件

  • 创建一个 .j2 文件(例如 config.j2),作为配置模板文件。
  • 在模板文件中使用 {``{ 变量名 }} 格式引用主机变量、组变量、自定义变量以及 facts 信息字段变量。

示例 config.j2 文件:

jinja2 复制代码
[mysqld]
user={{ mysql_user }}
port={{ mysql_port }}
datadir={{ mysql_datadir }}

2. 修改 inventory 主机清单配置文件

  • 编辑 /etc/ansible/hosts 文件,设置主机变量和组变量。

示例 /etc/ansible/hosts 文件:

ini 复制代码
[mysql_servers]
db1 ansible_host=192.168.1.10 mysql_user=mysqluser mysql_port=3306 mysql_datadir=/var/lib/mysql
db2 ansible_host=192.168.1.11 mysql_user=mysqluser mysql_port=3306 mysql_datadir=/var/lib/mysql

[mysql_servers:vars]
mysql_version=5.7

3. 编写 playbook

  • 编写一个 playbook 文件,使用 template 模块将模板文件应用到远程主机。

示例 deploy_config.yml 文件:

yaml 复制代码
- name: Deploy MySQL Configuration
  hosts: mysql_servers
  tasks:
    - name: Template MySQL Configuration File
      template:
        src: config.j2
        dest: /etc/my.cnf

二、Ansible 执行效率优化

1. 加大 forks 值

  • 修改 /etc/ansible/ansible.cfg 文件,增加 forks 的值以提升并发工作进程数。
ini 复制代码
[defaults]
forks = 20

2. 修改执行策略

  • 将默认策略从 linear 改为 free,使得节点执行完一个任务后不等待其它节点即可继续执行剩余任务。
ini 复制代码
[defaults]
strategy = free

3. 开启 SSH 长连接

  • 修改 /etc/ansible/ansible.cfg 文件,启用 SSH 长连接。
ini 复制代码
[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=60m

4. 开启 Pipelining 特性

  • 修改 /etc/ansible/ansible.cfg 文件,启用 Pipelining 特性。
  • 远程主机需要禁用 requiretty,编辑 /etc/sudoers 文件,注释掉 Defaults requiretty
ini 复制代码
[defaults]
pipelining = True

5. 关闭 Facts 信息收集

  • 在 playbook 中使用 gather_facts: false 禁用 facts 信息收集。

示例 deploy_config.yml 文件:

yaml 复制代码
- name: Deploy MySQL Configuration
  hosts: mysql_servers
  gather_facts: false
  tasks:
    - name: Template MySQL Configuration File
      template:
        src: config.j2
        dest: /etc/my.cnf

6. 使用 Ansible 异步执行任务

  • 在 playbook 中使用 asyncpoll 参数异步执行任务,并注册任务 ID。
  • 使用 async_status 模块检查异步任务状态。

示例 async_task.yml 文件:

yaml 复制代码
- name: Run Asynchronous Task
  hosts: mysql_servers
  tasks:
    - name: Start Asynchronous Task
      async: 3600  # 后台任务3600秒还未完成,则任务失败
      poll: 0      # 不检查后台任务执行状况
      command: /path/to/long_running_command
      register: job_id

    - name: Wait for Asynchronous Task to Complete
      async_status:
        jid: "{{ job_id.ansible_job_id }}"
      register: job_result
      until: job_result.finished
      retries: 300  # 每3秒检查一次,共等待900秒
      delay: 3
相关推荐
代码游侠几秒前
学习笔记——线程控制 - 互斥与同步
linux·运维·笔记·学习·算法
AALoveTouch6 分钟前
n8n 2.0 中文汉化版一键部署教程 | 解除Execute Command限制
人工智能·自动化
牛奶咖啡1310 分钟前
Linux常见系统故障案例说明并修复解决(下)
linux·服务器·文件系统挂载异常分析并修复·持久化挂载分区文件丢失故障修复·分析系统进程cpu占用率过高
程序人生51816 分钟前
解决Dbeaver 连上 MySQL 数据库后不显示 information_schame、mysql 等数据库
数据库·mysql
与衫17 分钟前
SQLFlow × 高斯数据库:构建可治理、可追溯的数据底座
数据库·oracle
java_logo23 分钟前
Webtop Docker 容器化部署指南:基于浏览器的Linux桌面环境
linux·docker·容器·webtop·webtop部署教程·docker部署webtop·linux桌面
小小测试开发33 分钟前
SQL常用语法全解析:从入门到进阶的实战指南
数据库·sql
Bruce_Liuxiaowei34 分钟前
SSH主机密钥验证失败(Host key verification failed)深度解析与解决方案
运维·网络·ssh
暗之星瞳35 分钟前
mysql练习
数据库·mysql
月上林梢37 分钟前
QT圆形加载进度条
数据库·c++·qt·进度条