summaryrefslogtreecommitdiff
path: root/cloud/amazon/ec2_vpc_nat_gateway.py
blob: 1b574840f9646532e730ee54e0b945031b62482a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

DOCUMENTATION = '''
---
module: ec2_vpc_nat_gateway
short_description: Manage AWS VPC NAT Gateways
description:
  - Ensure the state of AWS VPC NAT Gateways based on their id, allocation and subnet ids.
version_added: "2.2"
requirements: [boto3, botocore]
options:
  state:
    description:
      - Ensure NAT Gateway is present or absent
    required: false
    default: "present"
    choices: ["present", "absent"]
  nat_gateway_id:
    description:
      - The id AWS dynamically allocates to the NAT Gateway on creation.
        This is required when the absent option is present.
    required: false
    default: None
  subnet_id:
    description:
      - The id of the subnet to create the NAT Gateway in. This is required
        with the present option.
    required: false
    default: None
  allocation_id:
    description:
      - The id of the elastic IP allocation. If this is not passed and the
        eip_address is not passed. An EIP is generated for this Nat Gateway
    required: false
    default: None
  eip_address:
    description:
      - The elasti ip address of the EIP you want attached to this Nat Gateway.
        If this is not passed and the allocation_id is not passed.
        An EIP is generated for this Nat Gateway
    required: false
  if_exist_do_not_create:
    description:
      - if a Nat Gateway exists already in the subnet_id, then do not create a new one.
    required: false
    default: false
  release_eip:
    description:
      - Deallocate the EIP from the VPC.
      - Option is only valid with the absent state.
    required: false
    default: true
  wait:
    description:
      - Wait for operation to complete before returning
    required: false
    default: false
  wait_timeout:
    description:
      - How many seconds to wait for an operation to complete before timing out
    required: false
    default: 300
  client_token:
    description:
      - Optional unique token to be used during create to ensure idempotency.
        When specifying this option, ensure you specify the eip_address parameter
        as well otherwise any subsequent runs will fail.
    required: false

author:
  - "Allen Sanabria (@linuxdynasty)"
  - "Jon Hadfield (@jonhadfield)"
  - "Karen Cheng(@Etherdaemon)"
extends_documentation_fragment:
  - aws
  - ec2
'''

EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.

- name: Create new nat gateway with client token
  ec2_vpc_nat_gateway:
    state: present
    subnet_id: subnet-12345678
    eip_address: 52.1.1.1
    region: ap-southeast-2
    client_token: abcd-12345678
  register: new_nat_gateway

- name: Create new nat gateway using an allocation-id
  ec2_vpc_nat_gateway:
    state: present
    subnet_id: subnet-12345678
    allocation_id: eipalloc-12345678
    region: ap-southeast-2
  register: new_nat_gateway

- name: Create new nat gateway, using an eip address  and wait for available status
  ec2_vpc_nat_gateway:
    state: present
    subnet_id: subnet-12345678
    eip_address: 52.1.1.1
    wait: yes
    region: ap-southeast-2
  register: new_nat_gateway

- name: Create new nat gateway and allocate new eip
  ec2_vpc_nat_gateway:
    state: present
    subnet_id: subnet-12345678
    wait: yes
    region: ap-southeast-2
  register: new_nat_gateway

- name: Create new nat gateway and allocate new eip if a nat gateway does not yet exist in the subnet.
  ec2_vpc_nat_gateway:
    state: present
    subnet_id: subnet-12345678
    wait: yes
    region: ap-southeast-2
    if_exist_do_not_create: true
  register: new_nat_gateway

- name: Delete nat gateway using discovered nat gateways from facts module
  ec2_vpc_nat_gateway:
    state: absent
    region: ap-southeast-2
    wait: yes
    nat_gateway_id: "{{ item.NatGatewayId }}"
    release_eip: yes
  register: delete_nat_gateway_result
  with_items: "{{ gateways_to_remove.result }}"

- name: Delete nat gateway and wait for deleted status
  ec2_vpc_nat_gateway:
    state: absent
    nat_gateway_id: nat-12345678
    wait: yes
    wait_timeout: 500
    region: ap-southeast-2

- name: Delete nat gateway and release EIP
  ec2_vpc_nat_gateway:
    state: absent
    nat_gateway_id: nat-12345678
    release_eip: yes
    region: ap-southeast-2
