Created
April 6, 2022 08:35
-
-
Save saumalya75/3cc8c1b9f5e114592182f8c8d2c65405 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
import datetime | |
from botocore.exceptions import ClientError | |
from cloudformation_validator.ValidateUtility import ValidateUtility | |
s3_client = boto3.client("s3") | |
s3_resource = boto3.resource("s3") | |
cfn_client = boto3.client('cloudformation') | |
S3_BUCKET = 'linter-testing-bucket' | |
def handler(event, context): | |
cfn_template_key = event['cfn_template_key'] | |
cfn_template_bucket = event.get('cfn_template_bucket', None) or S3_BUCKET | |
print(f"Reading code file - s3://{cfn_template_bucket}/{cfn_template_key}") | |
file_content = s3_client.get_object(Bucket=cfn_template_bucket, Key=cfn_template_key)["Body"].read() | |
tmp_file_name = '/tmp/code_file_f{0}.py'.format(context.aws_request_id.replace('-', '')) | |
print(f"Writing code content to local temp disk with '{tmp_file_name}' name.") | |
with open(tmp_file_name, 'wb') as tw: | |
tw.write(file_content) | |
try: | |
cfn_client.validate_template(TemplateBody=file_content.decode()) | |
config_dict = { | |
'template_file': tmp_file_name | |
} | |
validator = ValidateUtility(config_dict) | |
validation_result = validator.validate() | |
except ClientError as e: | |
validation_result = str(e) | |
result_file_key = "linter-output/cfn-lint-output/{0}".format( | |
cfn_template_key.split('/')[-1].split('.')[0] | |
+ '_lint_output_' | |
+ datetime.datetime.strftime(datetime.datetime.now(), '%Y%m%d%H%M%S') | |
+ '.txt' | |
) | |
print(f"Writing lint result to s3://{cfn_template_bucket}/{result_file_key} file.") | |
s3_resource.Bucket(cfn_template_bucket).put_object(Key=result_file_key, Body=validation_result.encode('utf-8')) | |
print(f"Linting for s3://{cfn_template_bucket}/{cfn_template_key} code file is done.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[
{
"failure_count": "0",
"filename": "/tmp/code_file_f47750bb0aafc4006899166a1f8a32ebe.py",
"file_results": [
{
"id": "F4",
"type": "VIOLATION::WARNING",
"message": "IAM policy should not allow * action",
"logical_resource_ids": ["CFNUserPolicies", "CFNAdminPolicies"]
},
{
"id": "W12",
"type": "VIOLATION::WARNING",
"message": "IAM policy should not allow * resource",
"logical_resource_ids": ["CFNUserPolicies", "CFNAdminPolicies"]
}
]
}
]