Cannot delete vpc of AWS using ansible - ansible

Have created a vpc with a subnet. Deleted the instance in that subnet. So, the subnet and vpc doesn't contain any more instances(dependencies).
Further, the vpc can be deleted from the console. But when attempted through ec2_vpc module, gives the error stating "dependencies are present under this vpc so cannot be deleted". But it can see deleted from the console.
So thought that subnet under this vpc may be the dependency. The ansible documentation provides module for subnet but when used it gives the module doesn't exist stating "illegal parameter"
The image showing the route table which cannot be deleted by snippet given by olle
[IMG]http://i59.tinypic.com/2d7xwxt.png[/IMG]

I am using this code to create a VPC with ansible
- name: create a VPC
local_action:
module: ec2_vpc
state: present
cidr_block: 10.0.0.0/16
resource_tags: "{}"
subnets:
- cidr: 10.0.0.0/16
internet_gateway: True
route_tables:
- subnets:
- 10.0.0.0/16
routes:
- dest: 0.0.0.0/0
gw: igw
region: '{{ region }}'
wait: yes
register: vpc
and the following two commands to remove it.
The first command removes the subnets, the IGW and the routing tables.
- name: remove subnets and route tables from VPC
local_action:
module: ec2_vpc
vpc_id: "{{ vpc.vpc_id }}"
region: "{{ region }}"
state: present
resource_tags: "{}"
subnets: []
internet_gateway: False
route_tables: []
wait: yes
and then I can remove the actual VPC
- name: delete VPC
local_action:
module: ec2_vpc
vpc_id: "{{ vpc.vpc_id }}"
region: "{{ region }}"
state: absent
resource_tags: "{}"
wait: yes
Hope this helps you.

Ansible has provided ec2_vpc_net module for VPC, you can create or delete the VPC.
Ex:
- name: DELETE THE VPC
ec2_vpc_net:
name: vpc_name
cidr_block: "{{ build_env.vpc_net_cidr }}".
region: "{{ build_env.region }}"
profile: "{{ build_env.profile }}"
state: absent
purge_cidrs: yes
register: vpc_delete
Hope this helps

Related

Launch instance in AWS and add in host file in ansible (not dynaminc inventory)

I have a lot of inventories inside ansible. I not looking for a dynamic inventory solution.
When I create an instance from ansible in AWS, I need to run some tasks inside that new server but I don’t know what is the best way to do it.
tasks:
- ec2:
aws_secret_key: "{{ ec2_secret_key }}"
aws_access_key: "{{ ec2_access_key }}"
region: us-west-2
key_name: xxxxxxxxxx
instance_type: t2.medium
image: ami-xxxxxxxxxxxxxxxxxx
wait: yes
wait_timeout: 500
volumes:
- device_name: /dev/xvda
volume_type: gp3
volume_size: 20
delete_on_termination: yes
vpc_subnet_id: subnet-xxxxxxxxxxxx
assign_public_ip: no
instance_tags:
Name: new-instances
count: 1
- name: Buscamos la IP de la instancia creada
ec2_instance_facts:
filters:
"tag:Name": new-instances
register: ec2_instance_info
- set_fact:
msg: "{{ ec2_instance_info | json_query('instances[*].private_ip_address') }} "
- debug: var=msg
I currently show the IP of the new instance but I need to create a new host file and insert the IP of the new instance alias as I need to run several tasks after creating it.
Any help doing this?

How to check for string when not in variable

I am trying to create a ec2 volume and attache to EC2 if device is not present.
here is my code:
vars:
region: us-east-1
ec2_instance_id: i-xxxxxxxx
ec2_volume_size: 5
ec2_volume_name: chompx
ec2_device_name: "/dev/sdf"
tasks:
- name: List volumes for an instance
ec2_instance_facts:
instance_ids: "{{ ec2_instance_id }}"
region: "{{ region }}"
register: ec2
- debug: msg="{{ ec2.instances[0].block_device_mappings | list }}"
- name: Create new volume using SSD storage
ec2_vol:
region: "{{ region }}"
instance: "{{ ec2_instance_id }}"
volume_size: "{{ ec2_volume_size }}"
volume_type: gp2
state: present
when: "ec2_device_name not in ec2"
Problem,
Create volume code is still getting executed even when /dev/sdf is present in ec2 variable.
register: ec2 creates an object with all the information about the task that was run. You are trying to operate on only the results of that command.
You probably need:
when: "ec2_device_name not in ec2.stdout_lines" # ec2.stdout_lines should be a list
But I'm not 100% sure on the output of that command. Check it by adding a debug statement:
- debug: var=ec2

