ansible之loops
来源:互联网 发布:如何防御网络攻击 编辑:程序博客网 时间:2024/05/22 10:29
有时候,你想在一个task进行很多重复的操作,例如创建用户、安装包、或者重复执行一个操作直到某个希望的状态。
Standard Loops 标准循环
为了少打一些字,可以这样写重复的任务:
- name: add several users user: name: "{{ item }}" state: present groups: "wheel" with_items: - testuser1 - testuser2
如果有定义了yaml格式的list在变量文件中,或变量段落,可以这样做:
with_items: "{{ somelist }}"
上面的例子,等价于:
- name: add user testuser1 user: name: "testuser1" state: present groups: "wheel"- name: add user testuser2 user: name: "testuser2" state: present groups: "wheel"
所以呢,用loops更加灵活。
yum和apt模块可以用with_item来执行较少的包管理事务。
- 注意
用with_items来迭代的时候,其值不一定是字符串,还可以是哈希(hashes):
- name: add several users user: name: "{{ item.name }}" state: present groups: "{{ item.groups }}" with_items: - { name: 'testuser1', groups: 'wheel' } - { name: 'testuser2', groups: 'root' }
这样会更加灵活。
loops其实是with_
和<lookup>
的组合,所以任何<lookup>
都可以当做源来迭代,上面的例子就是用了items这个<lookup>
Looping over Hashes从哈希列表循环
假设我定义了这样一个变量:
---users: alice: name: Alice Appleworth telephone: 123-456-7890 bob: name: Bob Bananarama telephone: 987-654-3210
我现在要打印出名字和电话,可以用with_dict从哈希中取值:
tasks: - name: Print phone records debug: msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})" with_dict: "{{ users }}"
格式化输出,挺好用的。
Looping over Files 从文件中循环
with_file可以遍历文件列表的内容,item将按顺序设置为每个文件的内容:
---- hosts: all tasks: # emit a debug message containing the content of each file. - debug: msg: "{{ item }}" with_file: - first_example_file - second_example_file
假如第一个文件内容为hello,第二个文件内容为world,那么上面的执行结果如下:
TASK [debug msg={{ item }}] ******************************************************ok: [localhost] => (item=hello) => { "item": "hello", "msg": "hello"}ok: [localhost] => (item=world) => { "item": "world", "msg": "world"}
阅读全文
0 0
- ansible之loops
- 使用Ansible loops编写循环
- ansible学习之--ansible初探
- loops
- Ansible(二):Ansible之剧本(Playbooks)
- ansible之并发运行
- ansible register 之用法
- LINUX学习之ANSIBLE
- ansible之inventory文件
- ansible之yaml语法
- ansible之patterns
- ansible之playbook入门
- ansible之variable
- ansible之条件语句
- ansible之并发运行
- ansible学习之--安装Svn
- python之ansible 2.0 API
- Ansible之playbook学习一
- HTML中的role属性
- Beanstalkd+Supervisor构建消息队列
- 循环神经网络RNN
- opencv cmakelists
- JAVA 定时器的三种方法
- ansible之loops
- 学习mysql时经常用到的语句和错误
- 关于javax.mail.MessagingException: Could not connect to SMTP host: smtp.qq.com, port: 25;
- onclick和click的区别及示例
- Runnable JAR file spring + mybatis 普通项目(非maven 非springboot)
- scikit-learn 梯度提升树(GBDT)调参小结
- windows 下c++获取操作系统版本名称笔记
- python测试opencv时imread导致的错误
- 线性回归与岭回归python代码实现