循环语句

简介

我们在编写playbook的时候,不可避免的要执行一些重复性操作,比如指安装软件包,批量创建用户,操作某个目录下的所有文件等。正如我们所说,ansible一门简单的自动化语言,所以流程控制、循环语句这些编程语言的基本元素它同样都具备。

下面我们简单的说一说Playbook中循环语句。

loop关键字说明

在playbook中使用循环,直接使用loop关键字即可。

如下示例,启动httpd和postfilx服务:

tasks:
- name: postfix and httpd are running
service:
name: "{{ item }}"
state: started
loop:
- postfix
- httpd

也可以将loop循环的列表提前赋值给一个变量,然后在循环语句中调用:

#cat test_services.yml
test_services:
- postfix
- httpd # cat install_pkgs.yml
- name: start services
hosts: test
vars_files:
- test_services.yml
tasks:
- name: postfix and httpd are running
service:
name: "{{ item }}"
state: started
loop: "{{ test_services }}"

下面是一个循环更复杂类型数据的示例:

# cat test_loop.yml
- name: test loop
hosts: test
tasks:
- name: add www group
group:
name: www
- name: add several users
user:
name: "{{ item.name }}"
state: present
groups: "{{ item.groups }}"
loop:
- { name: 'testuser1', groups: 'wheel' }
- { name: 'testuser2', groups: 'www' }

在循环语句中注册变量

下面是一个register的变量在循环中使用的例子:

# cat register_loop.yml
- name: registered variable usage as a loop list
hosts: test
tasks:
- name: ensure /mnt/bkspool exists
file:
path: /mnt/bkspool
state: directory
- name: retrieve the list of home directories
command: ls /home
register: home_dirs
- name: Show home_dirs results
debug:
var: home_dirs.stdout_lines
- name: add home dirs to the backup spooler
file:
path: /mnt/bkspool/{{ item }}
src: /home/{{ item }}
state: link
force: yes
loop: "{{ home_dirs.stdout_lines }}"

在循环语句中注册变量:

- name: Loop Register test
gather_facts: no
hosts: test
tasks:
- name: Looping Echo Task
shell: "echo this is my item: {{ item }}"
loop:
- one
- two
register: echo_results
- name: Show echo_results variable
debug:
var: echo_results

执行语句,可以看到变量的返回结果为一个字典列表:

ok: [10.1.61.187] => {
"echo_results": {
"changed": true,
"msg": "All items completed",
"results": [
{
"ansible_loop_var": "item",
"changed": true,
"cmd": "echo this is my item: one",
"delta": "0:00:00.004905",
"end": "2019-06-10 00:23:51.814151",
"failed": false,
"invocation": {
"module_args": {
"_raw_params": "echo this is my item: one",
"_uses_shell": true,
"argv": null,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"stdin": null,
"stdin_add_newline": true,
"strip_empty_ends": true,
"warn": true
}
},
"item": "one",
"rc": 0,
"start": "2019-06-10 00:23:51.809246",
"stderr": "",
"stderr_lines": [],
"stdout": "this is my item: one",
"stdout_lines": [
"this is my item: one"
]
},
{
"ansible_loop_var": "item",
"changed": true,
"cmd": "echo this is my item: two",
"delta": "0:00:00.004736",
"end": "2019-06-10 00:23:52.008981",
"failed": false,
"invocation": {
"module_args": {
"_raw_params": "echo this is my item: two",
"_uses_shell": true,
"argv": null,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"stdin": null,
"stdin_add_newline": true,
"strip_empty_ends": true,
"warn": true
}
},
"item": "two",
"rc": 0,
"start": "2019-06-10 00:23:52.004245",
"stderr": "",
"stderr_lines": [],
"stdout": "this is my item: two",
"stdout_lines": [
"this is my item: two"
]
}
]
}
}

旧循环语句

在Ansible 2.5以前,playbook通过不同的循环语句以实现不同的循环,这些语句使用with_作为前缀。这些语法目前仍然兼容,但在未来的某个时间点,会逐步废弃。