Ansible: ec2_eni cannot attach interface

Using ansible I am trying to create ec2 instances and attach an extra network interface to each instance so that they will have two private IP addresses. However, for some reason, it seems that the ec2_eni module can create network interfaces, but will not attach them to the instances specified. What am I doing wrong? Below is my playbook:
---
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: Create new servers
ec2:
region: "{{ region }}"
vpc_subnet_id: "{{ subnet }}"
group_id: "{{ sec_group }}"
assign_public_ip: yes
wait: true
key_name: '{{ key }}'
instance_type: t2.micro
image: '{{ ami }}'
exact_count: '{{ count }}'
count_tag:
Name: "{{ server_name }}"
instance_tags:
Name: "{{ server_name }}"
register: ec2
- name: Show ec2 instance json data
debug:
msg: "{{ ec2['tagged_instances'] }}"
- name: allocate new elastic IPs and associate it with instances
ec2_eip:
region: "{{ region }}"
device_id: "{{ item['id'] }}"
with_items: "{{ ec2['tagged_instances'] }}"
register: eips
- name: Show eip instance json data
debug:
msg: "{{ eips['results'] }}"
- ec2_eni:
subnet_id: "{{ subnet }}"
state: present
secondary_private_ip_address_count: 1
security_groups: "{{ sec_group }}"
region: "{{ region }}"
device_index: 1
description: "test-eni"
instance_id: "{{ item['id'] }}"
with_items: "{{ ec2['tagged_instances'] }}"
The strange thing is that the ec2_eni task succeeds, saying that it has attached the network interface to each instance when in reality it just creates the network interface and then does nothing with it.
As best I can tell, since attached defaults to None, but the module docs say:
Specifies if network interface should be attached or detached from instance. If ommited, attachment status won't change
then the code does what they claim and skips the attachment step.
This appears to be a bug in the documentation, which claims the default is 'yes' but is not accurate.

How do I add routes to a VPC's default/main route table with Ansible ec2_vpc_route_table?

