Ansible playbook之循环

2024-05-01 07:36
文章标签 循环 ansible playbook

本文主要是介绍Ansible playbook之循环,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.标准Loops

        当我们想安装10个软件包的时候,为了避免写10个task来安装,我们可以直接使用标准的loops简单快速实现10个软件包的安装,下面例子是分别打印了one two这两个值:

#1.编写loop.yaml
[root@ansible01 ansible]# cat loops.yaml 
---
- hosts: 11.0.1.18gather_facts: Falsetasks:- name: debug loopsdebug: msg="name --> {{ item }}"with_items:- one- two
#2.运行loop.yaml文件
[root@ansible01 ansible]# ansible-playbook loops.yaml 
PLAY [11.0.1.18] **************************************************************************************************************************************************************************TASK [debug loops] ************************************************************************************************************************************************************************
ok: [11.0.1.18] => (item=one) => {"msg": "name --> one"
}
ok: [11.0.1.18] => (item=two) => {"msg": "name --> two"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

        with_items的值是python list数据结构,可以理解为每个task会循环读取list里面的值,然后key的名称是item,当然list里面也支持python字典,如下:

[root@ansible01 ansible]# cat loops2.yaml 
---
- hosts: 11.0.1.18gather_facts: Falsetasks:- name: debug loopsdebug: msg="name --> {{ item.key }} value -->{{ item.value}}"with_items:- {key: "one",value: "hello"}- {key: "two",value: "wyx"}[root@ansible01 ansible]# ansible-playbook loops2.yaml 
PLAY [11.0.1.18] **************************************************************************************************************************************************************************TASK [debug loops] ************************************************************************************************************************************************************************
ok: [11.0.1.18] => (item={u'value': u'hello', u'key': u'one'}) => {"msg": "name --> one value -->hello"
}
ok: [11.0.1.18] => (item={u'value': u'wyx', u'key': u'two'}) => {"msg": "name --> two value -->wyx"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

2.嵌套Loops

        嵌套Loops也是我们编写playbook中比较常见的一种循环,它主要实现一对多或者多对多的合并,如下:

[root@ansible01 ansible]# cat loops3.yaml 
---
- hosts: 11.0.1.18gather_facts: Falsetasks:- name: debug loopsdebug: msg="name --> {{ item[0] }} value --> {{ item[1] }}"with_nested:- ['A']- ['a','b','c']
[root@ansible01 ansible]# ansible-playbook loops3.yaml 
PLAY [11.0.1.18] **************************************************************************************************************************************************************************TASK [debug loops] ************************************************************************************************************************************************************************
ok: [11.0.1.18] => (item=[u'A', u'a']) => {"msg": "name --> A value --> a"
}
ok: [11.0.1.18] => (item=[u'A', u'b']) => {"msg": "name --> A value --> b"
}
ok: [11.0.1.18] => (item=[u'A', u'c']) => {"msg": "name --> A value --> c"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

3. 散列loops

        散列loops相比标准的loops就是变量支持更丰富的数据结构,比如标准loops的最外层数据必须是Python的list数据类型,而散列loops直接支持YAML格式的数据变量。如下:

[root@ansible01 ansible]# cat loops4.yaml 
---
- hosts: 11.0.1.18gather_facts: Falsevars:user:shencan:name: shencanshell: bashruifengyun:name: ruifengyunshell: zshtasks:- name: debug loopsdebug: msg="name --> {{ item.key }} value --> {{ item.value.name }} shell --> {{ item.value.shell }}"with_dict: "{{ user }}"[root@ansible01 ansible]# ansible-playbook loops4.yaml
PLAY [11.0.1.18] **************************************************************************************************************************************************************************TASK [debug loops] ************************************************************************************************************************************************************************
ok: [11.0.1.18] => (item={u'key': u'ruifengyun', u'value': {u'shell': u'zsh', u'name': u'ruifengyun'}}) => {"msg": "name --> ruifengyun value --> ruifengyun shell --> zsh"
}
ok: [11.0.1.18] => (item={u'key': u'shencan', u'value': {u'shell': u'bash', u'name': u'shencan'}}) => {"msg": "name --> shencan value --> shencan shell --> bash"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

4. 文件匹配loops

        我们针对一个目录下指定格式的文件进行处理时,可以直接引用with_fileglob循环去匹配我们需要处理的文件即可,如下:

[root@ansible01 ansible]# cat /etc/ansible/loops5.yaml 
---
- hosts: 11.0.1.18gather_facts: Falsetasks:- name: debug loopsdebug: msg="files --> {{ item }}"with_fileglob:- /etc/ansible/*.yaml 
[root@ansible01 ansible]# ansible-playbook loops5.yaml
PLAY [11.0.1.18] **************************************************************************************************************************************************************************TASK [debug loops] ************************************************************************************************************************************************************************
ok: [11.0.1.18] => (item=/etc/ansible/loops2.yaml) => {"msg": "files --> /etc/ansible/loops2.yaml"
}
ok: [11.0.1.18] => (item=/etc/ansible/loops3.yaml) => {"msg": "files --> /etc/ansible/loops3.yaml"
}
ok: [11.0.1.18] => (item=/etc/ansible/loops5.yaml) => {"msg": "files --> /etc/ansible/loops5.yaml"
}
ok: [11.0.1.18] => (item=/etc/ansible/loops4.yaml) => {"msg": "files --> /etc/ansible/loops4.yaml"
}
ok: [11.0.1.18] => (item=/etc/ansible/variable.yaml) => {"msg": "files --> /etc/ansible/variable.yaml"
}
ok: [11.0.1.18] => (item=/etc/ansible/variable2.yaml) => {"msg": "files --> /etc/ansible/variable2.yaml"
}
ok: [11.0.1.18] => (item=/etc/ansible/loops.yaml) => {"msg": "files --> /etc/ansible/loops.yaml"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

with_fileglob 这个时候会匹配/etc/ansible下所有的yaml结尾的文件,当作{{ item }}变量来引用。

原理是使用了python glob模块去做的文件模糊匹配。

5. 随机选择loops

        with_random_choice会从传入的list里面随机选择一个,作为item引用的参数

[root@ansible01 ansible]# cat loops6.yaml 
---
- hosts: 11.0.1.18gather_facts: Falsetasks:- name: debug loopsdebug: msg="names --> {{ item }}"with_random_choice:- "ansible1"- "ansible2"- "ansible3"
[root@ansible01 ansible]# ansible-playbook loops6.yaml 
PLAY [11.0.1.18] **************************************************************************************************************************************************************************TASK [debug loops] ************************************************************************************************************************************************************************
ok: [11.0.1.18] => (item=ansible3) => {"msg": "names --> ansible3"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

6. 条件判断loops

        有时候执行一个task后,我们需要检测这个task的结果是否达到了预想状态,如果没有达到我们预想的状态时,就需要退出整个playbook执行,这个时候我们需要对某个task结果一直进行循环检测,如下:

[root@ansible01 ansible]# cat loops7.yaml 
---
- hosts: 11.0.1.18gather_facts: Falsetasks:- name: debug loopsshell: cat /etc/ansible/hostsregister: hostuntil: host.stdout.startswith("Master")retries: 5delay: 5
[root@ansible01 ansible]# ansible-playbook loops7.yaml
PLAY [11.0.1.18] **************************************************************************************************************************************************************************TASK [debug loops] ************************************************************************************************************************************************************************
FAILED - RETRYING: debug loops (5 retries left).
FAILED - RETRYING: debug loops (4 retries left).
FAILED - RETRYING: debug loops (3 retries left).
FAILED - RETRYING: debug loops (2 retries left).
FAILED - RETRYING: debug loops (1 retries left).
fatal: [11.0.1.18]: FAILED! => {"attempts": 5, "changed": true, "cmd": "cat /etc/ansible/hosts", "delta": "0:00:00.005700", "end": "2024-04-30 09:49:27.614588", "rc": 0, "start": "2024-04-30 09:49:27.608888", "stderr": "", "stderr_lines": [], "stdout": "# This is the default ansible 'hosts' file.\n#\n# It should live in /etc/ansible/hosts\n#\n#   - Comments begin with the '#' character\n#   - Blank lines are ignored\n#   - Groups of hosts are delimited by [header] elements\n#   - You can enter hostnames or ip addresses\n#   - A hostname/ip can be a member of multiple groups\n\n# Ex 1: Ungrouped hosts, specify before any group headers.\n\n## green.example.com\n## blue.example.com\n## 192.168.100.1\n## 192.168.100.10\n\n# Ex 2: A collection of hosts belonging to the 'webservers' group\n\n## [webservers]\n## alpha.example.org\n## beta.example.org\n## 192.168.1.100\n## 192.168.1.110\n\n# If you have multiple hosts following a pattern you can specify\n# them like this:\n\n## www[001:006].example.com\n\n# Ex 3: A collection of database servers in the 'dbservers' group\n\n## [dbservers]\n## \n## db01.intranet.mydomain.net\n## db02.intranet.mydomain.net\n## 10.25.1.56\n## 10.25.1.57\n\n# Here's another example of host ranges, this time there are no\n# leading 0s:\n#11.0.1.18\tkey=118\n#11.0.1.19\tkey=119\n[nginx]\n11.0.1.1[8:9]\n[nginx:vars]\nansible_python_interpreter=/usr/bin/python2.7", "stdout_lines": ["# This is the default ansible 'hosts' file.", "#", "# It should live in /etc/ansible/hosts", "#", "#   - Comments begin with the '#' character", "#   - Blank lines are ignored", "#   - Groups of hosts are delimited by [header] elements", "#   - You can enter hostnames or ip addresses", "#   - A hostname/ip can be a member of multiple groups", "", "# Ex 1: Ungrouped hosts, specify before any group headers.", "", "## green.example.com", "## blue.example.com", "## 192.168.100.1", "## 192.168.100.10", "", "# Ex 2: A collection of hosts belonging to the 'webservers' group", "", "## [webservers]", "## alpha.example.org", "## beta.example.org", "## 192.168.1.100", "## 192.168.1.110", "", "# If you have multiple hosts following a pattern you can specify", "# them like this:", "", "## www[001:006].example.com", "", "# Ex 3: A collection of database servers in the 'dbservers' group", "", "## [dbservers]", "## ", "## db01.intranet.mydomain.net", "## db02.intranet.mydomain.net", "## 10.25.1.56", "## 10.25.1.57", "", "# Here's another example of host ranges, this time there are no", "# leading 0s:", "#11.0.1.18\tkey=118", "#11.0.1.19\tkey=119", "[nginx]", "11.0.1.1[8:9]", "[nginx:vars]", "ansible_python_interpreter=/usr/bin/python2.7"]}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   

        5s执行一次cat /etc/ansible/hosts,将结果register给host然后判断host.stdout.startswith的内容是否Master字符串开头,如果条件成立,此task运行完成,如果条件不成立5s后再重试,5次后还不成立,此task运行失败。

7. 文件优先匹配loops

        这个与第4个文件匹配类似,就新增了一个优选项,如下:

[root@ansible01 ansible]# cat loops8.yaml 
---
- hosts: 11.0.1.18gather_facts: Falsetasks:- name: debug loopsdebug: msg="files --> {{ item }}"with_first_found:- "wyx.yaml"
[root@ansible01 ansible]# ansible-playbook loops8.yaml
PLAY [11.0.1.18] **************************************************************************************************************************************************************************TASK [debug loops] ************************************************************************************************************************************************************************
ok: [11.0.1.18] => (item=/etc/ansible/wyx.yaml) => {"msg": "files --> /etc/ansible/wyx.yaml"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

这篇关于Ansible playbook之循环的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/951084

相关文章

Python中顺序结构和循环结构示例代码

《Python中顺序结构和循环结构示例代码》:本文主要介绍Python中的条件语句和循环语句,条件语句用于根据条件执行不同的代码块,循环语句用于重复执行一段代码,文章还详细说明了range函数的使... 目录一、条件语句(1)条件语句的定义(2)条件语句的语法(a)单分支 if(b)双分支 if-else(

Python判断for循环最后一次的6种方法

《Python判断for循环最后一次的6种方法》在Python中,通常我们不会直接判断for循环是否正在执行最后一次迭代,因为Python的for循环是基于可迭代对象的,它不知道也不关心迭代的内部状态... 目录1.使用enuhttp://www.chinasem.cnmerate()和len()来判断for

Java循环创建对象内存溢出的解决方法

《Java循环创建对象内存溢出的解决方法》在Java中,如果在循环中不当地创建大量对象而不及时释放内存,很容易导致内存溢出(OutOfMemoryError),所以本文给大家介绍了Java循环创建对象... 目录问题1. 解决方案2. 示例代码2.1 原始版本(可能导致内存溢出)2.2 修改后的版本问题在

JAVA中while循环的使用与注意事项

《JAVA中while循环的使用与注意事项》:本文主要介绍while循环在编程中的应用,包括其基本结构、语句示例、适用场景以及注意事项,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录while循环1. 什么是while循环2. while循环的语句3.while循环的适用场景以及优势4. 注意

Python中的异步:async 和 await以及操作中的事件循环、回调和异常

《Python中的异步:async和await以及操作中的事件循环、回调和异常》在现代编程中,异步操作在处理I/O密集型任务时,可以显著提高程序的性能和响应速度,Python提供了asyn... 目录引言什么是异步操作?python 中的异步编程基础async 和 await 关键字asyncio 模块理论

好题——hdu2522(小数问题:求1/n的第一个循环节)

好喜欢这题,第一次做小数问题,一开始真心没思路,然后参考了网上的一些资料。 知识点***********************************无限不循环小数即无理数,不能写作两整数之比*****************************(一开始没想到,小学没学好) 此题1/n肯定是一个有限循环小数,了解这些后就能做此题了。 按照除法的机制,用一个函数表示出来就可以了,代码如下

【Linux 从基础到进阶】Ansible自动化运维工具使用

Ansible自动化运维工具使用 Ansible 是一款开源的自动化运维工具,采用无代理架构(agentless),基于 SSH 连接进行管理,具有简单易用、灵活强大、可扩展性高等特点。它广泛用于服务器管理、应用部署、配置管理等任务。本文将介绍 Ansible 的安装、基本使用方法及一些实际运维场景中的应用,旨在帮助运维人员快速上手并熟练运用 Ansible。 1. Ansible的核心概念

poj3750约瑟夫环,循环队列

Description 有N个小孩围成一圈,给他们从1开始依次编号,现指定从第W个开始报数,报到第S个时,该小孩出列,然后从下一个小孩开始报数,仍是报到S个出列,如此重复下去,直到所有的小孩都出列(总人数不足S个时将循环报数),求小孩出列的顺序。 Input 第一行输入小孩的人数N(N<=64) 接下来每行输入一个小孩的名字(人名不超过15个字符) 最后一行输入W,S (W < N),用

如何使用Ansible实现CI/CD流水线的自动化

如何使用Ansible实现CI/CD流水线的自动化 持续集成(CI)和持续交付(CD)是现代软件开发过程中的核心实践,它们帮助团队更快地交付高质量的软件。Ansible,作为一个强大的自动化工具,可以在CI/CD流水线中发挥关键作用。本文将详细介绍如何使用Ansible实现CI/CD流水线的自动化,包括设计流水线的结构、配置管理、自动化测试、部署、以及集成Ansible与CI/CD工具(如Jen

校验码:奇偶校验,CRC循环冗余校验,海明校验码

文章目录 奇偶校验码CRC循环冗余校验码海明校验码 奇偶校验码 码距:任何一种编码都由许多码字构成,任意两个码字之间最少变化的二进制位数就称为数据检验码的码距。 奇偶校验码的编码方法是:由若干位有效信息(如一个字节),再加上一个二进制位(校验位)组成校验码。 奇校验:整个校验码中1的个数为奇数 偶校验:整个校验码中1的个数为偶数 奇偶校验,可检测1位(奇数位)的错误,不可纠错。