Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
timeout, args=[event, context])
t.start()
try:
bucket = event['ResourceProperties']['BucketName']
repo_subdir = event['ResourceProperties']['RepoSubdir']
repo_url = event['ResourceProperties']['RepoURL']
repo_name = urlparse(repo_url).path.split('/')[-2]
local_file = download_repo(repo_url)
extract(local_file, '/tmp')
upload_to_s3(bucket, f'/tmp/{repo_name}-master/{repo_subdir}')
cfnresponse.send(event, context, cfnresponse.SUCCESS,
response_data, "CustomResourcePhysicalID")
except Exception as e:
print("Error: " + str(e))
cfnresponse.send(event, context, cfnresponse.FAILED,
response_data, "CustomResourcePhysicalID")
finally:
# Cancel timer before exit
t.cancel()
def handler(event, context):
"""
top-level handler for CloudFormation custom resource protocol
"""
if event['RequestType'] == 'Delete':
try:
stackname = event['ResourceProperties']['StackName']
# This is limited to the config bucket of the stack
# by NavigatorInitRole (the only bucket it references
# is ConfigBucket)
config_bucket_name = event['ResourceProperties']['DestBucket']
except KeyError as e:
print('Could not find {} resource property.'.format(e.args[0]))
print('Doing nothing and reporting success.')
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
return
try:
cf_client = boto3.client('cloudformation')
describe = cf_client.describe_stacks(StackName=stackname)
status = describe['Stacks'][0]['StackStatus']
if not status == 'DELETE_IN_PROGRESS':
print('Stack is not deleting, so this resource is just getting '
'cleaned up. Doing nothing and reporting success.')
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
return
wipe_bucket(config_bucket_name)
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
return
def handler(event, context):
properties = event['ResourceProperties']
rule_name = properties['Name'][:64] # Rule Names can't be longer than 64 characters.
physical_resource_id = 'rule-{}'.format(rule_name)
if event['RequestType'] == 'Delete':
delete_rule(rule_name)
send(event, context, SUCCESS)
return
# We don't check if RequestType is Create or Update, because we don't care
# much... as regardless of what CF thinks.
output = create_or_update_rule(
rule_name=rule_name,
role_arn=properties.get('RoleArn', ''),
schedule_expression=properties.get('ScheduleExpression', ''),
event_pattern=properties.get('EventPattern', ''),
state=properties.get('State', 'ENABLED'),
description=properties.get('Description', '')
)
send(event, context, SUCCESS, physical_resource_id=physical_resource_id, response_data={'Arn': output['RuleArn']})
print(pub_key)
# Encrypt private key
kms = boto3.client('kms',region_name=event["ResourceProperties"]["Region"])
enc_key = kms.encrypt(KeyId=event["ResourceProperties"]["KMSKey"],Plaintext=priv_key)['CiphertextBlob']
f = open('/tmp/enc_key','wb')
f.write(enc_key)
f.close()
# Upload priivate key to S3
s3 = boto3.client('s3')
s3.upload_file('/tmp/enc_key',event["ResourceProperties"]["KeyBucket"],'enc_key')
else:
pub_key = event['PhysicalResourceId']
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, pub_key)
except:
traceback.print_exc()
cfnresponse.send(event, context, cfnresponse.FAILED, {}, '')
if event['RequestType'] == 'Create':
phys_id = ''.join(random.choice(alnum) for _ in range(16))
else:
phys_id = event['PhysicalResourceId']
try:
if event['RequestType'] in ['Create', 'Update']:
if 'Length' in event['ResourceProperties']:
pw_len = int(event['ResourceProperties']['Length'])
else:
pw_len = 16
response_data['EMRClusterName'] = generate_password(pw_len)
cfnresponse.send(event, context, response_code, response_data, phys_id)
except Exception as e:
print(str(e))
traceback.print_exc()
cfnresponse.send(event, context, cfnresponse.FAILED, response_data, phys_id, str(e))
for each_key in replacements_map.keys():
each_value = replacements_map[each_key]
dest_file_content = dest_file_content.replace(each_key, each_value)
s3_client.put_object(
Bucket = resource_props["OutputBucket"],
Key = get_s3_key_for_physical_resource_id(physical_resource_id),
Body = dest_file_content
)
response_data["OutputBucket"] = resource_props["OutputBucket"]
response_data["OutputKey"] = get_s3_key_for_physical_resource_id(physical_resource_id)
cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data, None)
return {}
result = cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, "CustomResourcePhysicalID")
logger.info("Got response to cfnsend {} ".format(result))
elif event['RequestType'] == 'Update':
print("Update something")
elif event['RequestType'] == 'Delete':
print("Got Delete event")
try:
res = delete_route(fromTGWRouteTable, vnetroutecidr)
res1 = delete_route(VPC0_route_table_id, defroutecidr)
result = cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, "CustomResourcePhysicalID")
except Exception as e:
print("Errory trying to delete something")
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, "CustomResourcePhysicalID")
)
ret_value = None
if event["ResourceProperties"].get("Version") is not None:
for param in response["Parameters"]:
if param["Version"] == int(event["ResourceProperties"].get("Version")):
ret_value = param
break
else:
ret_value = response["Parameters"][-1]
if ret_value is None:
raise LookupError("Parameter not found")
logger.info("Successfully retrieved parameter {}".format(name))
cfnresponse.send(event, context, cfnresponse.SUCCESS,
json.loads(json.dumps(ret_value, default=date_2_string)),
name + str(ret_value["Version"]), noEcho=True)
else:
cfnresponse.send(event, context, cfnresponse.SUCCESS, None, name, noEcho=True)
except Exception as ex:
logger.error("Faild get parameter value: %s", name)
logger.debug("Stack trace %s", traceback.format_exc())
if event["RequestType"] in ["Create", "Update"]:
cfnresponse.send(event, context, cfnresponse.FAILED, None, "0", noEcho=True)
else:
cfnresponse.send(event, context, cfnresponse.SUCCESS, None, "0", noEcho=True)
if not pvwa_session_id:
return cfnresponse.send(event, context, cfnresponse.FAILED,
"Failed to connect to PVWA, see detailed error in logs", {}, physical_resource_id)
is_safe_created = create_safe(pvwa_integration_class, request_unix_safe_name, request_unix_cpm_name, request_pvwa_ip,
pvwa_session_id, 1)
if not is_safe_created:
return cfnresponse.send(event, context, cfnresponse.FAILED,
f"Failed to create the Safe {request_unix_safe_name}, see detailed error in logs",
{}, physical_resource_id)
is_safe_created = create_safe(pvwa_integration_class, request_windows_safe_name, request_windows_cpm_name,
request_pvwa_ip, pvwa_session_id, 1)
if not is_safe_created:
return cfnresponse.send(event, context, cfnresponse.FAILED,
f"Failed to create the Safe {request_windows_safe_name}, see detailed error in logs",
{}, physical_resource_id)
if not create_session_table():
return cfnresponse.send(event, context, cfnresponse.FAILED,
"Failed to create 'Sessions' table in DynamoDB, see detailed error in logs",
{}, physical_resource_id)
# Creating KeyPair Safe
is_safe_created = create_safe(pvwa_integration_class, request_key_pair_safe, "", request_pvwa_ip, pvwa_session_id)
if not is_safe_created:
return cfnresponse.send(event, context, cfnresponse.FAILED,
f"Failed to create the Key Pairs safe: {request_key_pair_safe}, " \
"see detailed error in logs",
{}, physical_resource_id)
def handler(event, context):
print(event)
response_data = {}
response_data['Data'] = 'DataResponse'
response_data['Reason'] = 'SomeTestReason'
cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data, "CustomResourcePhysicalID")