loops over the registered variable to inspect the

2019-08-24 19:34发布

I have an ansible-playbook that creates the multiple ec2 security groups using with_items and register the result.

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

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

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

Can somebody point me that how I can get the group_id for each group from the register result. Thanks

P.S: I can get the value of the group_id for individual sg group like:

aws_sg.results[0].group_id and aws_sg.results[1].group_id etc

1条回答
混吃等死
2楼-- · 2019-08-24 19:46

RTM. Ansible would set the loop variable item for each iteration.

aws_sg.results[0].group_id and aws_sg.results[1].group_id etc

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 }}"
查看更多
登录 后发表回答