Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
cfnresponse.send(
event,
context,
cfnresponse.SUCCESS,
responseData=responseData,
physicalResourceId=event['PhysicalResourceId'],
noEcho=no_echo
)
return True
event['ResourceProperties'].pop('AgentResourceId', None)
except Exception as e:
if self.verbose: print_exc()
cfnresponse.send(
event,
context,
cfnresponse.FAILED,
noEcho=no_echo,
reason=str(e)
)
return False
''' Create: (re)creates a resource and returns PhysicalResourceId based on
the specified AgentResourceId.'''
try:
(PhysicalResourceId, responseData) = self.handle_client_event(
agent,
event,
create=True
)
cfnresponse.send(
event,
"Failed to create the Key Pairs safe: {0}, see detailed error in logs".format(requestKeyPairSafe),
{}, physicalResourceId)
# key pair is optional parameter
if not requestKeyPairName:
print("Key Pair name parameter is empty, the solution will not create a new Key Pair")
return cfnresponse.send(event, context, cfnresponse.SUCCESS, None, {}, physicalResourceId)
else:
awsKeypair = create_new_key_pair_on_AWS(requestKeyPairName)
if awsKeypair is False:
# Account already exist, no need to create it, can't insert it to the vault
return cfnresponse.send(event, context, cfnresponse.FAILED, "Failed to create Key Pair '{0}' in AWS".format(requestKeyPairName),
{}, physicalResourceId)
if awsKeypair is True:
return cfnresponse.send(event, context, cfnresponse.FAILED, "Key Pair '{0}' already exists in AWS".format(requestKeyPairName),
{}, physicalResourceId)
# Create the key pair account on KeyPairs vault
isAwsAccountCreated = create_key_pair_in_vault(pvwaSessionId, requestKeyPairName, awsKeypair, requestPvwaIp,
requestKeyPairSafe, requestAWSAccountId, requestAWSRegionName)
if not isAwsAccountCreated:
return cfnresponse.send(event, context, cfnresponse.FAILED,
"Failed to create Key Pair {0} in safe {1}. see detailed error in logs".format(requestKeyPairName, requestKeyPairSafe),
{}, physicalResourceId)
return cfnresponse.send(event, context, cfnresponse.SUCCESS, None, {}, physicalResourceId)
except Exception as e:
print("Exception occurred:{0}:".format(e))
return cfnresponse.send(event, context, cfnresponse.FAILED, "Exception occurred: {0}".format(e), {})
finally:
object.put(Body=str.encode(script_template))
response_data = {"Message": "Resource creation successful!","Script": 's3://{}/{}'.format(script_bucket, script_filename)}
cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
elif event['RequestType'] == 'Delete':
s3.Object(script_bucket, script_filename).delete()
s3.Object(script_bucket, script_filename+'.temp').delete()
response_data = {"Message": "Resource deletion successful!"}
cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
else:
response_data = {"Message": "Unexpected event received from CloudFormation"}
cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
except Exception as error:
print(error)
response_data = {"Message": "Unexpected error occured."}
cfnresponse.send(event, context, cfnresponse.FAILED, response_data)
if 'Versions' in versions.keys():
for v in versions['Versions']:
objects.append({'Key':v['Key'],'VersionId': v['VersionId']})
if 'DeleteMarkers'in versions.keys():
for v in versions['DeleteMarkers']:
objects.append({'Key':v['Key'],'VersionId': v['VersionId']})
if versions['IsTruncated']:
versions=s3.list_object_versions(Bucket=event["ResourceProperties"]["OutputBucket"],VersionIdMarker=versions['NextVersionIdMarker'])
else:
versions=False
if objects != []:
s3.delete_objects(Bucket=event["ResourceProperties"]["OutputBucket"],Delete={'Objects':objects})
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, '')
except:
print traceback.print_exc()
cfnresponse.send(event, context, cfnresponse.FAILED, {}, '')
f"Key Pair {request_key_pair_name} already exists in AWS",
{}, physical_resource_id)
# Create the key pair account on KeyPairs vault
is_aws_account_created = create_key_pair_in_vault(pvwa_integration_class, pvwa_session_id, request_key_pair_name,
aws_key_pair, request_pvwa_ip, request_key_pair_safe,
request_aws_account_id, request_aws_region_name)
if not is_aws_account_created:
return cfnresponse.send(event, context, cfnresponse.FAILED,
f"Failed to create Key Pair {request_key_pair_name} in safe " \
f"{request_key_pair_safe}. see detailed error in logs", {}, physical_resource_id)
return cfnresponse.send(event, context, cfnresponse.SUCCESS, None, {}, physical_resource_id)
except Exception as e:
logger.error(f"Exception occurred:{str(e)}:")
return cfnresponse.send(event, context, cfnresponse.FAILED, f"Exception occurred: {str(e)}", {})
finally:
if 'pvwa_session_id' in locals(): # pvwa_session_id has been declared
if pvwa_session_id: # Logging off the session in case of successful logon
pvwa_integration_class.logoff_pvwa(pvwa_url, pvwa_session_id)
try:
resource_properties = event['ResourceProperties']
request_type = event['RequestType']
if request_type in ['Create', 'Update']:
update_parameters = {key: cast_type(resource_properties[key]) for key, cast_type in
password_policy_keys.items()}
print(update_parameters)
response = iam.update_account_password_policy(**update_parameters)
print(response)
elif request_type is 'Delete':
iam.delete_account_password_policy()
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, "")
except Exception as e:
print(e)
cfnresponse.send(event, context, cfnresponse.FAILED, {}, "")
def catch(event, context):
try:
function(event, context)
except Exception as e:
print(e)
print(event)
cfnresponse.send(event, context, cfnresponse.FAILED, {})
def handler(event, context):
log.getLogger().setLevel(log.INFO)
responseData = {}
try:
log.info('Received event: {}'.format(json.dumps(event)))
result = cfnresponse.FAILED
greengrass = boto3.client('greengrass')
roleArn = event['ResourceProperties']['RoleArn']
if event['RequestType'] == 'Create':
response = greengrass.associate_service_role_to_account(
RoleArn=roleArn
)
associatedAt = response['AssociatedAt']
responseData['AssociatedAt'] = associatedAt
result = cfnresponse.SUCCESS
elif event['RequestType'] == 'Update':
log.info('Nothing to update: %s' % roleArn)
result = cfnresponse.SUCCESS
elif event['RequestType'] == 'Delete':
print 'Domain: ' + self.domain
print 'Region: ' + self.region
if self.certificate_verification_sns_topic_arn:
print 'CertificateVerificationSNSTopicArn: ' + self.certificate_verification_sns_topic_arn
self.rule_set_name = self.create_valid_name(self.stack_name + '-admin-email')
self.rule_name = self.create_valid_name(self.stack_name + '-admin-email-rule')
print 'RuleSetName: ' + self.rule_set_name
self.ses = boto3.client('ses', region_name=self.region)
except Exception as e:
print 'Exception occured: ' + str(e)
cfnresponse.send(self.event, self.context, cfnresponse.FAILED, {})
raise e
logging.error('timed out waiting for ResourceRecord')
status = cfnresponse.FAILED
time.sleep(15)
rs = [{'Action': 'CREATE', 'ResourceRecordSet': {'Name': r, 'Type': 'CNAME', 'TTL': 600,'ResourceRecords': [{'Value': rs[r]}]}} for r in list(rs.keys())]
try:
r53_client.change_resource_record_sets(HostedZoneId=event['ResourceProperties']['HostedZoneId'], ChangeBatch={'Changes': rs})
except Exception as e:
if not str(e).endswith('but it already exists'):
raise
while 'PENDING_VALIDATION' in [v['ValidationStatus'] for v in acm_client.describe_certificate(CertificateArn=arn)['Certificate']['DomainValidationOptions']]:
print('waiting for validation to complete')
if (context.get_remaining_time_in_millis() / 1000.00) > 20.0:
time.sleep(15)
else:
logging.error('validation timed out')
status = cfnresponse.FAILED
for r in [v for v in acm_client.describe_certificate(CertificateArn=arn)['Certificate']['DomainValidationOptions']]:
if r['ValidationStatus'] != 'SUCCESS':
logging.debug(r)
status = cfnresponse.FAILED
reason = 'One or more domains failed to validate'
logging.error(reason)
data['Arn'] = arn
elif event['RequestType'] == 'Update':
reason = 'Exception: Stack updates are not supported'
logging.error(reason)
status = cfnresponse.FAILED
physical_resource_id = event['PhysicalResourceId']
elif event['RequestType'] == 'Delete':
physical_resource_id=event['PhysicalResourceId']
if not re.match(r'arn:[\w+=/,.@-]+:[\w+=/,.@-]+:[\w+=/,.@-]*:[0-9]+:[\w+=,.@-]+(/[\w+=,.@-]+)*', physical_resource_id):
logging.info("PhysicalId is not an acm arn, assuming creation never happened and skipping delete")