I'm having real trouble adding additional routes to a newly created VPC's default Route Table in a NAT scenario using Ansible and the ec2_vpc_route_table module. The related excerpts from my Playbook are...
Creating the VPC
- name: Create Production VPC
ec2_vpc:
region: "{{ aws.region }}"
aws_access_key: "{{ aws.access_key }}"
aws_secret_key: "{{ aws.secret_key }}"
state: present
cidr_block: 10.0.0.0/16
resource_tags: { "Name":"Production" }
internet_gateway: yes
dns_hostnames: yes
dns_support: yes
subnets:
- cidr: 10.0.10.0/24
resource_tags: { "Name":"A - NAT" }
- cidr: 10.0.20.0/24
resource_tags: { "Name":"B - Public" }
- cidr: 10.0.30.0/24
resource_tags: { "Name":"C - Private" }
wait: yes
register: prod_vpc
Gather facts and append new routes
- name: Gather default Route Table facts
ec2_vpc_route_table_facts:
region: "{{ aws.region }}"
filters:
vpc-id: "{{ prod_vpc.vpc.id }}"
register: vpc_default_route
- name: Add NAT routes
ec2_vpc_route_table:
aws_access_key: "{{ aws.access_key }}"
aws_secret_key: "{{ aws.secret_key }}"
vpc_id: "{{ prod_vpc.vpc.id }}"
region: "{{ aws.region }}"
route_table_id: "{{ vpc_default_route.route_tables[0].id }}"
lookup: id
tags:
Name: NAT
subnets:
- '10.0.10.0/24'
routes:
- dest: 0.0.0.0/0
gateway_id: igw
So first off, I tried to include the creation of the routes within the ec2_vpc task, but that actually ended up creating a second Route Table rather than including the routes in the default table.
So first off, why does a second table get created instead of adding the routes to the default?
Because including it in the vpc creation wasn't working I fell back on the above, which just identifies the default, or main Route Table. The problem now is that when I try to use ec2_vpc_route_table to add the NAT route, Ansible fails with the following error...
fatal: [localhost]: FAILED! => {"changed": false, "failed": true, "msg": "Unable to associate subnets for route table RouteTable:rtb-..., error: EC2ResponseError: 400 Bad Request\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Response><Errors><Error><Code>InvalidParameterValue</Code><Message>cannot disassociate the main route table association rtbassoc-...</Message></Error></Errors><RequestID>...</RequestID></Response>"}
That error makes it sound like, dispite the fact I'm explicitly providing route_table_id, and lookup: id, that it's not updating the existing table, but it's basically recreating it, trying to delete the original (which is the main route table) in the process.
How can I append additional routes to an existing main route table?
So far the only workaround I've been able to use is to call the EC2 CLI via the command: ... method, but that's obviously not ideal.
We're on Ansible 2.3.0 (devel 14a2757116)
Any help would be greatly appreciated!
I've managed to update the main route table by looking it up and then using the route_table_id to modify it.
- name: Lookup VPC facts
ec2_vpc_net_facts:
region: "{{ region }}"
filters:
"tag:Name": "{{ vpc_name }}"
register: vpc_group
- name: Create vgw
ec2_vpc_vgw:
region: "{{ region }}"
vpc_id: "{{ vpc_group.vpcs[0].id }}"
name: "{{ vpc_name }}"
type: ipsec.1
state: present
validate_certs: no
register: vpc_vgw
- name: Create igw
ec2_vpc_igw:
region: "{{ region }}"
vpc_id: "{{ vpc_group.vpcs[0].id }}"
state: present
validate_certs: no
register: igw
- name: Lookup route tables
ec2_vpc_route_table_facts:
region: "{{ region }}"
filters:
vpc-id: "{{ vpc_group.vpcs[0].id }}"
register: vpc_route_tables
- name: Setup route tables
ec2_vpc_route_table:
region: "{{ region }}"
vpc_id: "{{ vpc_group.vpcs[0].id }}"
lookup: id
purge_subnets: false
route_table_id: "{{ vpc_route_tables.route_tables[0].id }}"
subnets: "{{ subnet_ids }}"
routes:
- dest: 10.0.0.0/8
gateway_id: "{{ vpc_vgw.vgw.id }}"
- dest: 0.0.0.0/0
gateway_id: "{{ igw.gateway_id }}"
Note: You need to disable purging the subnets otherwise you'll get an error when ansible tries to remove the default subnet association from the main route_table.
From http://docs.ansible.com/ansible/ec2_vpc_route_table_module.html#options
Look up route table by either tags or by route table ID. Non-unique tag lookup will fail. If no tags are specifed then no lookup for an existing route table is performed and a new route table will be created. To change tags of a route table or delete a route table, you must look up by id.
Try lookup: tag instead of lookup: id.
That should work.

Connect EC2 instance to Target Group using Ansible

I have been working for a while registering EC2 instances to ELB's using Ansible. But now I'm starting to use ALB's and I need to connect my instances to Target Groups which in turn are connected to the ALB. Is there an Ansible plugin that allows me to register an instance to a AWS Target Group?
Since Ansible does not support registration of instances to target groups I had to use the AWS-CLI tool. With the following command you can register an instance to a target group:
aws elbv2 register-targets --target-group-arn arn:aws:elasticloadbalancing:us-east-1:your-target-group --targets Id=i-your-instance
So I just call this command from Ansible and it's done.
Use elb_target:
name: Gather facts for all new proxy instances
ec2_instance_facts:
filters:
"tag:Name": "{{ ec2_tag_proxy }}"
register: ec2_proxy
elb_target_group:
name: uat-target-proxy
protocol: http
port: 80
vpc_id: vpc-4e6e8112
deregistration_delay_timeout: 60
stickiness_enabled: True
stickiness_lb_cookie_duration: 86400
health_check_path: /
successful_response_codes: "200"
health_check_interval: "20"
state: present
elb_target:
target_group_name: uat-target-proxy
target_id: "{{ item.instance_id }}"
target_port: 80
state: present
with_items: "{{ ec2_proxy.instances }}"
when: ec2_proxy.instances|length > 0
Try the following configurations:
- name: creating target group
local_action:
module: elb_target_group
region: us-east-2
vpc_id: yourvpcid
name: create-targetgrp-delete
protocol: https
port: 443
health_check_path: /
successful_response_codes: "200,250-260"
state: present
targets:
- Id: ec2isntanceid
Port: 443
wait_timeout: 200
register: tgp

Resources