循环语句关键字 描述
with_items 简单的列表循环
with_nested 嵌套循环
with_dict 循环字典
with_fileglob 循环指定目录中的所有文件
with_lines 循环一个文件中的所有行
with_sequence 生成一个自增的整数序列,可以指定起始值和结束值以及步长。参数以key=value的形式指定,format指定输出的格式。数字可以是十进制、十六进制、八进制
with_subelement 遍历子元素
with_together 遍历数据并行集合

1. with_items

- hosts: test
vars:
data:
- user0
- user1
- user2
tasks:
- name: "with_items"
debug:
msg: "{{ item }}"
with_items: "{{ data }}"

2. with_nested

tasks:
- name: debug loops
debug: msg="name is {{ item[0] }} vaule is {{ item[1] }} num is {{ item[2] }}"
with_nested:
- ['alice','bob']
- ['a','b','c']
- ['1','2','3']

item[0]是循环的第一个列表的值['alice','bob']。item[1]是第二个列表的值;item[2]则是第三个列表的值,以上的执行输出如下:

# ansible-playbook with_nested_ex.yml 

PLAY [with_nested test] ******************************************************************************************

TASK [Gathering Facts] *******************************************************************************************
ok: [10.1.61.187] TASK [debug loops] ***********************************************************************************************
ok: [10.1.61.187] => (item=['alice', 'a', '1']) => {
"msg": "name is alice vaule is a num is 1"
}
ok: [10.1.61.187] => (item=['alice', 'a', '2']) => {
"msg": "name is alice vaule is a num is 2"
}
ok: [10.1.61.187] => (item=['alice', 'a', '3']) => {
"msg": "name is alice vaule is a num is 3"
}
ok: [10.1.61.187] => (item=['alice', 'b', '1']) => {
"msg": "name is alice vaule is b num is 1"
}
ok: [10.1.61.187] => (item=['alice', 'b', '2']) => {
"msg": "name is alice vaule is b num is 2"
}
ok: [10.1.61.187] => (item=['alice', 'b', '3']) => {
"msg": "name is alice vaule is b num is 3"
}
ok: [10.1.61.187] => (item=['alice', 'c', '1']) => {
"msg": "name is alice vaule is c num is 1"
}
ok: [10.1.61.187] => (item=['alice', 'c', '2']) => {
"msg": "name is alice vaule is c num is 2"
}
ok: [10.1.61.187] => (item=['alice', 'c', '3']) => {
"msg": "name is alice vaule is c num is 3"
}
ok: [10.1.61.187] => (item=['bob', 'a', '1']) => {
"msg": "name is bob vaule is a num is 1"
}
ok: [10.1.61.187] => (item=['bob', 'a', '2']) => {
"msg": "name is bob vaule is a num is 2"
}
ok: [10.1.61.187] => (item=['bob', 'a', '3']) => {
"msg": "name is bob vaule is a num is 3"
}
ok: [10.1.61.187] => (item=['bob', 'b', '1']) => {
"msg": "name is bob vaule is b num is 1"
}
ok: [10.1.61.187] => (item=['bob', 'b', '2']) => {
"msg": "name is bob vaule is b num is 2"
}
ok: [10.1.61.187] => (item=['bob', 'b', '3']) => {
"msg": "name is bob vaule is b num is 3"
}
ok: [10.1.61.187] => (item=['bob', 'c', '1']) => {
"msg": "name is bob vaule is c num is 1"
}
ok: [10.1.61.187] => (item=['bob', 'c', '2']) => {
"msg": "name is bob vaule is c num is 2"
}
ok: [10.1.61.187] => (item=['bob', 'c', '3']) => {
"msg": "name is bob vaule is c num is 3"
} PLAY RECAP *******************************************************************************************************
10.1.61.187

3. 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 }}"

4. with_fileglob

