|
| 1 | +import boto3 |
| 2 | +import json |
| 3 | +import os |
| 4 | +import sys |
| 5 | + |
| 6 | +sys.path.append(f"{os.environ['LAMBDA_TASK_ROOT']}/lib") |
| 7 | +sys.path.append(os.path.dirname(os.path.realpath(__file__))) |
| 8 | + |
| 9 | +import cr_response |
| 10 | +import stack_manage |
| 11 | +import lambda_invoker |
| 12 | +import traceback |
| 13 | + |
| 14 | +create_stack_success_states = ['CREATE_COMPLETE'] |
| 15 | +update_stack_success_states = ['CREATE_COMPLETE', 'UPDATE_COMPLETE'] |
| 16 | +delete_stack_success_states = ['DELETE_COMPLETE'] |
| 17 | + |
| 18 | +create_stack_failure_states = ['CREATE_FAILED', |
| 19 | + 'DELETE_FAILED', |
| 20 | + 'UPDATE_FAILED', |
| 21 | + 'ROLLBACK_FAILED', |
| 22 | + 'DELETE_COMPLETE', |
| 23 | + 'ROLLBACK_COMPLETE'] |
| 24 | +update_stack_failure_states = ['CREATE_FAILED', 'DELETE_FAILED', 'UPDATE_FAILED', 'ROLLBACK_COMPLETE','UPDATE_ROLLBACK_COMPLETE'] |
| 25 | +delete_stack_failure_states = ['DELETE_FAILED'] |
| 26 | + |
| 27 | + |
| 28 | +def respond_disabled_region(region, payload): |
| 29 | + cfn_response = cr_response.CustomResourceResponse(payload) |
| 30 | + payload['PhysicalResourceId'] = f"Disabled{region.replace('-','')}{payload['ResourceProperties']['StackName']}" |
| 31 | + cfn_response.response['Status'] = 'SUCCESS' |
| 32 | + cfn_response.respond() |
| 33 | + return |
| 34 | + |
| 35 | + |
| 36 | +def create_update_stack(cmd, payload): |
| 37 | + if 'Capabilities' not in payload['ResourceProperties']: |
| 38 | + payload['ResourceProperties']['Capabilities'] = 'CAPABILITY_IAM' |
| 39 | + |
| 40 | + # compile stack parameters |
| 41 | + stack_params = {} |
| 42 | + for key, value in payload['ResourceProperties'].items(): |
| 43 | + if key.startswith('StackParam_'): |
| 44 | + param_key = key.replace('StackParam_', '') |
| 45 | + param_value = value |
| 46 | + stack_params[param_key] = param_value |
| 47 | + |
| 48 | + # instantiate and use management handler |
| 49 | + manage = stack_manage.StackManagement() |
| 50 | + |
| 51 | + on_failure = 'DELETE' |
| 52 | + if 'OnFailure' in payload['ResourceProperties']: |
| 53 | + on_failure = payload['ResourceProperties']['OnFailure'] |
| 54 | + |
| 55 | + stack_id = '' |
| 56 | + if cmd == 'create': |
| 57 | + stack_id = manage.create( |
| 58 | + payload['ResourceProperties']['Region'], |
| 59 | + payload['ResourceProperties']['StackName'], |
| 60 | + payload['ResourceProperties']['TemplateUrl'], |
| 61 | + stack_params, |
| 62 | + payload['ResourceProperties']['Capabilities'].split(','), |
| 63 | + on_failure |
| 64 | + ) |
| 65 | + elif cmd == 'update': |
| 66 | + stack_id = payload['PhysicalResourceId'] |
| 67 | + result = manage.update( |
| 68 | + payload['ResourceProperties']['Region'], |
| 69 | + stack_id, |
| 70 | + payload['ResourceProperties']['TemplateUrl'], |
| 71 | + stack_params, |
| 72 | + payload['ResourceProperties']['Capabilities'].split(','), |
| 73 | + ) |
| 74 | + # no updates to be performed |
| 75 | + if result is None: |
| 76 | + cfn_response = cr_response.CustomResourceResponse(payload) |
| 77 | + cfn_response.respond() |
| 78 | + return None |
| 79 | + else: |
| 80 | + raise 'Cmd must be create or update' |
| 81 | + |
| 82 | + return stack_id |
| 83 | + |
| 84 | + |
| 85 | +def delete_stack(payload): |
| 86 | + manage = stack_manage.StackManagement() |
| 87 | + region = payload['ResourceProperties']['Region'] |
| 88 | + stack_id = payload['PhysicalResourceId'] |
| 89 | + manage.delete(region, payload['ResourceProperties']['StackName']) |
| 90 | + return stack_id |
| 91 | + |
| 92 | + |
| 93 | +def wait_stack_states(success_states, failure_states, lambda_payload, lambda_context): |
| 94 | + """ |
| 95 | + Wait for stack states, either be it success or failure. If none of the states |
| 96 | + appear and lambda is running out of time, it will be re-invoked with lambda_payload |
| 97 | + parameters |
| 98 | + :param lambda_context: |
| 99 | + :param stack_id: |
| 100 | + :param success_states: |
| 101 | + :param failure_states: |
| 102 | + :param lambda_payload: |
| 103 | + :return: |
| 104 | + """ |
| 105 | + manage = stack_manage.StackManagement() |
| 106 | + result = manage.wait_stack_status( |
| 107 | + lambda_payload['ResourceProperties']['Region'], |
| 108 | + lambda_payload['PhysicalResourceId'], |
| 109 | + success_states, |
| 110 | + failure_states, |
| 111 | + lambda_context |
| 112 | + ) |
| 113 | + |
| 114 | + # in this case we need to restart lambda execution |
| 115 | + if result is None: |
| 116 | + invoke = lambda_invoker.LambdaInvoker() |
| 117 | + invoke.invoke(lambda_payload) |
| 118 | + else: |
| 119 | + # one of the states is reached, and reply should be sent back to cloud formation |
| 120 | + cfn_response = cr_response.CustomResourceResponse(lambda_payload) |
| 121 | + cfn_response.response['PhysicalResourceId'] = lambda_payload['PhysicalResourceId'] |
| 122 | + cfn_response.response['Status'] = result.status |
| 123 | + cfn_response.response['Reason'] = result.reason |
| 124 | + cfn_response.response['StackId'] = lambda_payload['StackId'] |
| 125 | + cfn_response.respond() |
| 126 | + |
| 127 | + |
| 128 | +def lambda_handler(payload, context): |
| 129 | + # if lambda invoked to wait for stack status |
| 130 | + print(f"Received event:{json.dumps(payload)}") |
| 131 | + |
| 132 | + # handle disable region situation |
| 133 | + if 'EnabledRegions' in payload['ResourceProperties']: |
| 134 | + region_list = payload['ResourceProperties']['EnabledRegions'].split(',') |
| 135 | + current_region = payload['ResourceProperties']['Region'] |
| 136 | + print(f"EnabledRegions: {region_list}. Current region={current_region}") |
| 137 | + |
| 138 | + if current_region not in region_list: |
| 139 | + # if this is create request just skip |
| 140 | + if payload['RequestType'] == 'Create' or payload['RequestType'] == 'Update': |
| 141 | + print(f"{current_region} not enabled, skipping") |
| 142 | + # report disabled |
| 143 | + # in case of region disable (update), physical record changes, so cleanup delete request is |
| 144 | + # sent subsequently via Cf, which will delete the stack |
| 145 | + respond_disabled_region(current_region, payload) |
| 146 | + return |
| 147 | + |
| 148 | + |
| 149 | + |
| 150 | + # lambda was invoked by itself, we just have to wait for stack operation to be completed |
| 151 | + if ('WaitComplete' in payload) and (payload['WaitComplete']): |
| 152 | + print("Waiting for stack status...") |
| 153 | + if payload['RequestType'] == 'Create': |
| 154 | + wait_stack_states( |
| 155 | + create_stack_success_states, |
| 156 | + create_stack_failure_states, |
| 157 | + payload, |
| 158 | + context |
| 159 | + ) |
| 160 | + |
| 161 | + elif payload['RequestType'] == 'Update': |
| 162 | + wait_stack_states( |
| 163 | + update_stack_success_states, |
| 164 | + update_stack_failure_states, |
| 165 | + payload, |
| 166 | + context |
| 167 | + ) |
| 168 | + |
| 169 | + elif payload['RequestType'] == 'Delete': |
| 170 | + wait_stack_states( |
| 171 | + delete_stack_success_states, |
| 172 | + delete_stack_failure_states, |
| 173 | + payload, |
| 174 | + context |
| 175 | + ) |
| 176 | + |
| 177 | + # lambda was invoked directly by cf |
| 178 | + else: |
| 179 | + # depending on request type different handler is called |
| 180 | + print("Executing stack CRUD...") |
| 181 | + stack_id = None |
| 182 | + if 'PhysicalResourceId' in payload: |
| 183 | + stack_id = payload['PhysicalResourceId'] |
| 184 | + try: |
| 185 | + manage = stack_manage.StackManagement() |
| 186 | + stack_name = payload['ResourceProperties']['StackName'] |
| 187 | + region = payload['ResourceProperties']['Region'] |
| 188 | + stack_exists = manage.stack_exists(region, stack_name) |
| 189 | + |
| 190 | + if payload['RequestType'] == 'Create': |
| 191 | + # stack exists, create request => update |
| 192 | + # stack not exists, create request => create |
| 193 | + if stack_exists: |
| 194 | + print(f"Create request came for {stack_name}, but it already exists in {region}, updating...") |
| 195 | + payload['RequestType'] = 'Update' |
| 196 | + lambda_handler(payload, context) |
| 197 | + return |
| 198 | + else: |
| 199 | + stack_id = create_update_stack('create', payload) |
| 200 | + |
| 201 | + elif payload['RequestType'] == 'Update': |
| 202 | + # stack exists, update request => update |
| 203 | + # stack not exists, update request => create |
| 204 | + if stack_exists: |
| 205 | + stack_id = create_update_stack('update', payload) |
| 206 | + if stack_id is None: |
| 207 | + # no updates to be performed |
| 208 | + return |
| 209 | + else: |
| 210 | + print(f"Update request came for {stack_name}, but it does not exist in {region}, creating...") |
| 211 | + payload['RequestType'] = 'Create' |
| 212 | + lambda_handler(payload, context) |
| 213 | + return |
| 214 | + |
| 215 | + elif payload['RequestType'] == 'Delete': |
| 216 | + # stack exists, delete request => delete |
| 217 | + # stack not exists, delete request => report ok |
| 218 | + # for delete we are interested in actual stack id |
| 219 | + stack_exists = manage.stack_exists(region, stack_id) |
| 220 | + if stack_exists: |
| 221 | + delete_stack(payload) |
| 222 | + else: |
| 223 | + # reply with success |
| 224 | + print(f"Delete request came for {stack_name}, but it is nowhere to be found...") |
| 225 | + cfn_response = cr_response.CustomResourceResponse(payload) |
| 226 | + cfn_response.response['Reason'] = 'CloudFormation stack has not been found, may be removed manually' |
| 227 | + cfn_response.respond() |
| 228 | + return |
| 229 | + |
| 230 | + # if haven't moved to other operation, set payloads stack id to created/updated stack and wait |
| 231 | + # for appropriate stack status |
| 232 | + payload['PhysicalResourceId'] = stack_id |
| 233 | + payload['WaitComplete'] = True |
| 234 | + invoker = lambda_invoker.LambdaInvoker() |
| 235 | + invoker.invoke(payload) |
| 236 | + |
| 237 | + except Exception as e: |
| 238 | + print(f"Exception:{e}\n{str(e)}") |
| 239 | + print(traceback.format_exc()) |
| 240 | + cfn_response = cr_response.CustomResourceResponse(payload) |
| 241 | + if 'PhysicalResourceId' in payload: |
| 242 | + cfn_response.response['PhysicalResourceId'] = payload['PhysicalResourceId'] |
| 243 | + cfn_response.response['Status'] = 'FAILED' |
| 244 | + cfn_response.response['Reason'] = str(e) |
| 245 | + cfn_response.respond() |
| 246 | + raise e |
0 commit comments