'''

RETURN = '''
create_time:
  description: The ISO 8601 date time formatin UTC.
  returned: In all cases.
  type: string
  sample: "2016-03-05T05:19:20.282000+00:00'"
nat_gateway_id:
  description: id of the VPC NAT Gateway
  returned: In all cases.
  type: string
  sample: "nat-0d1e3a878585988f8"
subnet_id:
  description: id of the Subnet
  returned: In all cases.
  type: string
  sample: "subnet-12345"
state:
  description: The current state of the Nat Gateway.
  returned: In all cases.
  type: string
  sample: "available"
vpc_id:
  description: id of the VPC.
  returned: In all cases.
  type: string
  sample: "vpc-12345"
nat_gateway_addresses:
  description: List of dictionairies containing the public_ip, network_interface_id, private_ip, and allocation_id.
  returned: In all cases.
  type: string
  sample: [
      {
          'public_ip': '52.52.52.52',
          'network_interface_id': 'eni-12345',
          'private_ip': '10.0.0.100',
          'allocation_id': 'eipalloc-12345'
      }
  ]
'''

try:
    import botocore
    import boto3
    HAS_BOTO3 = True
except ImportError:
    HAS_BOTO3 = False

import datetime
import random
import time

from dateutil.tz import tzutc

DRY_RUN_GATEWAYS = [
    {
        "nat_gateway_id": "nat-123456789",
        "subnet_id": "subnet-123456789",
        "nat_gateway_addresses": [
            {
                "public_ip": "55.55.55.55",
                "network_interface_id": "eni-1234567",
                "private_ip": "10.0.0.102",
                "allocation_id": "eipalloc-1234567"
            }
        ],
        "state": "available",
        "create_time": "2016-03-05T05:19:20.282000+00:00",
        "vpc_id": "vpc-12345678"
    }
]
DRY_RUN_GATEWAY_UNCONVERTED = [
    {
        'VpcId': 'vpc-12345678',
        'State': 'available',
        'NatGatewayId': 'nat-123456789',
        'SubnetId': 'subnet-123456789',
        'NatGatewayAddresses': [
            {
                'PublicIp': '55.55.55.55',
                'NetworkInterfaceId': 'eni-1234567',
                'AllocationId': 'eipalloc-1234567',
                'PrivateIp': '10.0.0.102'
            }
        ],
        'CreateTime': datetime.datetime(2016, 3, 5, 5, 19, 20, 282000, tzinfo=tzutc())
    }
]

DRY_RUN_ALLOCATION_UNCONVERTED = {
    'Addresses': [
        {
            'PublicIp': '55.55.55.55',
            'Domain': 'vpc',
            'AllocationId': 'eipalloc-1234567'
        }
    ]
}

DRY_RUN_MSGS = 'DryRun Mode:'

def convert_to_lower(data):
    """Convert all uppercase keys in dict with lowercase_

    Args:
        data (dict): Dictionary with keys that have upper cases in them
            Example.. FooBar == foo_bar
            if a val is of type datetime.datetime, it will be converted to
            the ISO 8601

    Basic Usage:
        >>> test = {'FooBar': []}
        >>> test = convert_to_lower(test)
        {
            'foo_bar': []
        }

    Returns:
        Dictionary
    """
    results = dict()
    if isinstance(data, dict):
        for key, val in data.items():
            key = re.sub(r'(([A-Z]{1,3}){1})', r'_\1', key).lower()
            if key[0] == '_':
                key = key[1:]
            if isinstance(val, datetime.datetime):
                results[key] = val.isoformat()
            elif isinstance(val, dict):
                results[key] = convert_to_lower(val)
            elif isinstance(val, list):
                converted = list()
                for item in val:
                    converted.append(convert_to_lower(item))
                results[key] = converted
            else:
                results[key] = val
    return results

def get_nat_gateways(client, subnet_id=None, nat_gateway_id=None,
                     states=None, check_mode=False):
    """Retrieve a list of NAT Gateways
    Args:
        client (botocore.client.EC2): Boto3 client

    Kwargs:
        subnet_id (str): The subnet_id the nat resides in.
        nat_gateway_id (str): The Amazon nat id.
        states (list): States available (pending, failed, available, deleting, and deleted)
            default=None

    Basic Usage:
        >>> client = boto3.client('ec2')
        >>> subnet_id = 'subnet-12345678'
        >>> get_nat_gateways(client, subnet_id)
        [
            true,
            "",
            {
                "nat_gateway_id": "nat-123456789",
                "subnet_id": "subnet-123456789",
                "nat_gateway_addresses": [
                    {
                        "public_ip": "55.55.55.55",
                        "network_interface_id": "eni-1234567",
                        "private_ip": "10.0.0.102",
                        "allocation_id": "eipalloc-1234567"
                    }
                ],
                "state": "deleted",
                "create_time": "2016-03-05T00:33:21.209000+00:00",
                "delete_time": "2016-03-05T00:36:37.329000+00:00",
                "vpc_id": "vpc-12345678"
            }

    Returns:
        Tuple (bool, str, list)
    """
    params = dict()
    err_msg = ""
    gateways_retrieved = False
    existing_gateways = list()
    if not states:
        states = ['available', 'pending']
    if nat_gateway_id:
        params['NatGatewayIds'] = [nat_gateway_id]
    else:
        params['Filter'] = [
            {
                'Name': 'subnet-id',
                'Values': [subnet_id]
            },
            {
                'Name': 'state',
                'Values': states
            }
        ]

    try:
        if not check_mode:
            gateways = client.describe_nat_gateways(**params)['NatGateways']
            if gateways:
                for gw in gateways:
                    existing_gateways.append(convert_to_lower(gw))
            gateways_retrieved = True
        else:
            gateways_retrieved = True
            if nat_gateway_id:
                if DRY_RUN_GATEWAYS[0]['nat_gateway_id'] == nat_gateway_id:
                    existing_gateways = DRY_RUN_GATEWAYS
            elif subnet_id:
                if DRY_RUN_GATEWAYS[0]['subnet_id'] == subnet_id:
                    existing_gateways = DRY_RUN_GATEWAYS
            err_msg = '{0} Retrieving gateways'.format(DRY_RUN_MSGS)

    except botocore.exceptions.ClientError, e:
            err_msg = str(e)

    return gateways_retrieved, err_msg, existing_gateways

def wait_for_status(client, wait_timeout, nat_gateway_id, status,
                    check_mode=False):
    """Wait for the Nat Gateway to reach a status
    Args:
        client (botocore.client.EC2): Boto3 client
        wait_timeout (int): Number of seconds to wait, until this timeout is reached.
        nat_gateway_id (str): The Amazon nat id.
        status (str): The status to wait for.
            examples. status=available, status=deleted

    Basic Usage:
        >>> client = boto3.client('ec2')
        >>> subnet_id = 'subnet-12345678'
        >>> allocation_id = 'eipalloc-12345678'
        >>> wait_for_status(client, subnet_id, allocation_id)
        [
            true,
            "",
            {
                "nat_gateway_id": "nat-123456789",
                "subnet_id": "subnet-1234567",
                "nat_gateway_addresses": [
                    {
                        "public_ip": "55.55.55.55",
                        "network_interface_id": "eni-1234567",
                        "private_ip": "10.0.0.102",
                        "allocation_id": "eipalloc-12345678"
                    }
                ],
                "state": "deleted",
                "create_time": "2016-03-05T00:33:21.209000+00:00",
                "delete_time": "2016-03-05T00:36:37.329000+00:00",
                "vpc_id": "vpc-12345677"
            }
        ]

    Returns:
        Tuple (bool, str, list)
    """
    polling_increment_secs = 5
    wait_timeout = time.time() + wait_timeout
    status_achieved = False
    nat_gateway = list()
    states = ['pending', 'failed', 'available', 'deleting', 'deleted']
    err_msg = ""

    while wait_timeout > time.time():
        try:
            gws_retrieved, err_msg, nat_gateway = (
                get_nat_gateways(
                    client, nat_gateway_id=nat_gateway_id,
                    states=states, check_mode=check_mode
                )
            )
            if gws_retrieved and nat_gateway:
                nat_gateway = nat_gateway[0]
                if check_mode:
                    nat_gateway['state'] = status

                if nat_gateway.get('state') == status:
                    status_achieved = True
                    break

                elif nat_gateway.get('state') == 'failed':
                    err_msg = nat_gateway.get('failure_message')
                    break

                elif nat_gateway.get('state') == 'pending':
                    if nat_gateway.has_key('failure_message'):
                        err_msg = nat_gateway.get('failure_message')
                        status_achieved = False
                        break

            else:
                time.sleep(polling_increment_secs)

        except botocore.exceptions.ClientError, e:
            err_msg = str(e)

    if not status_achieved:
        err_msg = "Wait time out reached, while waiting for results"

    return status_achieved, err_msg, nat_gateway

def gateway_in_subnet_exists(client, subnet_id, allocation_id=None,
                             check_mode=False):
    """Retrieve all NAT Gateways for a subnet.
    Args:
        subnet_id (str): The subnet_id the nat resides in.

    Kwargs:
        allocation_id (str): The eip Amazon identifier.
            default = None

    Basic Usage:
        >>> client = boto3.client('ec2')
        >>> subnet_id = 'subnet-1234567'
        >>> allocation_id = 'eipalloc-1234567'
        >>> gateway_in_subnet_exists(client, subnet_id, allocation_id)
        (
            [
                {
                    "nat_gateway_id": "nat-123456789",
                    "subnet_id": "subnet-123456789",
                    "nat_gateway_addresses": [
                        {
                            "public_ip": "55.55.55.55",
                            "network_interface_id": "eni-1234567",
                            "private_ip": "10.0.0.102",
                            "allocation_id": "eipalloc-1234567"
                        }
                    ],
                    "state": "deleted",
                    "create_time": "2016-03-05T00:33:21.209000+00:00",
                    "delete_time": "2016-03-05T00:36:37.329000+00:00",
                    "vpc_id": "vpc-1234567"
                }
            ],
            False
        )

    Returns:
        Tuple (list, bool)
    """
    allocation_id_exists = False
    gateways = []
    states = ['available', 'pending']
    gws_retrieved, _, gws = (
        get_nat_gateways(
            client, subnet_id, states=states, check_mode=check_mode
        )
    )
    if not gws_retrieved:
        return gateways, allocation_id_exists
    for gw in gws:
        for address in gw['nat_gateway_addresses']:
            if allocation_id:
                if address.get('allocation_id') == allocation_id:
                    allocation_id_exists = True
                    gateways.append(gw)
            else:
                gateways.append(gw)

    return gateways, allocation_id_exists

def get_eip_allocation_id_by_address(client, eip_address, check_mode=False):
    """Release an EIP from your EIP Pool
    Args:
        client (botocore.client.EC2): Boto3 client
        eip_address (str): The Elastic IP Address of the EIP.

    Kwargs:
        check_mode (bool): if set to true, do not run anything and
            falsify the results.

    Basic Usage:
        >>> client = boto3.client('ec2')
        >>> eip_address = '52.87.29.36'
        >>> get_eip_allocation_id_by_address(client, eip_address)
        'eipalloc-36014da3'

    Returns:
        Tuple (str, str)
    """
    params = {
        'PublicIps': [eip_address],
    }
    allocation_id = None
    err_msg = ""
    try:
        if not check_mode:
            allocations = client.describe_addresses(**params)['Addresses']
            if len(allocations) == 1:
                allocation = allocations[0]
            else:
                allocation = None
        else:
            dry_run_eip = (
                DRY_RUN_ALLOCATION_UNCONVERTED['Addresses'][0]['PublicIp']
            )
            if dry_run_eip == eip_address:
                allocation = DRY_RUN_ALLOCATION_UNCONVERTED['Addresses'][0]
            else:
                allocation = None
        if allocation:
            if allocation.get('Domain') != 'vpc':
                err_msg = (
                    "EIP {0} is a non-VPC EIP, please allocate a VPC scoped EIP"
                    .format(eip_address)
                )
            else:
                allocation_id = allocation.get('AllocationId')
        else:
            err_msg = (
                "EIP {0} does not exist".format(eip_address)
            )

    except botocore.exceptions.ClientError, e:
            err_msg = str(e)

    return allocation_id, err_msg

def allocate_eip_address(client, check_mode=False):
    """Release an EIP from your EIP Pool
    Args:
        client (botocore.client.EC2): Boto3 client

    Kwargs:
        check_mode (bool): if set to true, do not run anything and
            falsify the results.

    Basic Usage:
        >>> client = boto3.client('ec2')
        >>> allocate_eip_address(client)
        True

    Returns:
        Tuple (bool, str)
    """
    ip_allocated = False
    new_eip = None
    err_msg = ''
    params = {
        'Domain': 'vpc',
    }
    try:
        if check_mode:
            ip_allocated = True
            random_numbers = (
                ''.join(str(x) for x in random.sample(range(0, 9), 7))
            )
            new_eip = 'eipalloc-{0}'.format(random_numbers)
        else:
            new_eip = client.allocate_address(**params)['AllocationId']
            ip_allocated = True
        err_msg = 'eipalloc id {0} created'.format(new_eip)

    except botocore.exceptions.ClientError, e:
        err_msg = str(e)

    return ip_allocated, err_msg, new_eip

def release_address(client, allocation_id, check_mode=False):
    """Release an EIP from your EIP Pool
    Args:
        client (botocore.client.EC2): Boto3 client
        allocation_id (str): The eip Amazon identifier.

    Kwargs:
        check_mode (bool): if set to true, do not run anything and
            falsify the results.

    Basic Usage:
        >>> client = boto3.client('ec2')
        >>> allocation_id = "eipalloc-123456"
        >>> release_address(client, allocation_id)
        True

    Returns:
        Boolean
    """
    if check_mode:
        return True

    ip_released = False
    params = {
        'AllocationId': allocation_id,
    }
    try:
        client.release_address(**params)
        ip_released = True
    except botocore.exceptions.ClientError:
        pass

    return ip_released

def create(client, subnet_id, allocation_id, client_token=None,
           wait=False, wait_timeout=0, if_exist_do_not_create=False,
           check_mode=False):
    """Create an Amazon NAT Gateway.
    Args:
        client (botocore.client.EC2): Boto3 client
        subnet_id (str): The subnet_id the nat resides in.
        allocation_id (str): The eip Amazon identifier.

    Kwargs:
        if_exist_do_not_create (bool): if a nat gateway already exists in this
            subnet, than do not create another one.
            default = False
        wait (bool): Wait for the nat to be in the deleted state before returning.
            default = False
        wait_timeout (int): Number of seconds to wait, until this timeout is reached.
            default = 0
        client_token (str):
            default = None

    Basic Usage:
        >>> client = boto3.client('ec2')
        >>> subnet_id = 'subnet-1234567'
        >>> allocation_id = 'eipalloc-1234567'
        >>> create(client, subnet_id, allocation_id, if_exist_do_not_create=True, wait=True, wait_timeout=500)
        [
            true,
            "",
            {
                "nat_gateway_id": "nat-123456789",
                "subnet_id": "subnet-1234567",
                "nat_gateway_addresses": [
                    {
                        "public_ip": "55.55.55.55",
                        "network_interface_id": "eni-1234567",
                        "private_ip": "10.0.0.102",
                        "allocation_id": "eipalloc-1234567"
                    }
                ],
                "state": "deleted",
                "create_time": "2016-03-05T00:33:21.209000+00:00",
                "delete_time": "2016-03-05T00:36:37.329000+00:00",
                "vpc_id": "vpc-1234567"
            }
        ]

    Returns:
        Tuple (bool, str, list)
    """
    params = {
        'SubnetId': subnet_id,
        'AllocationId': allocation_id
    }
    request_time = datetime.datetime.utcnow()
    changed = False
    success = False
    token_provided = False
    err_msg = ""

    if client_token:
        token_provided = True
        params['ClientToken'] = client_token

    try:
        if not check_mode:
            result = client.create_nat_gateway(**params)["NatGateway"]
        else:
            result = DRY_RUN_GATEWAY_UNCONVERTED[0]
            result['CreateTime'] = datetime.datetime.utcnow()
            result['NatGatewayAddresses'][0]['AllocationId'] = allocation_id
            result['SubnetId'] = subnet_id

        success = True
        changed = True
        create_time = result['CreateTime'].replace(tzinfo=None)
        if token_provided and (request_time > create_time):
            changed = False
        elif wait:
            success, err_msg, result = (
                wait_for_status(
                    client, wait_timeout, result['NatGatewayId'], 'available',
                    check_mode=check_mode
                )
            )
            if success:
                err_msg = (
                    'Nat gateway {0} created'.format(result['nat_gateway_id'])
                )
            if check_mode:
                result['nat_gateway_addresses'][0]['allocation_id'] = allocation_id
                result['subnet_id'] = subnet_id

    except botocore.exceptions.ClientError as e:
        if "IdempotentParameterMismatch" in e.message:
            err_msg = (
                'NAT Gateway does not support update and token has already been provided'
            )
        else:
            err_msg = str(e)
            success = False
            changed = False
            result = None

    return success, changed, err_msg, result

def pre_create(client, subnet_id, allocation_id=None, eip_address=None,
              if_exist_do_not_create=False, wait=False, wait_timeout=0,
              client_token=None, check_mode=False):
    """Create an Amazon NAT Gateway.
    Args:
        client (botocore.client.EC2): Boto3 client
        subnet_id (str): The subnet_id the nat resides in.

    Kwargs:
        allocation_id (str): The eip Amazon identifier.
            default = None
        eip_address (str): The Elastic IP Address of the EIP.
            default = None
        if_exist_do_not_create (bool): if a nat gateway already exists in this
            subnet, than do not create another one.
            default = False
        wait (bool): Wait for the nat to be in the deleted state before returning.
            default = False
        wait_timeout (int): Number of seconds to wait, until this timeout is reached.
            default = 0
        client_token (str):
            default = None

    Basic Usage:
        >>> client = boto3.client('ec2')
        >>> subnet_id = 'subnet-w4t12897'
        >>> allocation_id = 'eipalloc-36014da3'
        >>> pre_create(client, subnet_id, allocation_id, if_exist_do_not_create=True, wait=True, wait_timeout=500)
        [
            true,
            "",
            {
                "nat_gateway_id": "nat-03835afb6e31df79b",
                "subnet_id": "subnet-w4t12897",
                "nat_gateway_addresses": [
                    {
                        "public_ip": "52.87.29.36",
                        "network_interface_id": "eni-5579742d",
                        "private_ip": "10.0.0.102",
                        "allocation_id": "eipalloc-36014da3"
                    }
                ],
                "state": "deleted",
                "create_time": "2016-03-05T00:33:21.209000+00:00",
                "delete_time": "2016-03-05T00:36:37.329000+00:00",
                "vpc_id": "vpc-w68571b5"
            }
        ]

    Returns:
        Tuple (bool, bool, str, list)
    """
    success = False
    changed = False
    err_msg = ""
    results = list()

    if not allocation_id and not eip_address:
        existing_gateways, allocation_id_exists = (
            gateway_in_subnet_exists(client, subnet_id, check_mode=check_mode)
        )

        if len(existing_gateways) > 0 and if_exist_do_not_create:
            success = True
            changed = False
            results = existing_gateways[0]
            err_msg = (
                'Nat Gateway {0} already exists in subnet_id {1}'
                .format(
                    existing_gateways[0]['nat_gateway_id'], subnet_id
                )
            )
            return success, changed, err_msg, results
        else:
            success, err_msg, allocation_id = (
                allocate_eip_address(client, check_mode=check_mode)
            )
            if not success:
                return success, 'False', err_msg, dict()

    elif eip_address or allocation_id:
        if eip_address and not allocation_id:
            allocation_id, err_msg = (
                get_eip_allocation_id_by_address(
                    client, eip_address, check_mode=check_mode
                )
            )
            if not allocation_id:
                success = False
                changed = False
                return success, changed, err_msg, dict()

        existing_gateways, allocation_id_exists = (
            gateway_in_subnet_exists(
                client, subnet_id, allocation_id, check_mode=check_mode
            )
        )
        if len(existing_gateways) > 0 and (allocation_id_exists or if_exist_do_not_create):
            success = True
            changed = False
            results = existing_gateways[0]
            err_msg = (
                'Nat Gateway {0} already exists in subnet_id {1}'
                .format(
                    existing_gateways[0]['nat_gateway_id'], subnet_id
                )
            )
            return success, changed, err_msg, results

    success, changed, err_msg, results = create(
        client, subnet_id, allocation_id, client_token,
        wait, wait_timeout, if_exist_do_not_create, check_mode=check_mode
    )

    return success, changed, err_msg, results

def remove(client, nat_gateway_id, wait=False, wait_timeout=0,
           release_eip=False, check_mode=False):
    """Delete an Amazon NAT Gateway.
    Args:
        client (botocore.client.EC2): Boto3 client
        nat_gateway_id (str): The Amazon nat id.

    Kwargs:
        wait (bool): Wait for the nat to be in the deleted state before returning.
        wait_timeout (int): Number of seconds to wait, until this timeout is reached.
        release_eip (bool): Once the nat has been deleted, you can deallocate the eip from the vpc.

    Basic Usage:
        >>> client = boto3.client('ec2')
        >>> nat_gw_id = 'nat-03835afb6e31df79b'
        >>> remove(client, nat_gw_id, wait=True, wait_timeout=500, release_eip=True)
        [
            true,
            "",
            {
                "nat_gateway_id": "nat-03835afb6e31df79b",
                "subnet_id": "subnet-w4t12897",
                "nat_gateway_addresses": [
                    {
                        "public_ip": "52.87.29.36",
                        "network_interface_id": "eni-5579742d",
                        "private_ip": "10.0.0.102",
                        "allocation_id": "eipalloc-36014da3"
                    }
                ],
                "state": "deleted",
                "create_time": "2016-03-05T00:33:21.209000+00:00",
                "delete_time": "2016-03-05T00:36:37.329000+00:00",
                "vpc_id": "vpc-w68571b5"
            }
        ]

    Returns:
        Tuple (bool, str, list)
    """
    params = {
        'NatGatewayId': nat_gateway_id
    }
    success = False
    changed = False
    err_msg = ""
    results = list()
    states = ['pending', 'available' ]
    try:
        exist, _, gw = (
            get_nat_gateways(
                client, nat_gateway_id=nat_gateway_id,
                states=states, check_mode=check_mode
            )
        )
        if exist and len(gw) == 1:
            results = gw[0]
            if not check_mode:
                client.delete_nat_gateway(**params)

            allocation_id = (
                results['nat_gateway_addresses'][0]['allocation_id']
            )
            changed = True
            success = True
            err_msg = (
                'Nat gateway {0} is in a deleting state. Delete was successfull'
                .format(nat_gateway_id)
            )

            if wait:
                status_achieved, err_msg, results = (
                    wait_for_status(
                        client, wait_timeout, nat_gateway_id, 'deleted',
                        check_mode=check_mode
                    )
                )
                if status_achieved:
                    err_msg = (
                        'Nat gateway {0} was deleted successfully'
                        .format(nat_gateway_id)
                    )

    except botocore.exceptions.ClientError as e:
        err_msg = str(e)

    if release_eip:
        eip_released = (
            release_address(client, allocation_id, check_mode=check_mode)
        )
        if not eip_released:
            err_msg = "Failed to release eip %s".format(allocation_id)

    return success, changed, err_msg, results

def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(
        subnet_id=dict(type='str'),
        eip_address=dict(type='str'),
        allocation_id=dict(type='str'),
        if_exist_do_not_create=dict(type='bool', default=False),
        state=dict(default='present', choices=['present', 'absent']),
        wait=dict(type='bool', default=False),
        wait_timeout=dict(type='int', default=320, required=False),
        release_eip=dict(type='bool', default=False),
        nat_gateway_id=dict(type='str'),
        client_token=dict(type='str'),
        )
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        mutually_exclusive=[
            ['allocation_id', 'eip_address']
        ]
    )

    # Validate Requirements
    if not HAS_BOTO3:
        module.fail_json(msg='botocore/boto3 is required.')

    state = module.params.get('state').lower()
    check_mode = module.check_mode
    subnet_id = module.params.get('subnet_id')
    allocation_id = module.params.get('allocation_id')
    eip_address = module.params.get('eip_address')
    nat_gateway_id = module.params.get('nat_gateway_id')
    wait = module.params.get('wait')
    wait_timeout = module.params.get('wait_timeout')
    release_eip = module.params.get('release_eip')
    client_token = module.params.get('client_token')
    if_exist_do_not_create = module.params.get('if_exist_do_not_create')

    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
            )
        )
    except botocore.exceptions.ClientError, e:
        module.fail_json(msg="Boto3 Client Error - " + str(e.msg))

    changed = False
    err_msg = ''

    #Ensure resource is present
    if state == 'present':
        if not subnet_id:
            module.fail_json(msg='subnet_id is required for creation')

        success, changed, err_msg, results = (
            pre_create(
                client, subnet_id, allocation_id, eip_address,
                if_exist_do_not_create, wait, wait_timeout,
                client_token, check_mode=check_mode
            )
        )
    else:
        if not nat_gateway_id:
            module.fail_json(msg='nat_gateway_id is required for removal')

        else:
            success, changed, err_msg, results = (
                remove(
                    client, nat_gateway_id, wait, wait_timeout, release_eip,
                    check_mode=check_mode
                )
            )

    if not success:
        module.exit_json(
            msg=err_msg, success=success, changed=changed
        )
    else:
        module.exit_json(
            msg=err_msg, success=success, changed=changed, **results
        )

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

if __name__ == '__main__':
    main()