循环注册变量以检查 ansible 中的结果 [英] loops over the registered variable to inspect the results in ansible
问题描述
我有一个 ansible-playbook,它使用 with_items 创建多个 ec2 安全组并注册结果.
I have an ansible-playbook that creates the multiple ec2 security groups using with_items and register the result.
这是该剧本的 var 文件:
here is the var file for this playbook:
---
ec2_security_groups:
- sg_name: nat_sg
sg_description: This sg is for nat instance
sg_rules:
- proto: tcp
from_port: 22
to_port: 22
cidr_ip: 0.0.0.0/0
- sg_name: web_sg
sg_description: This sg is for web instance
sg_rules:
- proto: tcp
from_port: 22
to_port: 22
cidr_ip: 0.0.0.0/0
- proto: tcp
from_port: 80
to_port: 80
cidr_ip: 0.0.0.0/0
这是创建 ec2 安全组的剧本:
and here is the playbook that creates the ec2 security groups:
---
- name: EC2Group | Creating an EC2 Security Group inside the Mentioned VPC
local_action:
module: ec2_group
name: "{{ item.sg_name }}"
description: "{{ item.sg_description }}"
region: "{{ vpc_region }}" # Change the AWS region here
vpc_id: "{{ vpc.vpc_id }}" # vpc is the resgister name, you can also set it manually
state: present
rules: "{{ item.sg_rules }}"
with_items: ec2_security_groups
register: aws_sg
这很有效,但问题是,我想获取此剧本为下一个任务创建的每个组的组 ID,我已经尝试过,但失败了:
This works very well but the problem is that, I want to get the group id of each group that this playbook has created for the next task, I have tried it but it failed:
- name: Tag the security group with a name
local_action:
module: ec2_tag
resource: "{{aws_sg.group_id}}"
region: "{{ vpc_region }}"
state: present
tags:
Name: "{{vpc_name }}-group"
with_items: aws_sg.results
有人可以指出我如何从注册结果中获取每个组的 group_id.谢谢
Can somebody point me that how I can get the group_id for each group from the register result. Thanks
P.S:我可以获取单个 sg 组的 group_id 值,例如:
P.S: I can get the value of the group_id for individual sg group like:
aws_sg.results[0].group_id 和 aws_sg.results[1].group_id 等
aws_sg.results[0].group_id and aws_sg.results[1].group_id etc
推荐答案
RTM.Ansible 会为每次迭代设置循环变量 item
.
RTM. Ansible would set the loop variable item
for each iteration.
aws_sg.results[0].group_id 和 aws_sg.results[1].group_id 等
aws_sg.results[0].group_id and aws_sg.results[1].group_id etc
假设你上面写的是正确的.您需要将 aws_sg.group_id
更改为 item.group_id
:
Assuming what you wrote above is correct. You need to change aws_sg.group_id
to item.group_id
:
- name: Tag the security group with a name
local_action:
module: ec2_tag
resource: "{{ item.group_id }}"
region: "{{ vpc_region }}"
state: present
tags:
Name: "{{vpc_name }}-group"
with_items: aws_sg.results
如果这不起作用,则发布此任务的输出以进行更正:
If this doesn't work then post the output of this task for corrections:
- debug: msg="aws_sg= {{ aws_sg }}"
这篇关于循环注册变量以检查 ansible 中的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!