Guillaume Coré
2020-03-11 1d970fbaa4bd88c9d094d9587db59fdf9cd0239a
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
---
- environment:
    AWS_PROFILE: "{{ account_profile }}"
    AWS_REGION: "{{ _region }}"
  ignore_errors: yes
  block:
    - debug:
        var: _region
 
    # Security groups
 
    - name: Get all security groups
      register: r_all_sg
      ec2_group_facts:
 
    - when: r_all_sg.security_groups | length > 0
      block:
        - name: Clean up all ingress and egress rules
          loop: "{{ r_all_sg.security_groups }}"
          loop_control:
            loop_var: _sg
          ec2_group:
            rules: []
            rules_egress: []
            name: "{{ _sg.group_name }}"
            description: "{{ _sg.description }}"
            vpc_id: "{{ _sg.vpc_id }}"
 
        - set_fact:
            run_aws_nuke_again: true
 
    # Instance
 
    - name: Get all instances
      ec2_instance_facts:
      register: r_all_instances
 
    - when: r_all_instances.instances | length > 0
      block:
        - name: Disable termination protection on all instances
          command: >-
            aws ec2 --profile "{{ account_profile }}"
            --region "{{ _region }}"
            modify-instance-attribute
            --instance-id {{ _instance.instance_id }}
            --no-disable-api-termination
          when:
            - '"state" in _instance'
            - _instance.state.name != "terminated"
          loop: "{{ r_all_instances.instances }}"
          loop_control:
            loop_var: _instance
 
        - set_fact:
            run_aws_nuke_again: true
    # EIP
 
    - ec2_eip_facts:
      register: r_all_eips
 
    - when: r_all_eips.addresses | length > 0
      block:
        # The following does not seem to work with aws profile
        # Thus use the aws CLI instead.
        # - name: Disassociate and release EIP
        #   ec2_eip:
        #     state: absent
        #     release_on_disassociation: true
        #     public_ip: "{{ _eip.public_ip }}"
        #     profile: "{{ account_profile }}"
        #   loop: "{{ r_all_eips.addresses }}"
        #   loop_control:
        #     loop_var: _eip
 
        - name: Disassociate EIP
          command: >-
            aws ec2 --profile "{{ account_profile }}"
            --region "{{ _region }}"
            disassociate-address
            --public-ip "{{ _eip.public_ip }}"
          loop: "{{ r_all_eips.addresses }}"
          loop_control:
            loop_var: _eip
 
        - set_fact:
            run_aws_nuke_again: true