Standard Loops

with_items

  1. - name: add several users
  2. user: name={{ item }} state=present groups=wheel
  3. with_items:
  4. - testuser1
  5. - testuser2
  6. #
  7. with_items: somelist
  8. - name: add several users
  9. user: name={{ item.name }} state=present groups={{ item.groups }}
  10. with_items:
  11. - { name: 'testuser1', groups: 'wheel' }
  12. - { name: 'testuser2', groups: 'root' }

Nested Loops(with_nested)

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

Looping over Hashes(with_dict)

  1. ---
  2. users:
  3. alice:
  4. name: Alice Appleworth
  5. telephone: 123-456-7890
  6. bob:
  7. name: Bob Bananarama
  8. telephone: 987-654-3210
  9. tasks:
  10. - name: Print phone records
  11. debug: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
  12. with_dict: users

Looping over Fileglobs(with_fileglob)

  1. ---
  2. - hosts: all
  3. tasks:
  4. # first ensure our target directory exists
  5. - file: dest=/etc/fooapp state=directory
  6. # copy each file over that matches the given pattern
  7. - copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
  8. with_fileglob:
  9. - /playbooks/files/fooapp/*

Looping over Parallel Sets of Data

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

Looping over Subelements(with_subelements)

  1. # group_vars/all
  2. ---
  3. users:
  4. - name: alice
  5. authorized:
  6. - /tmp/alice/onekey.pub
  7. - /tmp/alice/twokey.pub
  8. - name: bob
  9. authorized:
  10. - /tmp/bob/id_rsa.pub
  11. - user: name={{ item.name }} state=present generate_ssh_key=yes
  12. with_items: users
  13. - authorized_key: "user={{ item.0.name }} key='{{ lookup('file', item.1) }}'"
  14. with_subelements:
  15. - users
  16. - authorized

Looping over Integer Sequences(with_sequence)

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

Random Choices(with_random_choice)

  1. - debug: msg={{ item }}
  2. with_random_choice:
  3. - "go through the door"
  4. - "drink from the goblet"
  5. - "press the red button"
  6. - "do nothing"

Do-Until Loops

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

Finding First Matched Files(with_first_found)

  1. - name: INTERFACES | Create Ansible header for /etc/network/interfaces
  2. template: src={{ item }} dest=/etc/foo.conf
  3. with_first_found:
  4. - "{{ansible_virtualization_type}}_foo.conf"
  5. - "default_foo.conf"
  6. - name: some configuration template
  7. template: src={{ item }} dest=/etc/file.cfg mode=0444 owner=root group=root
  8. with_first_found:
  9. - files:
  10. - "{{inventory_hostname}}/etc/file.cfg"
  11. paths:
  12. - ../../../templates.overwrites
  13. - ../../../templates
  14. - files:
  15. - etc/file.cfg
  16. paths:
  17. - templates

Iterating Over The Results of a Program Execution(with_lines)

  1. - name: Example of looping over a command result
  2. shell: /usr/bin/frobnicate {{ item }}
  3. with_lines: /usr/bin/frobnications_per_host --param {{ inventory_hostname }}
  4. - name: Example of looping over a REMOTE command result
  5. shell: /usr/bin/something
  6. register: command_result
  7. - name: Do something with each result
  8. shell: /usr/bin/something_else --param {{ item }}
  9. with_items: command_result.stdout_lines

Looping Over A List With An Index(with_indexed_items)

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

Flattening A List

  1. # file: roles/foo/vars/main.yml
  2. packages_base:
  3. - [ 'foo-package', 'bar-package' ]
  4. packages_apps:
  5. - [ ['one-package', 'two-package' ]]
  6. - [ ['red-package'], ['blue-package']]
  7. to
  8. - name: flattened loop demo
  9. yum: name={{ item }} state=installed
  10. with_flattened:
  11. - packages_base
  12. - packages_apps

Using register with a loop

  1. - shell: echo "{{ item }}"
  2. with_items:
  3. - one
  4. - two
  5. register: echo
  6. {
  7. "changed": true,
  8. "msg": "All items completed",
  9. "results": [
  10. {
  11. "changed": true,
  12. "cmd": "echo \"one\" ",
  13. "delta": "0:00:00.003110",
  14. "end": "2013-12-19 12:00:05.187153",
  15. "invocation": {
  16. "module_args": "echo \"one\"",
  17. "module_name": "shell"
  18. },
  19. "item": "one",
  20. "rc": 0,
  21. "start": "2013-12-19 12:00:05.184043",
  22. "stderr": "",
  23. "stdout": "one"
  24. },
  25. {
  26. "changed": true,
  27. "cmd": "echo \"two\" ",
  28. "delta": "0:00:00.002920",
  29. "end": "2013-12-19 12:00:05.245502",
  30. "invocation": {
  31. "module_args": "echo \"two\"",
  32. "module_name": "shell"
  33. },
  34. "item": "two",
  35. "rc": 0,
  36. "start": "2013-12-19 12:00:05.242582",
  37. "stderr": "",
  38. "stdout": "two"
  39. }
  40. ]
  41. }
  42. - name: Fail if return code is not 0
  43. fail:
  44. msg: "The command ({{ item.cmd }}) did not have a 0 return code"
  45. when: item.rc != 0
  46. 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. anglarJs分页

    首先在页面引入分页插件 <script src="../plugins/angularjs/pagination.js"></script> <lin ...

  2. [Ruby]转载: 关于ruby中 %Q, %q, %W, %w, %x, %r, %s 的用法

    单引号内的内容,ruby会原样输出 双引号内的内容,ruby会解析 我们看个简单的例子,针对字符串      #{foo}test     我们分别用单引号核双引号操作 '#{foo}test'   ...

  3. Mybatis学习笔记(五) —— Mapper.xml(输入映射和输出映射)

    一.parameterType(输入类型) 1.1 传递简单类型 <!-- 根据用户id查询用户 --> <select id="queryUserById" p ...

  4. 读经典——《CLR via C#》(Jeffrey Richter著) 笔记_基元类型(二)

    [基元类型推荐] 推荐直接使用 FCL 类型. [理由] 编码时不至于困惑string与String的使用.由于C#的stirng(一个关键字)直接映射到System.String(一个 FCL 类型 ...

  5. python中 列表 字典 元组的了解

    #######列表######1.列表的特性 server = [['http'],['ssh'],['ftp']] server1 = [['mysql'],['firewalld']]  连接  ...

  6. spring boot CrossOrigin不生效?

    直接postman, curl, 浏览器访问后端接口, response header是不会自动加上Access-Control-Allow-Origin的. 需要在ajax中调用,客户端reques ...

  7. 3 不用IDE开发groovy

    1       不用IDE开发groovy 1.1  不用IDE开发的方法 可以在IDE中运行Groovy类或者脚本,但是Groovy也提供了其他运行途径.你能运行Groovy代码基于以下: ·    ...

  8. 用vector实现二维向量

    如果一个向量的每一个元素是一个向量,则称为二维向量,例如 vector<vector<int> >vv(3, vector<int>(4));//这里,两个“> ...

  9. Angular JS 1.X 接口拿不到 http post 请求的数据

    app上加上配置相关的代码即可 var myApp = angular.module('myApp',[]); myApp.config(function($httpProvider){ $httpP ...

  10. Dev Express Report 学习总结(三)关于子报表Sub-Report的使用

    子报表即在一个Report(主报表)中嵌入另一个Report(子报表),从理论上来讲,任何一个Report都可以作为一个子报表,但在实际使用过程中,只有主报表和子报表构成一对多关系时才会使用子报表.使 ...