- hosts: test
tasks:
- name: Make key directory
file:
path: /root/.sshkeys
state: directory
mode: 0700
owner: root
group: root - name: Upload public keys
copy:
src: "{{ item }}"
dest: /root/.sshkeys
mode: 0600
owner: root
group: root
with_fileglob:
- /root/.ssh/*.pub - name: Assemble keys into authorized_keys file
assemble:
src: /root/.sshkeys
dest: /root/.ssh/authorized_keys
mode: 0600
owner: root
group: root

5. with_lines

with_lines循环结构会让你在控制主机上执行任意命令,并对命令的输出进行逐行迭代。假设我们有一个 文件test.txt包含如下行:

Breeze Yan
Bernie Yang
jerry Qing

我们可以通过如下方法进行逐行输出:

- name: print all names
debug: msg="{{ item }}"
with_lines:
- cat test.txt

6. with_subelement

假如现在需要遍历一个用户列表,并创建每个用户,而且还需要为每个用户配置以特定的SSH key登录。变量文件内容如下:

users:
- name: alice
authorized:
- /tmp/alice/onekey.pub
- /tmp/alice/twokey.pub
mysql:
password: mysql-password
hosts:
- "%"
- "127.0.0.1"
- "::1"
- "localhost"
privs:
- "*.*:SELECT"
- "DB1.*:ALL"
- name: bob
authorized:
- /tmp/bob/id_rsa.pub
mysql:
password: other-mysql-password
hosts:
- "db1"
privs:
- "*.*:SELECT"
- "DB2.*:ALL"

playbook中定义如下:

tasks:
- 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

也可以遍历嵌套的子列表:

- name: Setup MySQL users
mysql_user: name={{ item.0.name }} password={{ item.0.mysql.password }} host={{ item.1 }} priv={{ item.0.mysql.privs | join('/') }}
with_subelements:
- users
- mysql.hosts

7. 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%02d
# 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 # stride用于指定步长
# a simpler way to use the sequence plugin
# create 4 groups
- group: name=group{{ item }} state=present
with_sequence: count=4

8. with_random_choice

从列表中随机取一个值:

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

9. do-Util循环

- action: shell /usr/bin/foo
register: result
until: result.stdout.find("all systems go") != -1
retries: 5
delay: 10

重复执行shell模块,当shell模块执行的命令输出内容包含"all systems go"的时候停止。重试5次,延迟时间10秒。retries默认值为3,delay默认值为5。任务的返回值为最后一次循环的返回结果。

10. with_together

示例:

- hosts: webservers
remote_user: root
vars:
alpha: [ 'a','b','c','d']
numbers: [ 1,2,3,4 ]
tasks:
- debug: msg="{{ item.0 }} and {{ item.1 }}"
with_together:
- "{{ alpha }}"
- "{{ numbers }}"
# 输出的结果为:
ok: [192.168.1.65] => (item=['a', 1]) => {
"item": [
"a",
1
],
"msg": "a and 1"
}
ok: [192.168.1.65] => (item=['b', 2]) => {
"item": [
"b",
2
],
"msg": "b and 2"
}
ok: [192.168.1.65] => (item=['c', 3]) => {
"item": [
"c",
3
],
"msg": "c and 3"
}
ok: [192.168.1.65] => (item=['d', 4]) => {
"item": [
"d",
4
],
"msg": "d and 4"
}

Ansible13:Playbook循环语句的更多相关文章

  1. Ansible8:Playbook循环【转】

    在使用ansible做自动化运维的时候,免不了的要重复执行某些操作,如:添加几个用户,创建几个MySQL用户并为之赋予权限,操作某个目录下所有文件等等.好在playbook支持循环语句,可以使得某些需 ...

  2. Ansible Playbook 循环

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

  3. Ansible14:Playbook条件语句

    目录 简介 when关键字 1. when基本使用 2. 比较运算符 3. 逻辑运算符 条件判断与tests 判断变量 判断执行结果 判断路径 判断字符串 判断整除 其他tests 条件判断与bloc ...

  4. 010.Ansible_palybook 循环语句

    Ansible循环语句 1 简介 我们在编写playbook的时候,不可避免的要执行一些重复性操作,比如指安装软件包,批量创建用户,操作某个目录下的所有文件等.正如我们所说,ansible一门简单的自 ...

  5. 【python之路4】循环语句之while

    1.while 循环语句 #!/usr/bin/env python # -*- coding:utf-8 -*- import time bol = True while bol: print '1 ...

  6. python之最强王者(3)——变量,条件、循环语句

    1.Python 变量类型 变量存储在内存中的值.这就意味着在创建变量时会在内存中开辟一个空间. 基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中. 因此,变量可以指定不同的 ...

  7. #9.5课堂JS总结#循环语句、函数

    一.循环语句 1.for循环 下面是 for 循环的语法: for (语句 1; 语句 2; 语句 3) { 被执行的代码块 } 语句 1 在循环(代码块)开始前执行 语句 2 定义运行循环(代码块) ...

  8. 详解Python中的循环语句的用法

    一.简介 Python的条件和循环语句,决定了程序的控制流程,体现结构的多样性.须重要理解,if.while.for以及与它们相搭配的 else. elif.break.continue和pass语句 ...

  9. 【java开发】分支语句、循环语句学习

    一.Java分支语句类型 if-else 语句 switch 关于if-esle语句可以拆分为三种 if语句 if(条件){语句块;} if-else语句if(条件语句){语句块;} if-else ...

随机推荐

  1. 微信页面script标签添加crossorigin=“anonymous”导致页面加载失败

    公司一个微信企业号项目,突然出现页面数据加载失败,页面报错信息如下 意思是前端向服务端发送跨域资源请求访问这个js文件,但是服务端并不同意,所以服务端拒绝访问这个地址. 后来发现将crossorigi ...

  2. msgTips 顶部弹窗

    最近发现好多网站都采用顶部弹窗,并且不用用户手动去点击确定.感觉这样很方便用户,所以也找了好多大神的代码,整理一下方便以后查找 前端: @{ Layout = null; } <!DOCTYPE ...

  3. ObjC: 委托模式

    转自:http://marshal.easymorse.com/tech/objc-%e5%a7%94%e6%89%98%e6%a8%a1%e5%bc%8f 在ObjC中,经常提到委托模式(deleg ...

  4. 分析mybatis中 #{} 和${}的区别

    分析方法: 在 GenericTokenParser这个类的parse方法的这一行下个断点调试一下就明白了 builder.append(handler.handleToken(content)); ...

  5. zookeeper中的QuorumPeerMain解析

    https://www.cnblogs.com/7758521gorden/p/8006983.html zookeeper中的QuorumPeerMain解析   在一个初级的hadoop与zook ...

  6. Jmeter(四十四)启动提示 Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.

    有已知的已知:有些事情我们自己知道自己知道: 我们也知道有已知的未知:这是指我们知道有些事情自己不知道: 但是还有未知的未知:有些事情我们不知道自己不知道:   ---美国国防部长 唐纳德·拉姆斯菲尔 ...

  7. ubuntu使用anaconda安装tensorflow

    https://blog.csdn.net/shiheyingzhe/article/details/80863422 https://blog.csdn.net/sheyanshangjiang/a ...

  8. 网络协议 11 - Socket 编程(下)

    之前我们基本了解了网络通信里的大部分协议,一直都是在“听”的过程.很多人都会觉得,好像看懂了,但关了页面回忆起来,好像又什么都没懂.这次咱们就“真枪实弹”的码起来,再用一个“神器”-网络分析系统详细跟 ...

  9. ZROI 暑期高端峰会 A班 Day6 离线问题

    FBI Warning:本文含有大量人类本质之一. 动态联通问题 允许离线. 模板,不讲了. 归并排序 %@)(#&%)++%($@)%!#(&%)(&@))) 主定理 U^( ...

  10. The import junit cannot be resolved解决问题

    第一次安装Junit,配置环境之后发现添加语句import junit.framework.TestCase; 编译错误 解决:项目右键Properties->Java Build Path-& ...