Teng's blog Teng's blog
首页
Java
H5前端
GitHub (opens new window)
首页
Java
H5前端
GitHub (opens new window)
  • 背景介绍
  • 安装
  • 配置说明
  • 基础命令
  • 常用模块
  • Playbook

    • 简单介绍
    • yaml语法
    • hosts
    • task
    • 运行playbook
    • handlers
    • tags
    • variables
    • template
    • when条件判断
    • with_items迭代
      • 应用实例
        • 创建多个文件以及安装包
        • 创建多个组
        • 创建多个用户
      • 迭代嵌套子变量
    • roles
    • 附:jinja2语法
  • Tool-Ansible
  • Playbook
Shetengteng
2022-05-21

with_items迭代

当有需要重复性执行的任务时,使用迭代机制

使用说明

  • 在task中使用with_items给定要迭代的元素列表

  • 对迭代项的引用,固定变量名为 item

  • 列表格式:字符串,字典

  • ansible的循环机制还有更多的高级功能,具体请参见官方文档 http://docs.ansible.com/playbooks_loops.html

# 应用实例

# 创建多个文件以及安装包

创建 playbook执行的yml文件,app.yml

- hosts: app
  remote_user: root
  
  tasks:
    - name: create file
      file: name=/opt/{{ item }} state=touch
      when: ansible_distribution_major_version == '7'
      with_items:
        - file1
        - file2
        - file3
    - name: install some package
      yum: name={{ item }}
      with_items:
        - htop
        - sl
        - hping3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

执行命令

ansible-playbook -C app.yml
ansible-playbook app.yml
1
2

验证

ansible app -m shell -a 'rpm -q htop sl hping3'
1

# 创建多个组

编写yaml

- hosts: app
  remote_user: root
  
  tasks:
    - name: create group
      group: name={{ item }}
      when: ansible_distribution_major_version == '7'
      with_items:
        - g1
        - g2
        - g3
1
2
3
4
5
6
7
8
9
10
11

# 创建多个用户

- hosts: app
  remote_user: root
  
  tasks:
    - name: add users
      user: name={{ item }} state=present groups=wheel 
      when: ansible_distribution_major_version == '7'
      with_items:
        - user1
        - user2
1
2
3
4
5
6
7
8
9
10

# 迭代嵌套子变量

with_items中使用元素可为字典

实例:创建不同用户到不同的组

- hosts: app
  remote_user: root
  
  tasks:
    - name: add users
      user: name={{ item.name }} state=present groups={{ item.group }} 
      when: ansible_distribution_major_version == '7'
      with_items:
        - { name: 'user1', group: 'wheel' }
        - { name: 'user2', group: 'root' }
1
2
3
4
5
6
7
8
9
10
Last Updated: 2022/05/22, 12:42:00
when条件判断
roles

← when条件判断 roles→

Theme by Vdoing | Copyright © 2021-2022 Shetengteng | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式