Standard Loops

with_items

- name: add several users
user: name={{ item }} state=present groups=wheel
with_items:
- testuser1
- testuser2 #
with_items: somelist - name: add several users
user: name={{ item.name }} state=present groups={{ item.groups }}
with_items:
- { name: 'testuser1', groups: 'wheel' }
- { name: 'testuser2', groups: 'root' }

Nested Loops(with_nested)

- name: give users access to multiple databases
mysql_user: name={{ item[0] }} priv={{ item[1] }}.*:ALL append_privs=yes password=foo
with_nested:
- [ 'alice', 'bob' ]
- [ 'clientdb', 'employeedb', 'providerdb' ] - name: here, 'users' contains the above list of employees
mysql_user: name={{ item[0] }} priv={{ item[1] }}.*:ALL append_privs=yes password=foo
with_nested:
- users
- [ 'clientdb', 'employeedb', 'providerdb' ]

Looping over Hashes(with_dict)

---
users:
alice:
name: Alice Appleworth
telephone: 123-456-7890
bob:
name: Bob Bananarama
telephone: 987-654-3210 tasks:
- name: Print phone records
debug: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
with_dict: users

Looping over Fileglobs(with_fileglob)

---
- hosts: all tasks: # first ensure our target directory exists
- file: dest=/etc/fooapp state=directory # copy each file over that matches the given pattern
- copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
with_fileglob:
- /playbooks/files/fooapp/*

Looping over Parallel Sets of Data

---
alpha: [ 'a', 'b', 'c', 'd' ]
numbers: [ 1, 2, 3, 4 ] tasks:
- debug: msg="{{ item.0 }} and {{ item.1 }}"
with_together:
- alpha
- numbers
# ('a',1), ('b',2), ('c',3)

Looping over Subelements(with_subelements)

# group_vars/all

---
users:
- name: alice
authorized:
- /tmp/alice/onekey.pub
- /tmp/alice/twokey.pub
- name: bob
authorized:
- /tmp/bob/id_rsa.pub - user: name={{ item.name }} state=present generate_ssh_key=yes
with_items: users - authorized_key: "user={{ item.0.name }} key='{{ lookup('file', item.1) }}'"
with_subelements:
- users
- authorized

Looping over Integer Sequences(with_sequence)

---
- hosts: all tasks: # create groups
- group: name=evens state=present
- group: name=odds state=present # create some test users
- user: name={{ item }} state=present groups=evens
with_sequence: start=0 end=32 format=testuser%02x # create a series of directories with even numbers for some reason
- file: dest=/var/stuff/{{ item }} state=directory
with_sequence: start=4 end=16 stride=2 # a simpler way to use the sequence plugin
# create 4 groups
- group: name=group{{ item }} state=present
with_sequence: count=4

Random Choices(with_random_choice)

- debug: msg={{ item }}
with_random_choice:
- "go through the door"
- "drink from the goblet"
- "press the red button"
- "do nothing"

Do-Until Loops

- action: shell /usr/bin/foo
register: result
until: result.stdout.find("all systems go") != -1
retries: 5
delay: 10
# retried for 5 times with a delay of 10 seconds

Finding First Matched Files(with_first_found)

- name: INTERFACES | Create Ansible header for /etc/network/interfaces
template: src={{ item }} dest=/etc/foo.conf
with_first_found:
- "{{ansible_virtualization_type}}_foo.conf"
- "default_foo.conf" - name: some configuration template
template: src={{ item }} dest=/etc/file.cfg mode=0444 owner=root group=root
with_first_found:
- files:
- "{{inventory_hostname}}/etc/file.cfg"
paths:
- ../../../templates.overwrites
- ../../../templates
- files:
- etc/file.cfg
paths:
- templates

Iterating Over The Results of a Program Execution(with_lines)

- name: Example of looping over a command result
shell: /usr/bin/frobnicate {{ item }}
with_lines: /usr/bin/frobnications_per_host --param {{ inventory_hostname }} - name: Example of looping over a REMOTE command result
shell: /usr/bin/something
register: command_result - name: Do something with each result
shell: /usr/bin/something_else --param {{ item }}
with_items: command_result.stdout_lines

Looping Over A List With An Index(with_indexed_items)

- name: indexed loop demo
debug: msg="at array position {{ item.0 }} there is a value {{ item.1 }}"
with_indexed_items: some_list

Flattening A List

# file: roles/foo/vars/main.yml
packages_base:
- [ 'foo-package', 'bar-package' ]
packages_apps:
- [ ['one-package', 'two-package' ]]
- [ ['red-package'], ['blue-package']] to - name: flattened loop demo
yum: name={{ item }} state=installed
with_flattened:
- packages_base
- packages_apps

Using register with a loop

- shell: echo "{{ item }}"
with_items:
- one
- two
register: echo {
"changed": true,
"msg": "All items completed",
"results": [
{
"changed": true,
"cmd": "echo \"one\" ",
"delta": "0:00:00.003110",
"end": "2013-12-19 12:00:05.187153",
"invocation": {
"module_args": "echo \"one\"",
"module_name": "shell"
},
"item": "one",
"rc": 0,
"start": "2013-12-19 12:00:05.184043",
"stderr": "",
"stdout": "one"
},
{
"changed": true,
"cmd": "echo \"two\" ",
"delta": "0:00:00.002920",
"end": "2013-12-19 12:00:05.245502",
"invocation": {
"module_args": "echo \"two\"",
"module_name": "shell"
},
"item": "two",
"rc": 0,
"start": "2013-12-19 12:00:05.242582",
"stderr": "",
"stdout": "two"
}
]
} - name: Fail if return code is not 0
fail:
msg: "The command ({{ item.cmd }}) did not have a 0 return code"
when: item.rc != 0
with_items: echo.results

ansible使用7-Loops的更多相关文章

  1. ansible官方文档翻译之变量

    Ansible变量 在使用ansible变量的时候,主要是因为各个系统的不同,从而需要使用不同的变量来进行设置,例如在设置一些配置文件的时候,有大部分内容是相同的,但是一部分内容是和主机的ip地址或者 ...

  2. Ansible自动化运维笔记3(playbook)

    1.基本语法 playbook文件格式为yaml语法.示例如下: 1.1 nginx.yaml --- - hosts: all tasks: - name: Install Nginx Packag ...

  3. 【Ansible 文档】【译文】Playbooks 变量

    Variables 变量 自动化的存在使得重复的做事情变得很容易,但是我们的系统不可能完全一样. 在某些系统中,你可能想要设置一些与其他系统不一样的行为和配置. 同样地,远程系统的行为和状态也可以影响 ...

  4. Ansible 入门指南 - ansible-playbook 命令

    上篇文章Ansible 入门指南 - 安装及 Ad-Hoc 命令使用介绍的额是 Ad-Hoc 命令方式,本文将介绍 Playbook 方式. Playbook 译为「剧本」,觉得还挺恰当的. play ...

  5. Ansible 入门指南 - 常用模块

    介绍 module 文档: 官宣-模块分类的索引 官宣-全部模块的索引 在playbook脚本中,tasks 中的每一个 action都是对 module的一次调用.在每个 action中: 冒号前面 ...

  6. Ansible Playbook 循环

    Standard Loops 为了节省一些打字,重复的任务可以写成如下: - name: add several users user: name: "{{ item }}" st ...

  7. Ansible Playbook Conditionals

    通常,play的结果可能取决于变量的值,facts(有关远程系统的知识)或先前的任务结果. 在某些情况下,变量的值可能取决于其他变量. 此外,可以创建其他组,以根据主机是否与其他条件匹配来管理主机. ...

  8. ansible 2.1.0 api 编程

    pdf文档 https://media.readthedocs.org/pdf/ansible/latest/ansible.pdf api介绍 http://blog.csdn.net/python ...

  9. ansible playbooks loop循环

    在一个task中循环某个操作 1.标准循环 - name: add several users user: name: "{{ item }}" state: present gr ...

随机推荐

  1. Qt 学习之路 2(9):资源文件

    Qt 学习之路 2(9):资源文件  豆子  2012年8月31日  Qt 学习之路 2  62条评论 上一章节中我们介绍了如何使用QAction添加动作.其中,我们使用QIcon加载了一张 png ...

  2. Java类成员变量、普通成员变量、初始化块、构造方法的初始化和执行顺序

    结论:执行的大致顺序如下, (1) 在一个不存在继承的类中:初始化static变量,执行static初始化块-->初始化普通成员变量(如果有赋值语句),执行普通初始化块-->构造方法 (2 ...

  3. Linux防火墙详解

    1.Linux防火墙基础 作为隔离内外网.过滤非法数据的有力屏障,防火墙通常按实现环境的不同分为硬件防火墙和软件防火墙.硬件防火墙是功能专一的硬件设备,具有比较全面的功能,其工作效率较高,但是加个昂贵 ...

  4. kibana启动调试

    在windows的命令行窗口中,将路径制定到kibana的源代码bin目录中,然后执行 kibana.bat --dev --no-base-path 需要注意的是kibana.yml中的配置文件需要 ...

  5. logback error 分开存日志

    <?xml version="1.0" encoding="UTF-8"?> <configuration> <property ...

  6. k2安装LEDE

    固件下载时请用Breed Web 恢复控制台恢复固件,步骤如下:1.到LEDE官方网站下载最新开发版固件2.Web Breed台刷写固件3.将一台能上网的路由器LAN口接至K2 WAN口,等待K2连上 ...

  7. my06_sysbench install for mysql 并初始化表数据

    sysbench安装 ************************************************************** 安装sysbench依赖包 rpm -q autom ...

  8. js和jq中常见的各种位置距离之offset和offset()的区别(三)

    offsetLeft:元素的边框的外边缘距离与已定位的父容器(offsetparent)的左边距离(不包括元素的边框和父容器的边框). offset().left:返回的是相对于当前文档的坐标,使用o ...

  9. Linux进程间通信的几种方式

    1.管道及有名管道(pipe & named pipe) pipe 用于亲缘关系的进程间通信,named pipe除了pipe的功能外,还可以进行无亲缘关系进程间的通信. 2.信号(Signa ...

  10. 前后端分离之JWT用户认证

    在前后端分离开发时为什么需要用户认证呢?原因是由于HTTP协定是不储存状态的(stateless),这意味着当我们透过帐号密码验证一个使用者时,当下一个request请求时它就把刚刚的资料忘了.于是我 ...