Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ec2_vpc_peer should remove peering connections #20113

Merged
merged 2 commits into from
Feb 15, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
96 changes: 61 additions & 35 deletions lib/ansible/modules/cloud/amazon/ec2_vpc_peer.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.

ANSIBLE_METADATA = {'status': ['stableinterface'],
'supported_by': 'committer',
'version': '1.0'}
Expand Down Expand Up @@ -192,13 +193,14 @@
type: dictionary
'''

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import boto3_conn, ec2_argument_spec
from ansible.module_utils.ec2 import get_aws_connection_info, HAS_BOTO3

try:
import json
import botocore
import boto3
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
pass # caught by imported HAS_BOTO3


def tags_changed(pcx_id, client, module):
Expand All @@ -224,15 +226,19 @@ def tags_changed(pcx_id, client, module):


def describe_peering_connections(params, client):
result = client.describe_vpc_peering_connections(Filters=[
{'Name': 'requester-vpc-info.vpc-id', 'Values': [params['VpcId']]},
{'Name': 'accepter-vpc-info.vpc-id', 'Values': [params['PeerVpcId']]}
])
result = client.describe_vpc_peering_connections(
Filters=[
{'Name': 'requester-vpc-info.vpc-id', 'Values': [params['VpcId']]},
{'Name': 'accepter-vpc-info.vpc-id', 'Values': [params['PeerVpcId']]}
]
)
if result['VpcPeeringConnections'] == []:
result = client.describe_vpc_peering_connections(Filters=[
{'Name': 'requester-vpc-info.vpc-id', 'Values': [params['PeerVpcId']]},
{'Name': 'accepter-vpc-info.vpc-id', 'Values': [params['VpcId']]}
])
result = client.describe_vpc_peering_connections(
Filters=[
{'Name': 'requester-vpc-info.vpc-id', 'Values': [params['PeerVpcId']]},
{'Name': 'accepter-vpc-info.vpc-id', 'Values': [params['VpcId']]}
]
)
return result


Expand Down Expand Up @@ -272,26 +278,46 @@ def create_peer_connection(client, module):
module.fail_json(msg=str(e))


def remove_peer_connection(client, module):
pcx_id = module.params.get('peering_id')
params = dict()
if not pcx_id:
params['VpcId'] = module.params.get('vpc_id')
params['PeerVpcId'] = module.params.get('peer_vpc_id')
if module.params.get('peer_owner_id'):
params['PeerOwnerId'] = str(module.params.get('peer_owner_id'))
params['DryRun'] = module.check_mode
peering_conns = describe_peering_connections(params, client)
if not peering_conns:
module.exit_json(changed=False)
else:
pcx_id = peering_conns['VpcPeeringConnections'][0]['VpcPeeringConnectionId']
try:
params['VpcPeeringConnectionId'] = pcx_id
client.delete_vpc_peering_connection(**params)
module.exit_json(changed=True)
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))


def peer_status(client, module):
params = dict()
params['VpcPeeringConnectionIds'] = [module.params.get('peering_id')]
vpc_peering_connection = client.describe_vpc_peering_connections(**params)
return vpc_peering_connection['VpcPeeringConnections'][0]['Status']['Code']


def accept_reject_delete(state, client, module):
def accept_reject(state, client, module):
changed = False
params = dict()
params['VpcPeeringConnectionId'] = module.params.get('peering_id')
params['DryRun'] = module.check_mode
invocations = {
'accept': client.accept_vpc_peering_connection,
'reject': client.reject_vpc_peering_connection,
'absent': client.delete_vpc_peering_connection
}
if state == 'absent' or peer_status(client, module) != 'active':
if peer_status(client, module) != 'active':
try:
invocations[state](**params)
if state == 'accept':
client.accept_vpc_peering_connection(**params)
else:
client.reject_vpc_peering_connection(**params)
if module.params.get('tags'):
create_tags(params['VpcPeeringConnectionId'], client, module)
changed = True
Expand Down Expand Up @@ -334,38 +360,38 @@ def find_pcx_by_id(pcx_id, client, module):

def main():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
vpc_id=dict(),
peer_vpc_id=dict(),
peering_id=dict(),
peer_owner_id=dict(),
tags=dict(required=False, type='dict'),
profile=dict(),
state=dict(default='present', choices=['present', 'absent', 'accept', 'reject'])
argument_spec.update(
dict(
vpc_id=dict(),
peer_vpc_id=dict(),
peering_id=dict(),
peer_owner_id=dict(),
tags=dict(required=False, type='dict'),
profile=dict(),
state=dict(default='present', choices=['present', 'absent', 'accept', 'reject'])
)
)
module = AnsibleModule(argument_spec=argument_spec)

if not HAS_BOTO3:
module.fail_json(msg='json, botocore and boto3 are required.')
state = module.params.get('state').lower()
state = module.params.get('state')
try:
region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
client = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs)
client = boto3_conn(module, conn_type='client', resource='ec2',
region=region, endpoint=ec2_url, **aws_connect_kwargs)
except botocore.exceptions.NoCredentialsError as e:
module.fail_json(msg="Can't authorize connection - "+str(e))

if state == 'present':
(changed, results) = create_peer_connection(client, module)
module.exit_json(changed=changed, peering_id=results)
elif state == 'absent':
remove_peer_connection(client, module)
else:
(changed, results) = accept_reject_delete(state, client, module)
(changed, results) = accept_reject(state, client, module)
module.exit_json(changed=changed, peering_id=results)


# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *

if __name__ == '__main__':
main()