amazon-web-services - 在 with_items 循环中迭代 ansible
问题描述
嗨,我正在 atm 尝试使用 aws 掌握 ansible 的窍门,到目前为止我真的很喜欢它的灵活性。
可悲的是,现在我的实验开始碰壁了。我正在尝试为具有标签environment: test with the tags environment: test and backup: true的特定实例标记卷。如果我在 with_items 循环中指定数组的每个索引,则剧本按预期工作。到目前为止,这是我的剧本:
---
- name: Tag the EBS Volumes
hosts: tag_environment_test
gather_facts: False
tags: tag
vars_files:
- /etc/ansible/vars/aws.yml
tasks:
- name: Gather instance instance_ids
local_action:
module: ec2_remote_facts
region: '{{ aws_region }}'
filters:
instance-state-name: running
"tag:environment": test
register: test_id
- name: Gather volume information for instance
local_action:
module: ec2_vol
region: '{{ aws_region }}'
instance: "{{ item.id }}"
state: list
with_items:
- "{{ test_id.instances }}"
register: ec2_volumes
- debug:
var: ec2_volumes
- name: Do some actual tagging
local_action:
module: ec2_tag
region: '{{ aws_region }}'
resource: "{{ item.id }}"
args:
tags:
environment: test
backup: true
with_items:
- "{{ ec2_volumes.results[0].volumes }}"
# - "{{ ec2_volumes.results[1].volumes }}"
我现在的问题是可以遍历 ec2_volumes.results 中的整个数组,而无需指定数组中的每个值。例如_ec2_volumes.results[X].volumes X=X+1_所以每次他通过循环时,他都会迭代 +1 直到数组结束。
剧本其余部分的每个输入也会非常受欢迎(就像我说的那样,仍在尝试掌握 ansible 的窍门。:)
问候德雷斯
解决方案
您可以遍历您的结果列表:
- name: Do some actual tagging
delegate_to: localhost
ec2_tag:
region: '{{ aws_region }}'
resource: "{{ item.volume.id }}"
tags:
environment: test
backup: true
with_items: "{{ ec2_volumes.results }}"
非常感谢剧本其余部分的每个输入
考虑使用delegate_to: localhost
而不是local_action
. 考虑这个任务:
- name: an example
command: do something
使用delegate_to
,我只需要添加一行:
- name: an example
delegate_to: localhost
command: do something
而使用local_action
我需要重写任务:
- name: an example
local_action:
module: command do something
当然,delegate_to
它更灵活:您可以使用它来委托给 localhost 以外的主机。
更新
如果没有看到您的实际剧本,就很难确定错误的来源。这是一个成功运行的完整剧本(使用合成数据并将您的ec2_tag
任务包装在一个debug
任务中):
---
- hosts: localhost
gather_facts: false
vars:
aws_region: example
ec2_volumes:
results:
- volume:
id: 1
- volume:
id: 2
tasks:
- name: Do some actual tagging
debug:
msg:
ec2_tag:
region: '{{ aws_region }}'
resource: '{{ item.volume.id }}'
tags:
environment: test
backup: true
with_items: "{{ ec2_volumes.results }}"
推荐阅读
- ejabberd - 是否有任何 API 可以更改用户的用户名
- c - malloc() 和 memset() 行为
- algorithm - 什么构成指数时间复杂度?
- asp.net-core - IdentityServer4 与 InMemory 存储的集成测试
- node.js - ExpressJS 中间件 bodyParser 性能很差
- java - Spring Cloud Stream:动态输出通道的奇怪行为
- html - 将 Div 设置为在屏幕尺寸缩小时移动到另一个 Div 下方
- c++ - 如何从输出中删除这些额外的箭头?
- excel - 如果为一列 Max,则在 A 列中选择与 MAX 对应的名称
- javascript - 这个正则表达式是否匹配我想要匹配的内容?