├── devsecops └── .gitignore ├── lambda-layers-project ├── layers │ └── python │ │ └── .gitkeep └── sam-layers │ ├── response.json │ ├── event.json │ ├── .DS_Store │ ├── samconfig.toml │ ├── package.json │ ├── layers │ └── nodejs │ │ ├── package.json │ │ └── package-lock.json │ ├── src │ └── putItem.js │ └── template.yaml ├── automated_ci_cd_pipelines ├── samplecode │ ├── python │ │ ├── requirements.txt │ │ ├── ops.py │ │ └── test_ops.py │ └── java │ │ ├── README.md │ │ ├── src │ │ ├── main │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── example │ │ │ │ └── javamavenjunithelloworld │ │ │ │ ├── Hello.java │ │ │ │ └── HelloApp.java │ │ └── test │ │ │ └── java │ │ │ └── com │ │ │ └── example │ │ │ └── javamavenjunithelloworld │ │ │ ├── TestingSecurityManager.java │ │ │ ├── HelloWithTestsIT.java │ │ │ ├── HelloTest.java │ │ │ └── HelloAppTest.java │ │ └── pom.xml ├── input-references │ ├── java │ │ ├── common.yml │ │ ├── installation.yml │ │ ├── reports.yml │ │ ├── post_build.yml │ │ ├── build.yml │ │ └── pre_build.yml │ └── python │ │ ├── common.yml │ │ ├── installation.yml │ │ ├── pre_build.yml │ │ ├── build.yml │ │ ├── post_build.yml │ │ └── reports.yml ├── example-input.json ├── automated-pipeline.drawio ├── pipelinecreation_stack.yml └── pipeline_dependencies.yml ├── api_gateway └── lambda │ ├── vpc │ ├── studentid.json │ ├── update_student.json │ ├── listLambda.py │ ├── getLambda.py │ ├── deleteLambda.py │ ├── updateLambda.py │ ├── dynamodb-policy.json │ ├── Untitled Diagram.drawio │ └── vpc_private_apis.drawio │ ├── lambda_query_strings_path_param.js │ └── lambda_random.js ├── lambda ├── ec2 │ ├── start_stop_ec2_test_data.json │ ├── securitypolicy.json │ ├── launch_ec2.py │ └── start_stop_ec2.py ├── sample-handler-python.zip ├── dynamodb │ ├── s3_bucket_policy.json │ ├── security_policy.json │ ├── dynamo_streams.py │ └── dynamodb-streams.drawio.html └── s3_event_lambda_trigger │ ├── notify.py │ ├── security_policy.json │ ├── Untitled Diagram.drawio │ └── s3_event_trigger_lambda.drawio.html ├── ec2 ├── cloud_watch_agent.drawio.png ├── ec2.sh ├── private-servers │ ├── private-server-1.sh │ └── private-server-2.sh ├── session_manager.drawio ├── cloud_watch_agent.drawio ├── session_manager.json ├── aws_inspector.drawio └── ec2-user-data.sh ├── ecs-cli ├── codepipeline.drawio.png ├── cloudformation │ ├── Readme.md │ └── ecs-ec2-with-cf.yml ├── core-infrastructure │ ├── readme.md │ └── core-infrastructure-setup.yml ├── ecsTaskRole.json ├── cli │ └── readme.md └── codeBuildServiceRole.md ├── sqs ├── Untitled Diagram.drawio.png ├── lambda_sqs_s3-role.json └── lambda_sqs.py ├── open-search ├── aws_openSearch.drawio.png ├── cli-commands.sh └── searchMovies.py ├── s3 ├── encryption_kms │ ├── Untitled Diagram.drawio.png │ ├── Untitled Diagram.drawio │ └── s3_bucket_encryption_kms.json ├── versioning.json └── aws_config.drawio ├── step_functions ├── lambda.py ├── step_function_role.json ├── step_function.json ├── lambda_role.json ├── aws_step_functions.drawio.html └── aws_step_functions.drawio ├── api-gateway-series ├── part01 │ └── lambda-part01.js ├── part4 │ ├── CalcValidatorModel.json │ └── CalcMappingModel.json └── part2 │ └── lambda-part2.js ├── cdk ├── best_practises │ ├── lib │ │ ├── cdk_test-stack.ts │ │ └── cdk_test-stack-suppress-errors.ts │ └── bin │ │ └── cdk_test.ts ├── service_catalog.drawio └── sample-stack.ts ├── README.md ├── alb_logs └── s3_bucket_policy.json ├── dynamodb └── s3 │ ├── lambda_s3_access.json │ └── dynamodb_s3_put_ backup.js ├── ecs └── alb │ └── alb-ecs-cluster.drawio ├── serverless └── backup_codecommit_repos │ ├── readme.md │ ├── backups_from_codecommit_to_s3.drawio │ └── template.yml ├── vpc └── cloudformation │ └── vpc.yaml └── codepipeline.drawio /devsecops/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lambda-layers-project/layers/python/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lambda-layers-project/sam-layers/response.json: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/samplecode/python/requirements.txt: -------------------------------------------------------------------------------- 1 | pytest -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/input-references/java/common.yml: -------------------------------------------------------------------------------- 1 | --- 2 | version: 0.2 3 | phases: 4 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/input-references/python/common.yml: -------------------------------------------------------------------------------- 1 | --- 2 | version: 0.2 3 | phases: 4 | -------------------------------------------------------------------------------- /api_gateway/lambda/vpc/studentid.json: -------------------------------------------------------------------------------- 1 | { 2 | "student_id": "$input.params('student_id')" 3 | } 4 | -------------------------------------------------------------------------------- /lambda-layers-project/sam-layers/event.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Test", 3 | "message": "Hello, World" 4 | } -------------------------------------------------------------------------------- /lambda/ec2/start_stop_ec2_test_data.json: -------------------------------------------------------------------------------- 1 | { 2 | "Instances": "ec2-1,ec2-2", 3 | "action": "Stop" 4 | } 5 | -------------------------------------------------------------------------------- /ec2/cloud_watch_agent.drawio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitmurali/aws_snippets/HEAD/ec2/cloud_watch_agent.drawio.png -------------------------------------------------------------------------------- /ecs-cli/codepipeline.drawio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitmurali/aws_snippets/HEAD/ecs-cli/codepipeline.drawio.png -------------------------------------------------------------------------------- /lambda/sample-handler-python.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitmurali/aws_snippets/HEAD/lambda/sample-handler-python.zip -------------------------------------------------------------------------------- /sqs/Untitled Diagram.drawio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitmurali/aws_snippets/HEAD/sqs/Untitled Diagram.drawio.png -------------------------------------------------------------------------------- /open-search/aws_openSearch.drawio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitmurali/aws_snippets/HEAD/open-search/aws_openSearch.drawio.png -------------------------------------------------------------------------------- /lambda-layers-project/sam-layers/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitmurali/aws_snippets/HEAD/lambda-layers-project/sam-layers/.DS_Store -------------------------------------------------------------------------------- /s3/encryption_kms/Untitled Diagram.drawio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitmurali/aws_snippets/HEAD/s3/encryption_kms/Untitled Diagram.drawio.png -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/input-references/python/installation.yml: -------------------------------------------------------------------------------- 1 | install: 2 | runtime-versions: 3 | python: 3.7 4 | commands: 5 | - pip3 install pytest 6 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/input-references/python/pre_build.yml: -------------------------------------------------------------------------------- 1 | pre_build: 2 | commands: 3 | - python --version 4 | - echo Pylint is successfully completed 5 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/input-references/python/build.yml: -------------------------------------------------------------------------------- 1 | build: 2 | commands: 3 | - python -m pytest --junitxml=pytest_reports/pytest_report.xml 4 | - echo Build steps are completed 5 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/input-references/python/post_build.yml: -------------------------------------------------------------------------------- 1 | post_build: 2 | commands: 3 | - echo Post Build steps execution started 4 | - echo Post Build steps execution completed 5 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/input-references/python/reports.yml: -------------------------------------------------------------------------------- 1 | reports: 2 | pytest_reports: 3 | files: 4 | - "./*.xml" 5 | base-directory: pytest_reports/ 6 | file-format: JUNITXML 7 | -------------------------------------------------------------------------------- /ec2/ec2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | sudo su 3 | yum update -y 4 | yum install -y httpd 5 | systemctl start httpd 6 | systemctl enable httpd 7 | echo "Response coming from server A" > /var/www/html/index.html 8 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/input-references/java/installation.yml: -------------------------------------------------------------------------------- 1 | install: 2 | runtime-versions: 3 | java: corretto8 4 | commands: 5 | - echo ********* Installation steps finished ********* 6 | -------------------------------------------------------------------------------- /api_gateway/lambda/vpc/update_student.json: -------------------------------------------------------------------------------- 1 | { 2 | "student_id": "$input.params('student_id')", 3 | "column_name": "$input.params('table_clmn_name')", 4 | "column_value": "$input.params('table_clmn_value')" 5 | } 6 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/input-references/java/reports.yml: -------------------------------------------------------------------------------- 1 | reports: 2 | sample-java-app-report: 3 | files: 4 | - "./*.xml" 5 | base-directory: "target/surefire-reports" 6 | file-format: "JUNITXML" 7 | -------------------------------------------------------------------------------- /ec2/private-servers/private-server-1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | sudo su 3 | yum update -y 4 | yum install httpd -y 5 | systemctl start httpd 6 | systemctl enable httpd 7 | echo "Response from server 1" > /var/www/html/index.html -------------------------------------------------------------------------------- /ec2/private-servers/private-server-2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | sudo su 3 | yum update -y 4 | yum install httpd -y 5 | systemctl start httpd 6 | systemctl enable httpd 7 | echo "Response from server 2" > /var/www/html/index.html -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/input-references/java/post_build.yml: -------------------------------------------------------------------------------- 1 | post_build: 2 | commands: 3 | - echo Post-Build steps started 4 | - echo Post Build Activities 5 | - echo ********* Post-Build steps finished ********* 6 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/samplecode/python/ops.py: -------------------------------------------------------------------------------- 1 | def add(x,y): 2 | return x+y 3 | 4 | def subtract(x,y): 5 | return x-y 6 | 7 | def multiply(x,y): 8 | return x*y 9 | 10 | def divide(x,y): 11 | return x/y -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/input-references/java/build.yml: -------------------------------------------------------------------------------- 1 | build: 2 | commands: 3 | - echo Build steps started 4 | - mvn clean install 5 | - mvn surefire-report:report 6 | - echo ********* Build steps finished ********* 7 | -------------------------------------------------------------------------------- /step_functions/lambda.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | def lambda_handler(event, context): 4 | 5 | return { 6 | 'statusCode': 200, 7 | 'body': json.dumps("You have invoked lambda function from Step Function successfully") 8 | } -------------------------------------------------------------------------------- /step_functions/step_function_role.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": ["lambda:InvokeFunction"], 7 | "Resource": ["*"] 8 | } 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/input-references/java/pre_build.yml: -------------------------------------------------------------------------------- 1 | pre_build: 2 | commands: 3 | - echo Pre-Build steps Started 4 | - mvn test #-f surefire/pom.xml -fn 5 | - echo 6 | - mvn verify 7 | - echo ********* Pre-Build steps finished ********* 8 | -------------------------------------------------------------------------------- /step_functions/step_function.json: -------------------------------------------------------------------------------- 1 | { 2 | "Comment": "invoke a lambda function", 3 | "StartAt": "invokeLambda", 4 | "States": { 5 | "invokeLambda": { 6 | "Type": "Task", 7 | "Resource": "", 8 | "End": true 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /api_gateway/lambda/vpc/listLambda.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | 4 | client = boto3.resource('dynamodb') 5 | 6 | def lambda_handler(event, context): 7 | table_name = "userdbtable" 8 | table = client.Table(table_name) 9 | response = table.scan() 10 | return response['Items'] -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/example-input.json: -------------------------------------------------------------------------------- 1 | { 2 | "details": { 3 | "tech_stack": "java", // "python" for python projects 4 | "project_name": "java-pipeline-project", 5 | "pre_build": "yes", 6 | "build": "yes", 7 | "post_build": "yes", 8 | "reports": "yes" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /ecs-cli/cloudformation/Readme.md: -------------------------------------------------------------------------------- 1 | # Create ECS cluster based on EC2 2 | 3 | Command to apply the CloudFormation template 4 | 5 | Launchtype _EC2_: 6 | 7 | ```bash 8 | aws cloudformation create-stack --stack-name ecs-type-ec2 --capabilities CAPABILITY_IAM --template-body file://./ecs-ec2-with-cf.yml 9 | ``` -------------------------------------------------------------------------------- /s3/versioning.json: -------------------------------------------------------------------------------- 1 | { 2 | "Id": "Policy1", 3 | "Version": "2012-10-17", 4 | "Statement": [ 5 | { 6 | "Sid": "Stmt1", 7 | "Action": ["s3:GetObject"], 8 | "Effect": "Allow", 9 | "Resource": "/*", 10 | "Principal": "*" 11 | } 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /open-search/cli-commands.sh: -------------------------------------------------------------------------------- 1 | #Post data to open search from cli. 2 | curl -XPOST -u 'username:password' 'open-search-domain/_bulk' --data-binary @bulk_movies.json -H 'Content-Type: application/json' 3 | 4 | 5 | #Search from cli 6 | curl -XGET -u 'username:password' 'open-search-domain/movies/_search?q=hero&pretty=true' -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/samplecode/python/test_ops.py: -------------------------------------------------------------------------------- 1 | from ops import * 2 | 3 | def test_add(): 4 | assert add(2,3) == 5 5 | 6 | def test_subtract(): 7 | assert subtract(2, 3) == -1 8 | 9 | def test_multiply(): 10 | assert multiply(2, 3) == 6 11 | 12 | def test_divide(): 13 | assert divide(10,5) == 2 -------------------------------------------------------------------------------- /step_functions/lambda_role.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "logs:CreateLogStream", 8 | "logs:CreateLogGroup", 9 | "logs:PutLogEvents" 10 | ], 11 | "Resource": ["*"] 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /api_gateway/lambda/lambda_query_strings_path_param.js: -------------------------------------------------------------------------------- 1 | export const handler = async (event) => { 2 | // TODO implement 3 | 4 | const response = { 5 | statusCode: 200, 6 | body: `Hellow from ${event["queryStringParameters"]["name"]} and ${event["pathParameters"]["name"]}`, 7 | }; 8 | 9 | return response; 10 | }; 11 | -------------------------------------------------------------------------------- /api-gateway-series/part01/lambda-part01.js: -------------------------------------------------------------------------------- 1 | // How to pass path params and query strings 2 | 3 | export const handler = async (event) => { 4 | const response = { 5 | statusCode: 200, 6 | body: `Good ${event["queryStringParameters"]["greeting"]}, nice to meet you ${event["pathParameters"]["name"]}!!`, 7 | }; 8 | 9 | return response; 10 | }; 11 | -------------------------------------------------------------------------------- /lambda-layers-project/sam-layers/samconfig.toml: -------------------------------------------------------------------------------- 1 | version=0.1 2 | [default.global.parameters] 3 | stack_name = "sam-layers" 4 | 5 | [default.deploy.parameters] 6 | region = "us-east-1" 7 | s3_bucket = "YOUR_S3_BUCKET" 8 | s3_prefix = "layers" 9 | confirm_changeset = false 10 | capabilities = "CAPABILITY_IAM" 11 | tags = "project=\"samLayers\" stage=\"development\"" -------------------------------------------------------------------------------- /ecs-cli/core-infrastructure/readme.md: -------------------------------------------------------------------------------- 1 | # Create core AWS infrastructure 2 | 3 | - VPC 4 | - 2 subnets in 2 different AZs 5 | - Internet Gateway (IGW) 6 | - route tables 7 | 8 | Command: 9 | 10 | ```bash 11 | aws cloudformation create-stack --capabilities CAPABILITY_IAM --stack-name ecs-core-infrastructure --template-body file://./core-infrastructure-setup.yml 12 | ``` -------------------------------------------------------------------------------- /api-gateway-series/part4/CalcValidatorModel.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json-schema.org/draft/2020-12/schema", 3 | "title": "Calculator Validator Model", 4 | "type": "object", 5 | "properties": { 6 | "num1": { 7 | "type": "number" 8 | }, 9 | "num2": { 10 | "type": "number" 11 | } 12 | }, 13 | "required": ["num1", "num2"] 14 | } 15 | -------------------------------------------------------------------------------- /lambda-layers-project/sam-layers/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sam-layers", 3 | "description": "sam-layers", 4 | "version": "0.0.1", 5 | "private": true, 6 | "dependencies": { 7 | "aws-sdk": "^2.799.0" 8 | }, 9 | "devDependencies": { 10 | "jest": "^26.6.3" 11 | }, 12 | "scripts": { 13 | "test": "jest" 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /lambda-layers-project/sam-layers/layers/nodejs/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "scripts": { 6 | "test": "echo \"Error: no test specified\" && exit 1" 7 | }, 8 | "keywords": [], 9 | "author": "", 10 | "license": "ISC", 11 | "description": "", 12 | "dependencies": { 13 | "uuid": "^11.1.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /cdk/best_practises/lib/cdk_test-stack.ts: -------------------------------------------------------------------------------- 1 | import { Stack, StackProps } from "aws-cdk-lib"; 2 | import { Construct } from "constructs"; 3 | import { Bucket } from "aws-cdk-lib/aws-s3"; 4 | 5 | export class CdkTestStack extends Stack { 6 | constructor(scope: Construct, id: string, props?: StackProps) { 7 | super(scope, id, props); 8 | const bucket = new Bucket(this, "Bucket"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /api_gateway/lambda/lambda_random.js: -------------------------------------------------------------------------------- 1 | exports.handler = async (event) => { 2 | const quotes = [ 3 | "Stay Hungry. Stay Foolish.", 4 | "Good Artists Copy, Great Artists Steal.", 5 | "Argue with idiots, and you become an idiot.", 6 | "Be yourself; everyone else is already taken.", 7 | "Simplicity is the ultimate sophistication.", 8 | ]; 9 | 10 | return quotes[Math.floor(Math.random() * 5)]; 11 | }; 12 | -------------------------------------------------------------------------------- /s3/aws_config.drawio: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /cdk/best_practises/bin/cdk_test.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | import "source-map-support/register"; 3 | import * as cdk from "aws-cdk-lib"; 4 | import { CdkTestStack } from "../lib/cdk_test-stack"; 5 | import { AwsSolutionsChecks } from "cdk-nag"; 6 | import { Aspects } from "aws-cdk-lib"; 7 | 8 | const app = new cdk.App(); 9 | // Add the cdk-nag AwsSolutions Pack with extra verbose logging enabled. 10 | Aspects.of(app).add(new AwsSolutionsChecks({ verbose: true })); 11 | new CdkTestStack(app, "CdkTestStack", {}); 12 | -------------------------------------------------------------------------------- /cdk/service_catalog.drawio: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/automated-pipeline.drawio: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /sqs/lambda_sqs_s3-role.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "logs:*" 8 | ], 9 | "Resource": "arn:aws:logs:*:*:*" 10 | }, 11 | { 12 | "Effect": "Allow", 13 | "Action": [ 14 | "s3:GetObject", 15 | "s3:PutObject" 16 | ], 17 | "Resource": "arn:aws:s3:::*" 18 | }, 19 | { 20 | "Effect": "Allow", 21 | "Action": [ 22 | "s3:*", 23 | "SQS:*", 24 | "s3-object-lambda:*" 25 | ], 26 | "Resource": "*" 27 | } 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /api_gateway/lambda/vpc/getLambda.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import boto3 4 | 5 | client = boto3.resource('dynamodb') 6 | 7 | def lambda_handler(event, context): 8 | table_name = "userdbtable" 9 | table = client.Table(table_name) 10 | try: 11 | student_id = event['student_id'] 12 | response = table.get_item(Key={ 13 | "id": student_id 14 | }) 15 | return (response['Item']) 16 | except Exception as e: 17 | return { 18 | "status": "400 - failed to retrieve item by id" 19 | } -------------------------------------------------------------------------------- /api-gateway-series/part4/CalcMappingModel.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json-schema.org/draft/2020-12/schema", 3 | "title": "Calculator Mapping Model", 4 | "type": "object", 5 | "properties": { 6 | "operation": { 7 | "type": "string" 8 | }, 9 | "inputs": { 10 | "type": "object", 11 | "properties": { 12 | "op1": { 13 | "type": "number" 14 | }, 15 | "op2": { 16 | "type": "number" 17 | } 18 | }, 19 | "required": ["op1", "op2"] 20 | } 21 | }, 22 | "required": ["operation", "inputs"] 23 | } 24 | -------------------------------------------------------------------------------- /cdk/sample-stack.ts: -------------------------------------------------------------------------------- 1 | import * as cdk from "aws-cdk-lib"; 2 | import * as lambda from "aws-cdk-lib/aws-lambda"; 3 | import { Construct } from "constructs"; 4 | 5 | export class SampleStack extends cdk.Stack { 6 | constructor(scope: Construct, id: string, props?: cdk.StackProps) { 7 | super(scope, id, props); 8 | 9 | const hello = new lambda.Function(this, "SampleLambda", { 10 | runtime: lambda.Runtime.NODEJS_14_X, 11 | code: lambda.Code.fromInline( 12 | 'exports.handler = async () => "hello world";' 13 | ), 14 | handler: "index.handler", 15 | }); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /lambda-layers-project/sam-layers/src/putItem.js: -------------------------------------------------------------------------------- 1 | const dynamodb = require("aws-sdk/clients/dynamodb"); 2 | const docClient = new dynamodb.DocumentClient(); 3 | const tableName = process.env.TableName; 4 | 5 | const { v4: uuidv4 } = require("uuid"); 6 | 7 | exports.handler = async (event) => { 8 | const { name, message } = event; 9 | 10 | const params = { 11 | TableName: tableName, 12 | Item: { 13 | id: uuidv4(), 14 | name: name, 15 | message: message, 16 | }, 17 | }; 18 | 19 | const result = await docClient.put(params).promise(); 20 | 21 | return result; 22 | }; 23 | -------------------------------------------------------------------------------- /api-gateway-series/part2/lambda-part2.js: -------------------------------------------------------------------------------- 1 | export const handler = async (event) => { 2 | const { op1, op2 } = event.inputs; 3 | let result; 4 | 5 | switch (event.operation) { 6 | case "add": 7 | result = op1 + op2; 8 | break; 9 | case "subtract": 10 | result = op1 - op2; 11 | break; 12 | case "multiply": 13 | result = op1 * op2; 14 | break; 15 | case "divide": 16 | result = op1 / op2; 17 | break; 18 | } 19 | 20 | const response = { 21 | statusCode: 200, 22 | body: JSON.stringify(result), 23 | }; 24 | return response; 25 | }; 26 | -------------------------------------------------------------------------------- /api_gateway/lambda/vpc/deleteLambda.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | import json 4 | 5 | client = boto3.resource('dynamodb') 6 | 7 | def lambda_handler(event, context): 8 | table_name = "userdbtable" 9 | table = client.Table(table_name) 10 | try: 11 | student_id = event['student_id'] 12 | response = table.delete_item( 13 | Key={ 14 | "id": student_id 15 | }) 16 | return { 17 | "status": "200 - Success" 18 | } 19 | except Exception as e: 20 | return { 21 | "status": "400 - failed to delete item" 22 | } -------------------------------------------------------------------------------- /lambda/dynamodb/s3_bucket_policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Id": "my-bucket-policy", 4 | "Statement": [ 5 | { 6 | "Effect": "Allow", 7 | "Principal": "*", 8 | "Action": "s3:GetObject", 9 | "Resource": "/*" 10 | }, 11 | { 12 | "Effect": "Allow", 13 | "Principal": { 14 | "AWS": "*" 15 | }, 16 | "Action": "s3:PutObject", 17 | "Resource": "/*" 18 | }, 19 | { 20 | "Effect": "Allow", 21 | "Principal": { 22 | "AWS": "*" 23 | }, 24 | "Action": "s3:DeleteBucket", 25 | "Resource": "" 26 | } 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /lambda/ec2/securitypolicy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Sid": "VisualEditor0", 6 | "Effect": "Allow", 7 | "Action": [ 8 | "ec2:AuthorizeSecurityGroupEgress", 9 | "ec2:AuthorizeSecurityGroupIngress", 10 | "ec2:DescribeInstances", 11 | "ec2:StartInstances", 12 | "ec2:DescribeTags", 13 | "ec2:CreateKeyPair", 14 | "ec2:CreateSecurityGroup", 15 | "ec2:CreateTags", 16 | "ec2:RunInstances", 17 | "ec2:StopInstances" 18 | ], 19 | "Resource": "*", 20 | "Condition": { 21 | "StringEquals": { 22 | "ec2:Region": "eu-west-2" 23 | } 24 | } 25 | } 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /sqs/lambda_sqs.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | 4 | def lambda_handler(event, context): 5 | sqs_msg = json.loads(event['Records'][0]['body']) 6 | print("SQS Message : ", sqs_msg) 7 | bucket_name = "sqs-lambda-bucket-123" 8 | 9 | try: 10 | s3Client = boto3.client("s3", region_name= "us-east-1") 11 | Response = s3Client.put_object(Bucket= bucket_name, Key= "sqs_message.json", Body= json.dumps(sqs_msg)) 12 | print("S3 upload successful !") 13 | 14 | return { 15 | "status" : 200, 16 | "body" : "S3 upload success" 17 | } 18 | 19 | except Exception as e: 20 | print("Client connection to S3 failed because ", e) 21 | return{ 22 | "status" : 500, 23 | "body" : "S3 upload failed" 24 | } -------------------------------------------------------------------------------- /lambda-layers-project/sam-layers/layers/nodejs/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs", 3 | "version": "1.0.0", 4 | "lockfileVersion": 3, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "nodejs", 9 | "version": "1.0.0", 10 | "license": "ISC", 11 | "dependencies": { 12 | "uuid": "^11.1.0" 13 | } 14 | }, 15 | "node_modules/uuid": { 16 | "version": "11.1.0", 17 | "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", 18 | "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", 19 | "funding": [ 20 | "https://github.com/sponsors/broofa", 21 | "https://github.com/sponsors/ctavan" 22 | ], 23 | "bin": { 24 | "uuid": "dist/esm/bin/uuid" 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /api_gateway/lambda/vpc/updateLambda.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | 4 | client = boto3.resource('dynamodb') 5 | 6 | def lambda_handler(event, context): 7 | table_name = "userdbtable" 8 | table = client.Table(table_name) 9 | 10 | try: 11 | student_id = event['student_id'] 12 | column_name = event['table_clmn_name'] 13 | column_value = event['table_clmn_value'] 14 | response = table.update_item( 15 | Key={'id': student_id}, 16 | UpdateExpression="SET {} = :l".format(column_name), 17 | ConditionExpression="attribute_exists(id)", 18 | ExpressionAttributeValues={':l': column_value}, 19 | ReturnValues="ALL_NEW" 20 | ) 21 | return (response['Attributes']) 22 | except Exception as e: 23 | return { 24 | "status": "400 - failed to update item." 25 | } 26 | -------------------------------------------------------------------------------- /lambda/dynamodb/security_policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "dynamodb:Describe*", 8 | "dynamodb:Get*", 9 | "dynamodb:List*", 10 | "dynamodb:Batch*", 11 | "logs:CreateLogGroup", 12 | "logs:CreateLogStream", 13 | "logs:Get*", 14 | "logs:List*", 15 | "logs:Describe*", 16 | "logs:PutLogEvents", 17 | "dynamodb:PutItem", 18 | "cloudwatch:Describe*", 19 | "cloudwatch:Get*", 20 | "cloudwatch:List*", 21 | "sns:CreateTopic", 22 | "application-autoscaling:Describe*", 23 | "s3:PutObject", 24 | "s3:List*", 25 | "s3:Get*", 26 | "dynamodb:Scan", 27 | "tag:Describe*", 28 | "tag:Get*" 29 | ], 30 | "Resource": "*" 31 | } 32 | ] 33 | } 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Welcome to AWS snippets 2 | 3 | ![GitHub stars](https://img.shields.io/github/stars/gitmurali/aws_snippets?style=social) 4 | ![GitHub forks](https://img.shields.io/github/forks/gitmurali/aws_snippets?style=social) 5 | ![GitHub watchers](https://img.shields.io/github/watchers/gitmurali/aws_snippets?style=social) 6 | ![GitHub repo size](https://img.shields.io/github/repo-size/gitmurali/aws_snippets) 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | Star History Chart 15 | 16 | -------------------------------------------------------------------------------- /api_gateway/lambda/vpc/dynamodb-policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Sid": "ListAndDescribe", 6 | "Effect": "Allow", 7 | "Action": [ 8 | "dynamodb:List*", 9 | "dynamodb:DescribeReservedCapacity*", 10 | "dynamodb:DescribeLimits", 11 | "dynamodb:DescribeTimeToLive" 12 | ], 13 | "Resource": "*" 14 | }, 15 | { 16 | "Sid": "SpecificTable", 17 | "Effect": "Allow", 18 | "Action": [ 19 | "dynamodb:BatchGet*", 20 | "dynamodb:DescribeStream", 21 | "dynamodb:DescribeTable", 22 | "dynamodb:Get*", 23 | "dynamodb:Query", 24 | "dynamodb:Scan", 25 | "dynamodb:BatchWrite*", 26 | "dynamodb:CreateTable", 27 | "dynamodb:Delete*", 28 | "dynamodb:Update*", 29 | "dynamodb:PutItem" 30 | ], 31 | "Resource": "arn:aws:dynamodb:*:*:table/userdbtable" 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /cdk/best_practises/lib/cdk_test-stack-suppress-errors.ts: -------------------------------------------------------------------------------- 1 | import { Stack, StackProps } from "aws-cdk-lib"; 2 | import { Construct } from "constructs"; 3 | import { Bucket } from "aws-cdk-lib/aws-s3"; 4 | import { NagSuppressions } from "cdk-nag"; 5 | 6 | export class CdkTestStack extends Stack { 7 | constructor(scope: Construct, id: string, props?: StackProps) { 8 | super(scope, id, props); 9 | // The local scope 'this' is the Stack. 10 | NagSuppressions.addStackSuppressions(this, [ 11 | { 12 | id: "AwsSolutions-S1", 13 | reason: "Demonstrate a stack level suppression.", 14 | }, 15 | ]); 16 | // Remediating AwsSolutions-S10 by enforcing SSL on the bucket. 17 | const bucket = new Bucket(this, "Bucket", { enforceSSL: true }); 18 | NagSuppressions.addResourceSuppressions(bucket, [ 19 | { 20 | id: "AwsSolutions-S2", 21 | reason: "Demonstrate a resource level suppression.", 22 | }, 23 | ]); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /alb_logs/s3_bucket_policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Id": "AWSConsole-AccessLogs-Policy-1668943070662", 4 | "Statement": [ 5 | { 6 | "Sid": "AWSConsoleStmt-1668943070662", 7 | "Effect": "Allow", 8 | "Principal": { 9 | "AWS": "" 10 | }, 11 | "Action": "s3:PutObject", 12 | "Resource": "arn:aws:s3:::murali-alb-logs-abc/prefix/AWSLogs//*" 13 | }, 14 | { 15 | "Sid": "AWSLogDeliveryWrite", 16 | "Effect": "Allow", 17 | "Principal": { 18 | "Service": "delivery.logs.amazonaws.com" 19 | }, 20 | "Action": "s3:PutObject", 21 | "Resource": "arn:aws:s3:::my-alb-logs-abc/prefix/AWSLogs//*", 22 | "Condition": { 23 | "StringEquals": { 24 | "s3:x-amz-acl": "bucket-owner-full-control" 25 | } 26 | } 27 | }, 28 | { 29 | "Sid": "AWSLogDeliveryAclCheck", 30 | "Effect": "Allow", 31 | "Principal": { 32 | "Service": "delivery.logs.amazonaws.com" 33 | }, 34 | "Action": "s3:GetBucketAcl", 35 | "Resource": "arn:aws:s3:::my-alb-logs-abc" 36 | } 37 | ] 38 | } -------------------------------------------------------------------------------- /lambda/ec2/launch_ec2.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | import time 4 | from botocore.exceptions import ClientError 5 | 6 | def lambda_handler(event, context): 7 | # Provision and launch the EC2 instance 8 | ec2_client = boto3.client('ec2') 9 | try: 10 | response = ec2_client.run_instances(ImageId='ami-04706e771f950937f', 11 | InstanceType='t2.micro', 12 | MinCount=1, 13 | MaxCount=1) 14 | 15 | print(response['Instances'][0], "EC2 Instance Created") 16 | return { 17 | 'statusCode': 200, 18 | 'body': json.dumps("success") 19 | } 20 | 21 | except ClientError as e: 22 | print("Detailed error: ", e) 23 | return { 24 | 'statusCode': 500, 25 | 'body': json.dumps("error") 26 | } 27 | 28 | except Exception as e: 29 | print("Detailed error: ", e) 30 | return { 31 | 'statusCode': 500, 32 | 'body': json.dumps("error") 33 | } 34 | -------------------------------------------------------------------------------- /lambda/s3_event_lambda_trigger/notify.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import json 3 | 4 | def lambda_handler(event, context): 5 | 6 | for e in event["Records"]: 7 | bucketName = e["s3"]["bucket"]["name"] 8 | objectName = e["s3"]["object"]["key"] 9 | eventName = e["eventName"] 10 | 11 | bClient = boto3.client("ses") 12 | 13 | eSubject = 'AWS' + str(eventName) + 'Event' 14 | 15 | eBody = """ 16 |
17 | Hey,
18 | 19 | Welcome to AWS S3 notification lambda trigger
20 | 21 | We are here to notify you that {} an event was triggered.
22 | Bucket name : {}
23 | Object name : {} 24 |
25 | """.format(eventName, bucketName, objectName) 26 | 27 | send = {"Subject": {"Data": eSubject}, "Body": {"Html": {"Data": eBody}}} 28 | result = bClient.send_email(Source= "info@muraliprashanth.me", Destination= {"ToAddresses": ["info@muraliprashanth.me"]}, Message= send) 29 | 30 | return { 31 | 'statusCode': 200, 32 | 'body': json.dumps(result) 33 | } 34 | -------------------------------------------------------------------------------- /lambda-layers-project/sam-layers/template.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: "2010-09-09" 2 | Transform: AWS::Serverless-2016-10-31 3 | 4 | Resources: 5 | # DynamoDB Table 6 | LabTable: 7 | Type: AWS::Serverless::SimpleTable 8 | Properties: 9 | ProvisionedThroughput: 10 | ReadCapacityUnits: 5 11 | WriteCapacityUnits: 5 12 | 13 | # Lambda Function 14 | NodejsLabFunction: 15 | Type: AWS::Serverless::Function 16 | Properties: 17 | FunctionName: NodejsLabFunction 18 | CodeUri: src/ 19 | Handler: putItem.handler 20 | Runtime: nodejs16.x 21 | Role: YOUR_LambdaExecRole 22 | Environment: 23 | Variables: 24 | TableName: !Ref LabTable 25 | Layers: 26 | - !Ref NodeLayer 27 | 28 | NodeLayer: 29 | Type: AWS::Serverless::LayerVersion 30 | Properties: 31 | LayerName: js-layer 32 | Description: Node dependencies for NodejsLabFunction 33 | ContentUri: layers/ 34 | CompatibleRuntimes: 35 | - nodejs16.x 36 | RetentionPolicy: Delete 37 | 38 | Outputs: 39 | TableName: 40 | Value: !Ref LabTable 41 | -------------------------------------------------------------------------------- /dynamodb/s3/lambda_s3_access.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "s3:List*", 8 | "s3:Get*", 9 | "s3:Put*", 10 | "s3:CreateBucket", 11 | "s3:DeleteBucket", 12 | "s3-object-lambda:List*", 13 | "s3-object-lambda:Get*", 14 | "s3:PutBucketNotification" 15 | ], 16 | "Resource": [ 17 | "arn:aws:s3:::dynamodb-json-backup", 18 | "arn:aws:s3:::dynamodb-json-backup/*" 19 | ], 20 | "Condition": { 21 | "StringEquals": { 22 | "aws:RequestedRegion": "us-east-1" 23 | } 24 | } 25 | }, 26 | { 27 | "Action": [ 28 | "dynamodb:Get*", 29 | "dynamodb:List*", 30 | "dynamodb:Describe*", 31 | "dynamodb:CreateTable", 32 | "dynamodb:DeleteTable", 33 | "dynamodb:Scan" 34 | ], 35 | "Effect": "Allow", 36 | "Resource": "*", 37 | "Condition": { 38 | "StringEquals": { 39 | "aws:RequestedRegion": "us-east-1" 40 | } 41 | } 42 | } 43 | ] 44 | } 45 | -------------------------------------------------------------------------------- /ecs-cli/ecsTaskRole.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "secretsmanager:GetSecretValue", 8 | "ssm:GetParameters", 9 | "kms:Decrypt" 10 | ], 11 | "Resource": [ 12 | "arn:aws:secretsmanager:::secret:*", 13 | "arn:aws:ssm:::parameter/*", 14 | "arn:aws:kms:::*" 15 | ] 16 | }, 17 | { 18 | "Effect": "Allow", 19 | "Action": [ 20 | "s3:GetObject" 21 | ], 22 | "Resource": [ 23 | "arn:aws:s3:::-/env-demo.env" 24 | ] 25 | }, 26 | { 27 | "Effect": "Allow", 28 | "Action": [ 29 | "s3:GetBucketLocation" 30 | ], 31 | "Resource": [ 32 | "arn:aws:s3:::-" 33 | ] 34 | } 35 | ] 36 | } 37 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/samplecode/java/README.md: -------------------------------------------------------------------------------- 1 | # A Java/Maven/JUnit HelloWorld example 2 | 3 | A "Hello World!” sample written in Java using Maven for the build, that showcases a few very simple tests. 4 | 5 | This example demonstrates: 6 | * A simple Java 8 application with tests 7 | * Unit tests written with [JUnit 5](https://junit.org/junit5/) 8 | * Integration tests written with [JUnit 5](https://junit.org/junit5/) 9 | * Code coverage reports via [JaCoCo](https://www.jacoco.org/jacoco/) 10 | * A Maven build that puts it all together 11 | 12 | ## Running the tests 13 | 14 | * To run the unit tests, call `mvn test` 15 | * To run the integration tests as well, call `mvn verify` 16 | * Code coverage reports are generated when `mvn verify` (or a full `mvn clean install`) is called. 17 | Point a browser at the output in `target/site/jacoco-both/index.html` to see the report. 18 | 19 | ## Conventions 20 | 21 | This example follows the following basic conventions: 22 | 23 | | | unit test | integration test | 24 | | --- | --- | --- | 25 | | **resides in:** | `src/test/java/*Test.java` | `src/test/java/*IT.java` | 26 | | **executes in Maven phase:** | test | verify | 27 | | **handled by Maven plugin:** | [surefire](http://maven.apache.org/surefire/maven-surefire-plugin/) | [failsafe](http://maven.apache.org/surefire/maven-failsafe-plugin/) | 28 | -------------------------------------------------------------------------------- /ecs-cli/cli/readme.md: -------------------------------------------------------------------------------- 1 | # Create ECS cluster using ecs-cli 2 | 3 | # add ecs cli to your command line 4 | ```bash 5 | curl https://amazon-ecs-cli.s3.amazonaws.com/ecs-cli-linux-amd64-latest -o "ecs-cli" 6 | sudo chmod +x ./ecs-cli 7 | sudo mv ./ecs-cli /usr/local/bin 8 | 9 | #check 10 | ecs-cli --version 11 | 12 | # configure 13 | ecs-cli configure profile --access-key <> --secret-key <> 14 | ``` 15 | 16 | # set your vpc and subnets 17 | 18 | ```bash 19 | export CORE_STACK_NAME="ecs-core-infrastructure" 20 | export vpc=$(aws cloudformation describe-stacks --stack-name $CORE_STACK_NAME --query 'Stacks[0].Outputs[?OutputKey==`VpcId`].OutputValue' --output text) 21 | export subnet_1=$(aws cloudformation describe-stacks --stack-name $CORE_STACK_NAME --query 'Stacks[0].Outputs[?OutputKey==`PublicSubnetOne`].OutputValue' --output text) 22 | export subnet_2=$(aws cloudformation describe-stacks --stack-name $CORE_STACK_NAME --query 'Stacks[0].Outputs[?OutputKey==`PublicSubnetTwo`].OutputValue' --output text) 23 | 24 | echo "vpc: $vpc" 25 | echo "subnet1: $subnet_1" 26 | echo "subnet2: $subnet_2" 27 | 28 | ``` 29 | 30 | # ecs using EC2 type 31 | 32 | ```bash 33 | ecs-cli up --capability-iam \ 34 | --subnets $subnet_1,$subnet_2 \ 35 | --vpc $vpc \ 36 | --launch-type EC2 \ 37 | --keypair my-ecs-env \ 38 | --size 1 \ 39 | --instance-type t2.small \ 40 | --cluster ecs-ec2 41 | ``` 42 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/samplecode/java/src/main/java/com/example/javamavenjunithelloworld/Hello.java: -------------------------------------------------------------------------------- 1 | package com.example.javamavenjunithelloworld; 2 | 3 | import java.io.PrintStream; 4 | 5 | /** 6 | * Simple class that says "Hello!". 7 | */ 8 | public class Hello { 9 | 10 | static final String HELLO = "Hello!"; 11 | 12 | public static final int MAXIMUM_AMOUNT_OF_TIMES = 20; 13 | 14 | private int times = 1; 15 | 16 | /** 17 | * Set how many times "Hello!" should be said. 18 | * 19 | * @param times How many times should this class say "Hello!"? The value should be no larger than 20. 20 | * @throws IllegalArgumentException Thrown when times is larger than 20 or a negative number. 21 | */ 22 | public void setTimes(int times) { 23 | if (times < 0 || times > MAXIMUM_AMOUNT_OF_TIMES) { 24 | throw new IllegalArgumentException(String.format( 25 | "Parameter «times» should be a positive number no larger than %d.", 26 | MAXIMUM_AMOUNT_OF_TIMES 27 | )); 28 | } 29 | this.times = times; 30 | } 31 | 32 | /** 33 | * Say "Hello!". 34 | * 35 | * @param printer PrintStream to write output to. 36 | */ 37 | public void sayHello(PrintStream printer) { 38 | for (short i = 0; i < times; i++) { 39 | printer.println(HELLO); 40 | } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/samplecode/java/src/test/java/com/example/javamavenjunithelloworld/TestingSecurityManager.java: -------------------------------------------------------------------------------- 1 | package com.example.javamavenjunithelloworld; 2 | 3 | import java.security.Permission; 4 | 5 | /** 6 | * A special implementation of {@link SecurityManager} that throws a {@link RuntimeException} when 7 | * {@link System#exit(int)} is called. This allows us to test the exit codes generated by our little application in a 8 | * test. 9 | */ 10 | public class TestingSecurityManager extends SecurityManager { 11 | @Override 12 | public void checkPermission(Permission perm) { 13 | // Allow everything. 14 | } 15 | 16 | @Override 17 | public void checkPermission(Permission perm, Object context) { 18 | // Allow everything. 19 | } 20 | 21 | @Override 22 | public void checkExit(int status) { 23 | super.checkExit(status); 24 | // By throwing a RuntimeException, we can catch it in our tests and verify the exit code. 25 | throw new TestExitException(status); 26 | } 27 | 28 | /** 29 | * An exception that stores the exit code for later verification. 30 | */ 31 | public static class TestExitException extends RuntimeException { 32 | private final int status; 33 | 34 | public TestExitException(int status) { 35 | this.status = status; 36 | } 37 | 38 | public int getStatus() { 39 | return status; 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/samplecode/java/src/main/java/com/example/javamavenjunithelloworld/HelloApp.java: -------------------------------------------------------------------------------- 1 | package com.example.javamavenjunithelloworld; 2 | 3 | /** 4 | * A very basic program that demonstrates the use of JUnit tests. The tests include a sample unit test and an 5 | * integration test. 6 | */ 7 | public class HelloApp { 8 | 9 | static int DEFAULT_TIMES = 3; 10 | 11 | static int EXIT_STATUS_PARAMETER_NOT_UNDERSTOOD = 2; 12 | static int EXIT_STATUS_HELLO_FAILED = 4; 13 | 14 | /** 15 | * The main method of this program. 16 | * 17 | * @param args Arguments passed to this program. 18 | */ 19 | public static void main(String[] args) { 20 | 21 | int times = DEFAULT_TIMES; 22 | if (args.length >= 1) { 23 | try { 24 | times = Integer.valueOf(args[0]); 25 | } catch (NumberFormatException e) { 26 | System.err.println("I don't understand the parameter you passed me. Is it a number? " + 27 | "Parameter was: [" + args[0] + "]"); 28 | System.exit(EXIT_STATUS_PARAMETER_NOT_UNDERSTOOD); 29 | } 30 | } 31 | 32 | Hello hi = new Hello(); 33 | try { 34 | hi.setTimes(times); 35 | } catch (IllegalArgumentException e) { 36 | System.err.println("Something went wrong: " + e.getMessage()); 37 | System.exit(EXIT_STATUS_HELLO_FAILED); 38 | } 39 | hi.sayHello(System.out); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /open-search/searchMovies.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import json 3 | from botocore.auth import SigV4Auth 4 | from botocore.awsrequest import AWSRequest 5 | import requests 6 | 7 | session = boto3.Session() 8 | credentials = session.get_credentials() 9 | creds = credentials.get_frozen_credentials() 10 | 11 | region = 'eu-west-2' 12 | service = 'es' 13 | 14 | host = 'https://search-movies-cnl2tufhuy2b6m5ty6bisa2234.eu-west-2.es.amazonaws.com' 15 | index = 'movies' 16 | url = host + '/' + index + '/_search' 17 | 18 | def signed_request(method, url, data=None, params=None, headers=None): 19 | request = AWSRequest(method=method, url=url, data=data, params=params, headers=headers) 20 | SigV4Auth(creds, service, region).add_auth(request) 21 | return requests.request(method=method, url=url, headers=dict(request.headers), data=data) 22 | 23 | def lambda_handler(event, context): 24 | query = { 25 | "size": 25, 26 | "query": { 27 | "multi_match": { 28 | "query": event['queryStringParameters']['q'], 29 | "fields": ["title^4"] 30 | } 31 | } 32 | } 33 | 34 | headers = { "Content-Type": "application/json" } 35 | 36 | r = signed_request(method='GET', url=url, data=json.dumps(query), headers=headers) 37 | 38 | response = { 39 | "statusCode": 200, 40 | "headers": { 41 | "Access-Control-Allow-Origin": '*' 42 | }, 43 | "isBase64Encoded": False 44 | } 45 | 46 | response['body'] = r.text 47 | return response -------------------------------------------------------------------------------- /ec2/session_manager.drawio: -------------------------------------------------------------------------------- 1 | 7VjbkqM2EP0aP2YKcTH244DtZKsmVVOZh+w+TclGBmUBESFsM1+fFoiLEDNrV3lzqeyMXaaPWlKj7nMae+GE2eVnjovkVxaRdGFb0WXhbBa2jWzfhQ+J1C3io2ULxJxGymkAXugbUaCl0IpGpNQcBWOpoIUOHliek4PQMMw5O+tuR5bquxY4JgbwcsCpif5OI5G06Mr2B/wXQuOk2xkt1+1IhjtndSdlgiN2HkHOduGEnDHRXmWXkKTy8Lpzaeft3hntA+MkF9dMeKvst32ebx55EVtn8enPnH75CallSlF3d0wiOABlMi4SFrMcp9sBDTir8ojIZS2wBp8nxgoAEYB/ECFqlU1cCQZQIrJUjULEvP4s5z/05pfGdL3O3lzU+q1Vj61nwmlGBOEKbO9BBv7u2XT3ySp+IB8ciKNqDPOYiA/8vD6DUPqEQTS8hnmcpFjQkx4HVjUY935DmuBCZeqGrKkgTzit1E5GFsuvRBySLkWVSGlOwp4jEjzSNA1ZyngzwdntlsEyALwUnH0lo5HIX+8tOSPCZdKn/US4oMCTJ7wn6TMrqaAsh7E9E4JlI4fHlMZyQMjiCLCyDpAZmb9xWRxZLlTNILuz1S3JLXFZtOEf6UXGERSMylW2J1isVIsAzQo5IbvEUpEe8Ll0H6qy2UsdGwRGLh9XipnZboKr6Kz0zHaUfR7UYa2gZCQMHXb3WkBm7v8OBl+o+Dy6btnrKWvgrjTqkTFl7qAEug58SwbuyHjvSsb7/yTjvRsZ3zCjCcIL4AXFF7ZvD1xDiTzY3gw4h/kmiEw3+EBzO0zBOcw3QWS6SauLWgfnMN8zI57ORjOz0WQ2vH4c552Pc74fgdqPug787yRBApDxiBJtbOe47soejW0oh4XaBpRLOTP7WxAix1vO9bdj8/dv7G+zvYyTVtI+HWQ8AZjtle5V1qUgWfma4RweUe/U/Jwrmh+yZrpfD95dGH1DGJ85PWFBpDhW+xwkfSqUs2Q2iDwlsUFgnbwGMaakMAihU9Ng75Tihg7oUmGwdUppg/cfknFKupzlRC/mc0IFeSlw01vPUHhXFDjUqcCwF1drTJ/fWp80xUVJ9/0soHbFS2ixv5GyXdx6jxsxPNgUTfhznGhGX0u5HBX16+D80khCt/BUH5Drb4NHU1G2y529W31TCVJyFHJZOCqax0+NtXFmFK/fR9OhO9DWW+q0RWvPoK09S1v/e9F29eN55j/dgP3V1nJva8AbywuR/79pwORgX8veW75udJTWGe0ig9D+yuRzh92dzmuDztvQZDScgdATopeCajLjulGQkdRp7jMaRc0327m2pH/b/W4pWesia5siu5zRWOd2iQVz+NmwGRv9+Ops/wI= -------------------------------------------------------------------------------- /lambda/dynamodb/dynamo_streams.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import json 3 | from botocore.exceptions import ClientError 4 | def lambda_handler(event, context): 5 | data = [] 6 | TableName = "my_dynamodb_table" 7 | try: 8 | s3 = boto3.resource('s3', region_name='eu-west-2') 9 | ddbclient = boto3.client('dynamodb', region_name='eu-west-2') 10 | response = ddbclient.list_tables() 11 | mytables = response['TableNames'] 12 | 13 | if TableName in mytables: 14 | allitems = ddbclient.scan(TableName= TableName) 15 | for item in allitems['Items']: 16 | item_list = {} 17 | allKeys = item.keys() 18 | for k in allKeys: 19 | value = list(item[k].values())[0] 20 | item_list[k] = str(value) 21 | data.append(item_list) 22 | data = json.dumps(data) 23 | responses3 = s3.Object('my-s3-bucket098', 'data.json').put(Body=data) 24 | print("Completed Upload to S3") 25 | print("Lambda run completed") 26 | return { 27 | 'statusCode': 200, 28 | 'body': json.dumps("success") 29 | } 30 | except ClientError as e: 31 | print("Detailed error: ",e) 32 | return { 33 | 'statusCode': 500, 34 | 'body': json.dumps("error") 35 | } 36 | except Exception as e: 37 | print("Detailed error: ",e) 38 | return { 39 | 'statusCode': 500, 40 | 'body': json.dumps("error") 41 | } 42 | -------------------------------------------------------------------------------- /lambda/ec2/start_stop_ec2.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | 4 | region = 'eu-west-2' 5 | 6 | ec2 = boto3.client('ec2', region_name=region) 7 | 8 | def get_instance_ids(instance_names): 9 | 10 | all_instances = ec2.describe_instances() 11 | instance_ids = [] 12 | 13 | for instance_name in instance_names: 14 | for reservation in all_instances['Reservations']: 15 | for instance in reservation['Instances']: 16 | if 'Tags' in instance: 17 | for tag in instance['Tags']: 18 | if tag['Key'] == 'Name' \ 19 | and tag['Value'] == instance_name: 20 | instance_ids.append(instance['InstanceId']) 21 | 22 | return instance_ids 23 | 24 | def lambda_handler(event, context): 25 | instance_names = event["Instances"].split(',') 26 | action = event["action"] 27 | 28 | instance_ids = get_instance_ids(instance_names) 29 | 30 | response = '' 31 | if action == 'Start': 32 | print("STARTing your instances: " + str(instance_ids)) 33 | ec2.start_instances(InstanceIds=instance_ids) 34 | response = "Successfully started instances: " + str(instance_ids) 35 | elif action == 'Stop': 36 | print("STOPping your instances: " + str(instance_ids)) 37 | ec2.stop_instances(InstanceIds=instance_ids) 38 | response = "Successfully stopped instances: " + str(instance_ids) 39 | 40 | return { 41 | 'statusCode': 200, 42 | 'body': json.dumps(response) 43 | } -------------------------------------------------------------------------------- /lambda/s3_event_lambda_trigger/security_policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Sid": "VisualEditor0", 6 | "Effect": "Allow", 7 | "Action": [ 8 | "ec2:Describe*", 9 | "ec2:RunInstances", 10 | "ec2:StartInstances", 11 | "ec2:StopInstances", 12 | "cloudwatch:DescribeAlarms", 13 | "compute-optimizer:GetEnrollmentStatus", 14 | "elasticloadbalancing:Describe*" 15 | ], 16 | "Resource": "*", 17 | "Condition": { 18 | "StringEquals": { 19 | "ec2:Region": "us-east-1" 20 | } 21 | } 22 | }, 23 | { 24 | "Sid": "SESLimitedAccess", 25 | "Effect": "Allow", 26 | "Action": [ 27 | "ses:CreateCustomVerificationEmailTemplate", 28 | "ses:Describe*", 29 | "ses:Get*", 30 | "ses:List*", 31 | "ses:VerifyEmailAddress", 32 | "ses:VerifyEmailIdentity", 33 | "ses:CreateEmailIdentity", 34 | "ses:TagResource", 35 | "route53:List*", 36 | "ses:SendEmail", 37 | "ses:SendRawEmail", 38 | "ses:SendTemplatedEmail" 39 | ], 40 | "Resource": "*", 41 | "Condition": { 42 | "StringEquals": { 43 | "aws:RequestedRegion": "us-east-1" 44 | } 45 | } 46 | }, 47 | { 48 | "Effect": "Allow", 49 | "Action": ["logs:*"], 50 | "Resource": "arn:aws:logs:*:*:*" 51 | }, 52 | { 53 | "Effect": "Allow", 54 | "Action": ["s3:GetObject", "s3:PutObject"], 55 | "Resource": "arn:aws:s3:::*" 56 | } 57 | ] 58 | } 59 | -------------------------------------------------------------------------------- /ec2/cloud_watch_agent.drawio: -------------------------------------------------------------------------------- 1 | 7Vpbc5s4FP41fqwHENdHFzvbziQ7mc1Md7cvHRkU0BYQK+Tb/vqVQLIFwmk68aVp85Kgo6Pr931HR0omIC63v1FY53ckRcXEsdLtBMwnjmM7gct/CcuuswS23xkyilPpdDA84P+QNFrSusIpanqOjJCC4bpvTEhVoYT1bJBSsum7PZKiP2oNM2QYHhJYmNY/ccryzho6wcH+AeEsVyPbftTVlFA5y5U0OUzJRjOBxQTElBDWfZXbGBVi89S+dO1ujtTuJ0ZRxZ7T4PdPmMV3f9SLyl+sg+Xnz9t/372Ty2jYTi0YpXz9skgoy0lGKlgsDtb3lKyqFIleLV46+NwSUnOjzY3/IMZ2Eky4YoSbclYWshZtMftL+/5bdDX1Q1mcb2XXbWGnFe4RxSViiEpbN3kx46N7Ik0NWdEEPbERjuQWpBliT/h5e+Q45RHhs6E73o6iAjK87s8DSu5lez/ZdEYp3GkONcEVa7Se74WBOygZuZJDUkQAgD7U3/J3HN2ff3QzUCVtKQdTS5/voJLcwTUsVnIbDG6RFStwheK9VgWIKWzyPZvWiDLM1XcLl6i4Jw1mmFS8bkkYI6XmMCtwJiqY4Nx7KEsJx12wQ2cb110txi+3mQhRU7hpwHTVtG6PuChiUhDazg/MnTmYA27nninmfam6ilRozzcxBbR9mnEmQ1QDqw+NE8ny5hBdXK8z5Vpg8cFxTmm4fj9sKtD+CCHAu2YEAM+MANELI8CL0AKvSWQlrPjxWHL3L/x4bkhLnYHkbrzQA+5ZJRfZPcXZwFScUtdFFOcaGH66jw0Ym6+IJblS2BimR3ZMQ2WTY4YeatjyfsOBEftPKiZlaTuqLIe1xpF0pxkXfN0O+TFpqWLWflnXiWjOKPmKNIDDILIjfwC8nOrTPCvQIxM98vnjKrttS3NgyTmPDdFj+QmYs89CFXUskzqeZ5ncAcrx9OHaFPyvGa69Z4br8Jrh2ntN4RolzlXiMxiozPFNlQX+dCQpis4VosPXhFtSkFW6ge1pMYQv8KJYrPuM8PnDjHYEvtC5KHy2bcB1wSBpTV0tTNrXDJLRM4PkS2+1L0Irek1io6NZ7AVkNoySo2nsSCrihVPHO5fOzOsITw8fcbaiiJtjEZjEDNvYxMfPxFqH2PItYYONH+aQy9BzPWs8hzQQHAJd4jRtMRvLhvui13Nh28wzb2a+581OA6frDKJmYMK5f8bpp5bnAtO8l0wcvxDYpHjNPzPxyUXQvba21zlZz8fTXEZaKdOSDi3Dpm/kEJrdH5eKHfbV2WGmsh0V2pe0N9j08KteXa8vad8ArWlEJMYVT154jpGYR+2vCZ3tf/tZ9sLYBQZ2i/gNLnVaHrIapTYPXBsx89b4cXYn0uj2qHwDTmx+OMhiXXdqXx048wYyTF3FQDhp2tDJf4irx5JAmr7B2iUsgf3j6VEtQ9dj1TDYtjxyN+ng/UkCrfbU73gnOieDvn7dkcceNzgNyrx4+O+I7q/Uh/8xAYv/AQ== -------------------------------------------------------------------------------- /ecs/alb/alb-ecs-cluster.drawio: -------------------------------------------------------------------------------- 1 | 7Vlbb6s4EP41edwIMOTymEu7+9CVWkXVOftUueAk1jEYGefWX79jsAkY0nK6od2e3VSq7PFtPN/nmbEZoEV8/F3gdPsnjwgbeE50HKDlwPOm7hj+K8GpEIw8LdgIGhUi9yxY0ReihY6W7mhEslpHyTmTNK0LQ54kJJQ1GRaCH+rd1pzVV03xhjQEqxCzpvQbjeS2kE7MLpT8D0I3W7OyO5oWLTE2nfVOsi2O+KEiQjcDtBCcy6IUHxeEKdsZuxTjbi+0looJksguA8aH9OXxG7p7CB4eeDI7ofvH1W96lj1mO71hraw8GQvwnWQ0IYvSwM4AzSOcbUmkK3siJAWT3eFnwu55RiXlCbQ9cyl5XOkwY3SjGiRPQYp1LYQNEAGCrYwZ1F0ogrFStX583ChaDfEhQ8MYJ2DuGLo/AdwZVxrO15SxBWdc5Nqi22ASIB/kMC6i0NW0JTxR3fV+QSFyvGhIt4QHaE14TKQ4QRfDaQ2oZnRJ1UOFH1q0rVDDDMOakZty4jNoUNC4/QSG6CthiNOUwTRq9ifGcfT0jBlOwnzsx0OJkIXltImlOdBVLMdeT1j6XwlLEmafgloQoKHvvXkIDUhV4EbjYdATdMHb0GU/iAy3GqVWHNf8bDAwJvzdKhUuGdOy/dIP5s5YwSUF/0Gszn1zROmuA7jrmbrevFoSZ2mx0TU9Kj3mKadqlps9TJZdJpo/BG8vMdhKPHlXYtCofu591KRPMBlO/CaD0KQn/oxa+DNiUgFH91DcqOJjBlbXYlil0tLS2YiehS2xh9o81SDsYjYLpeLQe/lSoUc73y3ncTtxHOc6GLtOHWM0aWKMWuL0qK84PX7bQZAkmqmkVZ0whrOMhnUbCr5LovIMkyOV33WLKv+l5ENk/XTj8lgZtTxVKvdEUNihOs7Ls+1J1EiMLcuD5nwnQvI2pyUWGyJf6YfakayexhakjEwQBgnFvq5uG3x6hXvldypJgJXQ+Y7FgGKbelQ1w7Ym8n2LcYE1UWGHxkQ5m8ptv59gk48hWPCZjEIdGRX8EowKbB827sYowBifKt3ySJtdVti34qHJiy8y3Y6fQa0/FAoNrkrvaZcAebNYFa8BRcLQf6yEACWtXLmWfEFUmy/HRVSzot3awcjBlaxKFExsxNIyyB62VJJVivMjcoAEqXZkTRJWWcLJf0o/LuiLsorRso8sqiXCTl85ZVePsOYScEUPmIBe389uT1ULLzh1SsHZEea1U7XWoysMOrpC/5dwhZ8dXN3mU9ksxnCkQJY7nZ/0Cy03OC1q3LFsdxDTKMrfvl53B+Y+ae5gZgNXvnq74+apH7UQCvV26r0ugWF2fnjqHBTuOI46d56bh6xPDzlfk1r2Wxxqe4v7UF61Pcb9AxQbQ1MuZOfOMU5Tmmz+Z9f72NXIcFtylY9lV4f3wivlKp+cp5jPdv/NRwDP7+fKhkZBfZ0gsDjZwxXMbT5SLgTBkijFqwHWYXnodMqvO/9OL3MFx+JOLLy9pmNx225B7/AsUD1/Ly4wPX90Rzd/Aw== -------------------------------------------------------------------------------- /ecs-cli/codeBuildServiceRole.md: -------------------------------------------------------------------------------- 1 | # Follow below steps to create codeBuildServiceRole IAM role 2 | 3 | ## create a policy called codeBuildBatchPolicy and attach the following permissions to the codeBuildServiceRole IAM role 4 | 5 | ``` 6 | { 7 | "Version": "2012-10-17", 8 | "Statement": [ 9 | { 10 | "Effect": "Allow", 11 | "Resource": [ 12 | "arn:aws:codebuild:us-east-1::project/simplehttp-cb" 13 | ], 14 | "Action": [ 15 | "codebuild:StartBuild", 16 | "codebuild:StopBuild", 17 | "codebuild:RetryBuild" 18 | ] 19 | } 20 | ] 21 | } 22 | ``` 23 | 24 | ## create a policy called codeBuildServiceRolePolicy and attach the following permissions to the codeBuildServiceRole IAM role 25 | 26 | ``` 27 | { 28 | "Version": "2012-10-17", 29 | "Statement": [ 30 | { 31 | "Sid": "VisualEditor0", 32 | "Effect": "Allow", 33 | "Action": [ 34 | "ecr:GetDownloadUrlForLayer", 35 | "ecr:GetAuthorizationToken", 36 | "codecommit:GitPull", 37 | "s3:GetBucketAcl", 38 | "logs:CreateLogGroup", 39 | "logs:PutLogEvents", 40 | "s3:PutObject", 41 | "s3:GetObject", 42 | "logs:CreateLogStream", 43 | "ecr:BatchGetImage", 44 | "s3:GetBucketLocation", 45 | "s3:GetObjectVersion", 46 | "ecr:BatchCheckLayerAvailability" 47 | ], 48 | "Resource": "*" 49 | } 50 | ] 51 | } 52 | ``` 53 | 54 | ## finally attach a policy called AmazonEC2ContainerRegistryPowerUser to your codeBuildServiceRole IAM role -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/samplecode/java/src/test/java/com/example/javamavenjunithelloworld/HelloWithTestsIT.java: -------------------------------------------------------------------------------- 1 | package com.example.javamavenjunithelloworld; 2 | 3 | 4 | import org.junit.jupiter.api.AfterEach; 5 | import org.junit.jupiter.api.BeforeEach; 6 | import org.junit.jupiter.api.Test; 7 | 8 | import java.io.ByteArrayOutputStream; 9 | import java.io.PrintStream; 10 | 11 | import static org.hamcrest.CoreMatchers.is; 12 | import static org.hamcrest.MatcherAssert.assertThat; 13 | 14 | /** 15 | * Integration test for the HelloApp program. 16 | *

17 | * An integration test verifies the workings of a complete program, a module, or a set of dependant classes. 18 | */ 19 | public class HelloWithTestsIT { 20 | private final ByteArrayOutputStream out = new ByteArrayOutputStream(); 21 | private final PrintStream originalOut = System.out; 22 | 23 | @BeforeEach 24 | public void before() { 25 | // By putting our own PrintStream in the place of the normal System.out, 26 | // the output produced by the application can be verified. 27 | System.setOut(new PrintStream(out)); 28 | } 29 | 30 | @AfterEach 31 | public void cleanUp() { 32 | // Restore the original System.out to prevent weirdness in any following tests. 33 | System.setOut(originalOut); 34 | } 35 | 36 | @Test 37 | public void doesItSayHelloTest() { 38 | String[] args = {"1"}; 39 | HelloApp.main(args); 40 | 41 | assertThat(out.toString(), is(String.format("%s%s", Hello.HELLO, System.lineSeparator()))); 42 | } 43 | 44 | @Test 45 | public void doesItSayHelloTest3() { 46 | String[] args = {"3"}; 47 | HelloApp.main(args); 48 | 49 | // Hello 50 | // Hello 51 | // Hello 52 | String thrice = String.format("%1$s%2$s%1$s%2$s%1$s%2$s", Hello.HELLO, System.lineSeparator()); 53 | assertThat(out.toString(), is(thrice)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /dynamodb/s3/dynamodb_s3_put_ backup.js: -------------------------------------------------------------------------------- 1 | const AWS = require("aws-sdk"); 2 | const str = require("querystring"); 3 | 4 | const Client = new AWS.DynamoDB.DocumentClient({ region: "us-east-1" }); 5 | const s3 = new AWS.S3(); 6 | var filecontent = "["; 7 | var finalstr = ""; 8 | const bucketName = ""; 9 | const filePath = "backup_dynamodb_table.json"; 10 | 11 | exports.handler = (event, context, callback) => { 12 | var parameter = { 13 | TableName: "", 14 | Limit: 10, 15 | }; 16 | 17 | Client.scan(parameter, function (err, data) { 18 | if (err) callback(err, null); 19 | else { 20 | var count = Object.keys(data.Items); 21 | for (var i = count.length - 1; i >= 0; i--) { 22 | console.info("\nStudent ID: " + data.Items[i]["id"] + "\n"); 23 | console.info("\nStudent Name: " + data.Items[i]["name"] + "\n"); 24 | console.info("\nCourse: " + data.Items[i]["course"] + "\n"); 25 | 26 | filecontent += 27 | '{"student_id":"' + 28 | data.Items[i]["id"] + 29 | '","Name:"' + 30 | data.Items[i]["name"] + 31 | '"","Course:"' + 32 | data.Items[i]["course"] + 33 | '"}'; 34 | if (i != 0) { 35 | filecontent = filecontent + ","; 36 | } 37 | 38 | console.info("200 : success"); 39 | } 40 | filecontent = filecontent + "]"; 41 | putObjectToS3(bucketName, filePath, filecontent); 42 | 43 | callback(null, "200 : success"); 44 | } 45 | }); 46 | }; 47 | 48 | function putObjectToS3(bucket, key, data) { 49 | var s3 = new AWS.S3(); 50 | var params = { 51 | Bucket: bucket, 52 | Key: key, 53 | Body: data, 54 | }; 55 | s3.putObject(params, function (err, data) { 56 | if (err) { 57 | console.log(err, err.stack); // an error occurred 58 | } else { 59 | console.info("File" + key + "Created\n" + data); // successful response 60 | } 61 | }); 62 | } 63 | -------------------------------------------------------------------------------- /s3/encryption_kms/Untitled Diagram.drawio: -------------------------------------------------------------------------------- 1 | 7Vpdc6M2FP01fowHJGPwo03ibafJbKZum92+7Cggg9YCURCxnV9fCYQNCDvubLDdNkkm0b0Ifdyjc3SleADdaPMpRUn4wHxMB8DwNwN4OwDAhMZY/JGebemxISgdQUp8VWnvWJBXrJyG8ubEx1mjImeMcpI0nR6LY+zxhg+lKVs3qy0ZbfaaoABrjoWHqO59Ij4PS68D7L3/J0yCsOrZHE/KJxGqKquZZCHy2brmgncD6KaM8bIUbVxMZfCquJTvzQ883Q0sxTE/6YWnPxeb2H18+u0vz31Fq89BEN2oVl4QzdWE/3h01Xj5tgpCwkjMi0BaM/Ej+nGNgSWeuNIaAqvlaNt202Hqlmyj6WjbdtNhtps3W/2b7QHWHJrVaN5o9W/UBih+4IzlnJIYu7slZwhnkCKfCChcRlkqfDGLRfRmIY+osExRXIeE40WCPBnVtaCL8C1ZzNWiN0Flq8DLVsWy5kj0lao2CiRweveCS0DKOpSiJCPPu7dS7OVpRl7wrzgrG5desQATWY42geTqEK2z0TBIWZ4Uw/9Z9NX59NtL4snXecpWuJreAEAwchxzJAdNKG1N+wWnnAgWTSkJZKucyU6QsihectmiiAWJg/vCuoWGmn+ti+l0Zs8c4fdRFmJfTUStWdEF3hwkg7mjmNAmzCLM062oUr3gKFYqWTLHyl7vSW5B5QtrBAcOVOKihCXYtb3nnigo+v0DKtoa7bAvpEiZLOUhC1iM6N3eOxPwxP4uLvs690zGu1gx3zHnW7XEUM5Zc02WfcqODgfyiG5kLE89fKTeSEk2SgN8rD2rG60UU8TFOm7K+ntHvmr4vKFvLfX53DEM44ogMY1LYjLSNiYNo2yFuRdWAHRpcivE4nsuh3BIq+s6JqrDuTMGI035VOWGIlVyd4+eMX1kGeGkENNnxjmL3tRDD0tR15fHsZ0BZUk50SXZyHFoW4N5SPKfc28lkT9RRw+utYPiCpvaOtKl1R4PJ0AX10qU3301Of9FbbVOJPLokjy2PnjcF4/Z8/fizd54bNpNIu+OMvUkqSNHsvqisXmRjbpvHk/+DTmSqfP2fxT6y+ZCk7c1tFM2+5a2DlWCw1WU6RJsWxP3mGL3lomMW8e8SUcu0qFgdm8KZpywH6qwkqi4m3obOSofzJC3CgrCVbH18RLllB+Gtr3zFB1OK69ReUQ55Fzet03l5MF8jV7zcOiJvsE8TyhDfiZKwJDbw9wQMjUXK+HGoyz3eUoQvUlYxm+Ix+JhEgd9wg2tJtw62ibogHvnfH+8oYb3QriMz+Xe3YZexIO3ONaVs3RcuGg8bWMeEd8vRLnrGqop1GfLJ6COz8jS4YG9oaMr6+/FepabTuyl24RjWS4zray4exa/FvBKgTt+pdADoEZLXi0d0HEH33oDFOjyelfi2EAxz4jQIWD88rDYIy1FFRgrvP0At2Sn1WKrBTVwd2f786ALusVUXWh8wFbn2+Et8LyM1DfABxYTLuJR8Q95IoUWSQ2uU7PIHqTgygTiA9qmvB6+WDPH59w/wUhD5gyHQrwh/It6XZa/yvLQUtbtpvbodnsSVP0dMCv6XfkJ0xxfEkizASQ4jqQ0HnFKxMSL/4qeiuKJgIFT8bokXPo+qMF3PRcCEYrFITIS1b+JE2DGaMcV7dxyLDj60fuBo+LZ0s7dWaS+MUJdO8d9/bvXtC5CuViM/cteMKX5tf5sT7rC2tatHmkHT6QduCTt9FTmimmXZ0W1FtGWaOwUG5/2aQ7XhpbRsVUaxdc7cXDS4CDsSGC6zv/9cdDWEJ0+yZTUVUJ1nXnneyBhDltXZbbT10FBmPtPuRXPap8VhHd/Aw== -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/samplecode/java/src/test/java/com/example/javamavenjunithelloworld/HelloTest.java: -------------------------------------------------------------------------------- 1 | package com.example.javamavenjunithelloworld; 2 | 3 | 4 | import org.junit.jupiter.api.Disabled; 5 | import org.junit.jupiter.api.Test; 6 | 7 | import java.io.ByteArrayOutputStream; 8 | import java.io.OutputStream; 9 | import java.io.PrintStream; 10 | 11 | import static org.hamcrest.CoreMatchers.equalTo; 12 | import static org.hamcrest.CoreMatchers.is; 13 | import static org.hamcrest.MatcherAssert.assertThat; 14 | import static org.junit.jupiter.api.Assertions.assertThrows; 15 | 16 | 17 | /** 18 | * Unit test for Hello. 19 | *

20 | * A unit test aims to test all code and code paths of a specific class. 21 | */ 22 | public class HelloTest { 23 | 24 | @Test 25 | public void testSayHello() { 26 | OutputStream os = new ByteArrayOutputStream(); 27 | PrintStream stream = new PrintStream(os, true); 28 | 29 | Hello hi = new Hello(); 30 | hi.sayHello(stream); 31 | 32 | assertThat(os.toString(), is(equalTo(String.format("%s%s", Hello.HELLO, System.lineSeparator())))); 33 | } 34 | 35 | @Test 36 | public void testSayHelloAFewTimes() { 37 | OutputStream os = new ByteArrayOutputStream(); 38 | PrintStream stream = new PrintStream(os, true); 39 | 40 | Hello hi = new Hello(); 41 | hi.setTimes(3); 42 | hi.sayHello(stream); 43 | 44 | // Does it say "Hello!" three times? 45 | String goal = String.format("%1$s%2$s%1$s%2$s%1$s%2$s", Hello.HELLO, System.lineSeparator()); 46 | assertThat(os.toString(), is(equalTo(goal))); 47 | } 48 | 49 | @Test 50 | public void testIllegalArgumentForHelloTooMuch() { 51 | Hello hi = new Hello(); 52 | assertThrows(IllegalArgumentException.class, () -> hi.setTimes(Hello.MAXIMUM_AMOUNT_OF_TIMES + 1)); 53 | } 54 | 55 | @Test 56 | public void testIllegalArgumentForHelloNegative() { 57 | Hello hi = new Hello(); 58 | assertThrows(IllegalArgumentException.class, () -> hi.setTimes(-1)); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /step_functions/aws_step_functions.drawio.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | aws_step_functions 6 | 7 | 8 |

9 | 10 | 11 | -------------------------------------------------------------------------------- /serverless/backup_codecommit_repos/readme.md: -------------------------------------------------------------------------------- 1 | # Deploy 2 | 3 | ``` 4 | sam deploy --guided --capabilities CAPABILITY_NAMED_IAM 5 | ``` 6 | 7 | # Clean up 8 | 9 | ``` 10 | aws cloudformation delete-stack --stack-name STACK_NAME 11 | ``` 12 | 13 | ``` 14 | aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus" 15 | ``` 16 | 17 | # Explanation 18 | 19 | This CloudFormation template automates the process of backing up a CodeCommit repository to an S3 bucket using EventBridge and CodeBuild. Let's break down the key components: 20 | 21 | S3 Bucket for CodeCommit Backups 22 | 23 | Creates an S3 bucket to store CodeCommit backups. 24 | Utilizes BucketOwnerEnforced ownership controls. 25 | IAM Role for CodeBuild Project 26 | 27 | Establishes an IAM role for the CodeBuild project. 28 | Grants necessary permissions for CodeBuild, including CodeCommit interaction and S3 access. 29 | CodeBuild Project 30 | 31 | Defines a CodeBuild project to sync CodeCommit repositories to the specified S3 bucket. 32 | Uses a Linux container with specific environment variables like BUCKET and ACCOUNT. 33 | The source is set to an S3 location for the CodeCommit repository, and the build commands involve cloning, compressing, and uploading the repository to S3. 34 | Lambda Function (CreateBuildspec) 35 | 36 | Implements a Lambda function to dynamically create a buildspec.yml file in the backup bucket to run CodeBuild. 37 | Python script within the Lambda function generates the necessary build commands for CodeBuild. 38 | Custom Resource to Trigger Lambda (TriggerBuildspecCreation) 39 | 40 | A custom resource triggers the Lambda function at deployment time. 41 | IAM Role for CloudWatch Events 42 | 43 | Defines an IAM role for CloudWatch Events to trigger AWS CodeBuild builds. 44 | Grants permissions for CodeBuild execution. 45 | CloudWatch Events Rule 46 | 47 | Sets up an EventBridge (CloudWatch Events) rule to trigger the CodeBuild project when the content of a CodeCommit repository changes. 48 | The template effectively orchestrates the backup process by combining S3, CodeBuild, Lambda, and CloudWatch Events to automate repository backups to S3 -------------------------------------------------------------------------------- /ecs-cli/core-infrastructure/core-infrastructure-setup.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Description: VPC and subnets as base for an ECS cluster 3 | Parameters: 4 | EnvironmentName: 5 | Type: String 6 | Default: my-ecs-env 7 | 8 | Mappings: 9 | SubnetConfig: 10 | VPC: 11 | CIDR: '172.16.0.0/16' 12 | PublicOne: 13 | CIDR: '172.16.0.0/24' 14 | PublicTwo: 15 | CIDR: '172.16.1.0/24' 16 | 17 | Resources: 18 | VPC: 19 | Type: AWS::EC2::VPC 20 | Properties: 21 | EnableDnsSupport: true 22 | EnableDnsHostnames: true 23 | CidrBlock: !FindInMap ['SubnetConfig', 'VPC', 'CIDR'] 24 | 25 | PublicSubnetOne: 26 | Type: AWS::EC2::Subnet 27 | Properties: 28 | AvailabilityZone: 29 | Fn::Select: 30 | - 0 31 | - Fn::GetAZs: {Ref: 'AWS::Region'} 32 | VpcId: !Ref 'VPC' 33 | CidrBlock: !FindInMap ['SubnetConfig', 'PublicOne', 'CIDR'] 34 | MapPublicIpOnLaunch: true 35 | PublicSubnetTwo: 36 | Type: AWS::EC2::Subnet 37 | Properties: 38 | AvailabilityZone: 39 | Fn::Select: 40 | - 1 41 | - Fn::GetAZs: {Ref: 'AWS::Region'} 42 | VpcId: !Ref 'VPC' 43 | CidrBlock: !FindInMap ['SubnetConfig', 'PublicTwo', 'CIDR'] 44 | MapPublicIpOnLaunch: true 45 | 46 | InternetGateway: 47 | Type: AWS::EC2::InternetGateway 48 | GatewayAttachement: 49 | Type: AWS::EC2::VPCGatewayAttachment 50 | Properties: 51 | VpcId: !Ref 'VPC' 52 | InternetGatewayId: !Ref 'InternetGateway' 53 | PublicRouteTable: 54 | Type: AWS::EC2::RouteTable 55 | Properties: 56 | VpcId: !Ref 'VPC' 57 | PublicRoute: 58 | Type: AWS::EC2::Route 59 | DependsOn: GatewayAttachement 60 | Properties: 61 | RouteTableId: !Ref 'PublicRouteTable' 62 | DestinationCidrBlock: '0.0.0.0/0' 63 | GatewayId: !Ref 'InternetGateway' 64 | PublicSubnetOneRouteTableAssociation: 65 | Type: AWS::EC2::SubnetRouteTableAssociation 66 | Properties: 67 | SubnetId: !Ref PublicSubnetOne 68 | RouteTableId: !Ref PublicRouteTable 69 | PublicSubnetTwoRouteTableAssociation: 70 | Type: AWS::EC2::SubnetRouteTableAssociation 71 | Properties: 72 | SubnetId: !Ref PublicSubnetTwo 73 | RouteTableId: !Ref PublicRouteTable 74 | 75 | Outputs: 76 | VpcId: 77 | Description: The ID of the VPC that this stack is deployed in 78 | Value: !Ref 'VPC' 79 | Export: 80 | Name: !Sub ${EnvironmentName}:VpcId 81 | PublicSubnetOne: 82 | Description: Public subnet one 83 | Value: !Ref 'PublicSubnetOne' 84 | Export: 85 | Name: !Sub ${EnvironmentName}:PublicSubnetOne 86 | PublicSubnetTwo: 87 | Description: Public subnet two 88 | Value: !Ref 'PublicSubnetTwo' 89 | Export: 90 | Name: !Sub ${EnvironmentName}:PublicSubnetTwo 91 | 92 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/samplecode/java/src/test/java/com/example/javamavenjunithelloworld/HelloAppTest.java: -------------------------------------------------------------------------------- 1 | package com.example.javamavenjunithelloworld; 2 | 3 | import com.example.javamavenjunithelloworld.TestingSecurityManager.TestExitException; 4 | import org.junit.jupiter.api.AfterAll; 5 | import org.junit.jupiter.api.BeforeAll; 6 | import org.junit.jupiter.api.Test; 7 | import org.junit.jupiter.api.extension.ExtendWith; 8 | import org.mockito.junit.jupiter.MockitoExtension; 9 | 10 | import static org.hamcrest.CoreMatchers.is; 11 | import static org.hamcrest.MatcherAssert.assertThat; 12 | import static org.junit.jupiter.api.Assertions.fail; 13 | 14 | 15 | /** 16 | * Unit test for HelloApp. 17 | *

18 | * A unit test aims to test all code and code paths of a specific class. 19 | */ 20 | @ExtendWith(MockitoExtension.class) 21 | public class HelloAppTest { 22 | static SecurityManager originalSecurityManager; 23 | 24 | @BeforeAll 25 | public static void setup() { 26 | // Insert our own custom SecurityManager that throws an exception when System.exit() is called. 27 | originalSecurityManager = System.getSecurityManager(); 28 | System.setSecurityManager(new TestingSecurityManager()); 29 | } 30 | 31 | @AfterAll 32 | public static void tearDown() { 33 | // Reinsert the original SecurityManager now that we are done with these tests. 34 | System.setSecurityManager(originalSecurityManager); 35 | } 36 | 37 | @Test 38 | public void testMain() { 39 | String[] args = {"1"}; 40 | HelloApp.main(args); 41 | } 42 | 43 | @Test 44 | public void testBogusArgument() { 45 | String[] args = {"bicycle"}; 46 | 47 | try { 48 | HelloApp.main(args); 49 | // Our custom SecurityManager should have thrown an exception when HelloApp exited. 50 | // This means this line below cannot be reached. To make sure that our custom SecurityManager 51 | // works as expected, we fail the test if this line is ever reached: 52 | fail("Unreachable."); 53 | } catch (TestExitException e) { 54 | // Did the program exit with the expected error code? 55 | assertThat(e.getStatus(), is(HelloApp.EXIT_STATUS_PARAMETER_NOT_UNDERSTOOD)); 56 | } 57 | } 58 | 59 | @Test 60 | public void testTooHighArgument() { 61 | String[] args = {"999"}; 62 | 63 | try { 64 | HelloApp.main(args); 65 | fail("Unreachable."); 66 | } catch (TestExitException e) { 67 | // Did the program exit with the expected error code? 68 | assertThat(e.getStatus(), is(HelloApp.EXIT_STATUS_HELLO_FAILED)); 69 | } 70 | } 71 | 72 | @Test 73 | public void testDefaultArgument() { 74 | // Passing no arguments should work. 75 | String[] args = {}; 76 | HelloApp.main(args); 77 | } 78 | 79 | @Test 80 | public void classInstanceForCodeCoverageTest() { 81 | // Strictly speaking this test doesn't achieve anything, because HelloApp contains only a single static 82 | // method, but for purposes of full code coverage it is included. In general, 83 | // it is easier to aim for full code coverage and be done with it, than to remember why class X is stuck at 84 | // 95% code coverage. 85 | new HelloApp(); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /ec2/session_manager.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "ssm:DescribeAssociation", 8 | "ssm:GetDeployablePatchSnapshotForInstance", 9 | "ssm:GetDocument", 10 | "ssm:DescribeDocument", 11 | "ssm:GetManifest", 12 | "ssm:GetParameters", 13 | "ssm:ListAssociations", 14 | "ssm:ListInstanceAssociations", 15 | "ssm:PutInventory", 16 | "ssm:PutComplianceItems", 17 | "ssm:PutConfigurePackageResult", 18 | "ssm:UpdateAssociationStatus", 19 | "ssm:UpdateInstanceAssociationStatus", 20 | "ssm:UpdateInstanceInformation" 21 | ], 22 | "Resource": "*", 23 | "Condition": { 24 | "StringEquals": { 25 | "aws:RequestedRegion": "us-east-1" 26 | } 27 | } 28 | }, 29 | { 30 | "Effect": "Allow", 31 | "Action": [ 32 | "ssmmessages:CreateControlChannel", 33 | "ssmmessages:CreateDataChannel", 34 | "ssmmessages:OpenControlChannel", 35 | "ssmmessages:OpenDataChannel" 36 | ], 37 | "Resource": "*", 38 | "Condition": { 39 | "StringEquals": { 40 | "aws:RequestedRegion": "us-east-1" 41 | } 42 | } 43 | }, 44 | { 45 | "Effect": "Allow", 46 | "Action": [ 47 | "ec2messages:AcknowledgeMessage", 48 | "ec2messages:DeleteMessage", 49 | "ec2messages:FailMessage", 50 | "ec2messages:GetEndpoint", 51 | "ec2messages:GetMessages", 52 | "ec2messages:SendReply" 53 | ], 54 | "Resource": "*", 55 | "Condition": { 56 | "StringEquals": { 57 | "aws:RequestedRegion": "us-east-1" 58 | } 59 | } 60 | }, 61 | { 62 | "Effect": "Allow", 63 | "Action": ["cloudwatch:PutMetricData"], 64 | "Resource": "*", 65 | "Condition": { 66 | "StringEquals": { 67 | "aws:RequestedRegion": "us-east-1" 68 | } 69 | } 70 | }, 71 | { 72 | "Effect": "Allow", 73 | "Action": ["ec2:DescribeInstanceStatus"], 74 | "Resource": "*", 75 | "Condition": { 76 | "StringEquals": { 77 | "aws:RequestedRegion": "us-east-1" 78 | } 79 | } 80 | }, 81 | { 82 | "Effect": "Allow", 83 | "Action": ["ds:CreateComputer", "ds:DescribeDirectories"], 84 | "Resource": "*", 85 | "Condition": { 86 | "StringEquals": { 87 | "aws:RequestedRegion": "us-east-1" 88 | } 89 | } 90 | }, 91 | { 92 | "Effect": "Allow", 93 | "Action": [ 94 | "logs:CreateLogGroup", 95 | "logs:CreateLogStream", 96 | "logs:DescribeLogGroups", 97 | "logs:DescribeLogStreams", 98 | "logs:PutLogEvents" 99 | ], 100 | "Resource": "*", 101 | "Condition": { 102 | "StringEquals": { 103 | "aws:RequestedRegion": "us-east-1" 104 | } 105 | } 106 | }, 107 | { 108 | "Effect": "Allow", 109 | "Action": [ 110 | "s3:GetBucketLocation", 111 | "s3:PutObject", 112 | "s3:GetObject", 113 | "s3:GetEncryptionConfiguration", 114 | "s3:AbortMultipartUpload", 115 | "s3:ListMultipartUploadParts", 116 | "s3:ListBucket", 117 | "s3:ListBucketMultipartUploads" 118 | ], 119 | "Resource": "*", 120 | "Condition": { 121 | "StringEquals": { 122 | "aws:RequestedRegion": "us-east-1" 123 | } 124 | } 125 | } 126 | ] 127 | } 128 | -------------------------------------------------------------------------------- /ecs-cli/cloudformation/ecs-ec2-with-cf.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Description: ECS cluster launchtype EC2. 3 | Parameters: 4 | EnvironmentName: 5 | Type: String 6 | Default: my-ecs-env 7 | Description: "A name that will be used for namespacing all cluster resources." 8 | InstanceType: 9 | Description: EC2 instance type 10 | Type: String 11 | Default: t2.small 12 | Description: Class of EC2 instance used to host containers. Choose t2 for testing, m5 for general purpose, c5 for CPU intensive services, and r5 for memory intensive services 13 | AllowedValues: [ t2.micro, t2.small, t2.medium, t2.large, t2.xlarge, t2.2xlarge, 14 | m5.large, m5.xlarge, m5.2large, m5.4xlarge, m5.12xlarge, m5.24large, 15 | c5.large, c5.xlarge, c5.2xlarge, c5.4xlarge, c5.9xlarge, c5.18xlarge, 16 | r5.large, r5.xlarge, r5.2xlarge, r5.4xlarge, r5.12xlarge, r5.24xlarge ] 17 | ConstraintDescription: Please choose a valid instance type. 18 | DesiredCapacity: 19 | Type: Number 20 | Default: '1' 21 | Description: Number of EC2 instances to launch in your ECS cluster. 22 | MaxSize: 23 | Type: Number 24 | Default: '6' 25 | Description: Maximum number of EC2 instances that can be launched in your ECS cluster. 26 | ECSAMI: 27 | Description: AMI ID 28 | Type: AWS::SSM::Parameter::Value 29 | Default: /aws/service/ecs/optimized-ami/amazon-linux-2/recommended/image_id 30 | Description: The Amazon Machine Image ID used for the cluster, leave it as the default value to get the latest AMI 31 | 32 | Resources: 33 | 34 | # ECS Resources 35 | ECSCluster: 36 | Type: AWS::ECS::Cluster 37 | Properties: 38 | ClusterName: !Sub ${EnvironmentName}-ec2 39 | 40 | # A security group for the EC2 hosts that will run the containers. 41 | # Rules are added based on what ingress you choose to add to the cluster. 42 | ContainerSecurityGroup: 43 | Type: AWS::EC2::SecurityGroup 44 | Properties: 45 | GroupDescription: Access to the ECS hosts that run containers 46 | VpcId: 47 | Fn::ImportValue: !Sub ${EnvironmentName}:VpcId 48 | 49 | # Autoscaling group. This launches the actual EC2 instances that will register 50 | # themselves as members of the cluster, and run the docker containers. 51 | ECSAutoScalingGroup: 52 | Type: AWS::AutoScaling::AutoScalingGroup 53 | Properties: 54 | VPCZoneIdentifier: 55 | - Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetOne 56 | - Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetTwo 57 | LaunchConfigurationName: !Ref 'ContainerInstances' 58 | MinSize: '1' 59 | MaxSize: !Ref 'MaxSize' 60 | DesiredCapacity: !Ref 'DesiredCapacity' 61 | CreationPolicy: 62 | ResourceSignal: 63 | Timeout: PT15M 64 | UpdatePolicy: 65 | AutoScalingReplacingUpdate: 66 | WillReplace: 'true' 67 | ContainerInstances: 68 | Type: AWS::AutoScaling::LaunchConfiguration 69 | Properties: 70 | ImageId: !Ref 'ECSAMI' 71 | SecurityGroups: [!Ref 'ContainerSecurityGroup'] 72 | InstanceType: !Ref 'InstanceType' 73 | IamInstanceProfile: !Ref 'EC2InstanceProfile' 74 | UserData: 75 | Fn::Base64: !Sub | 76 | #!/bin/bash -xe 77 | echo ECS_CLUSTER=${ECSCluster} >> /etc/ecs/ecs.config 78 | yum install -y aws-cfn-bootstrap 79 | /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource ECSAutoScalingGroup --region ${AWS::Region} 80 | EC2InstanceProfile: 81 | Type: AWS::IAM::InstanceProfile 82 | Properties: 83 | Path: / 84 | Roles: [ 'ecsInstanceRole' ] 85 | 86 | 87 | 88 | Outputs: 89 | ClusterName: 90 | Description: The name of the ECS cluster 91 | Value: !Ref 'ECSCluster' 92 | Export: 93 | Name: !Sub ${EnvironmentName}:ClusterName 94 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/pipelinecreation_stack.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: Creation of codecommit repository, Codebuild Project and CodePipeline 3 | Parameters: 4 | ProjectName: 5 | Description: The name of the project for which pipelines are to be created by the master pipeline. 6 | Type: String 7 | TechStack: 8 | Description: The technology stack of the project for which pipelines are to be created by the master pipeline. e.g. java, cloudformation 9 | Type: String 10 | AllowedValues: 11 | - java 12 | - cloudformation 13 | - python 14 | - terraform 15 | Resources: 16 | CodeRepository: 17 | Type: 'AWS::CodeCommit::Repository' 18 | Properties: 19 | RepositoryName: !Join 20 | - '-' 21 | - - !Ref 'ProjectName' 22 | - 'Repo' 23 | RepositoryDescription: !Join 24 | - '' 25 | - - 'Code repository for the Project ' 26 | - !Ref 'AWS::StackName' 27 | Code: 28 | BranchName: main 29 | S3: 30 | Bucket: '{{resolve:ssm:S3TemplateBucketName}}' 31 | Key: !Join 32 | - '' 33 | - - 'generated-artifacts' 34 | - '/' 35 | - !Ref 'TechStack' 36 | - '/' 37 | - !Ref 'ProjectName' 38 | - '/' 39 | - !Ref 'TechStack' 40 | - '-templates.zip' 41 | 42 | DeployResources: 43 | Type: AWS::CodeBuild::Project 44 | Properties: 45 | Name: !Join 46 | - '-' 47 | - - !Ref 'ProjectName' 48 | - 'Build' 49 | ServiceRole: '{{resolve:ssm:CodeBuildRoleARN}}' 50 | EncryptionKey: !Sub 'arn:aws:kms:${AWS::Region}:${AWS::AccountId}:alias/aws/s3' 51 | Artifacts: 52 | Type: CODEPIPELINE 53 | Environment: 54 | ComputeType: BUILD_GENERAL1_SMALL 55 | Image: aws/codebuild/amazonlinux2-x86_64-standard:3.0 56 | Type: LINUX_CONTAINER 57 | EnvironmentVariables: 58 | - Name: BUILD_ARTIFACT_BUCKET 59 | Value: '{{resolve:ssm:DeploymentArtifactBucketName}}' 60 | - Name: TECH_STACK 61 | Value: !Ref TechStack 62 | Source: 63 | Type: CODEPIPELINE 64 | BuildSpec: buildspec.yml 65 | DependsOn: CodeRepository 66 | 67 | CodePipeline: 68 | Type: AWS::CodePipeline::Pipeline 69 | Properties: 70 | Name: !Join 71 | - '-' 72 | - - !Ref 'ProjectName' 73 | - 'Pipeline' 74 | RoleArn: '{{resolve:ssm:CodePipelineServiceRoleARN}}' 75 | ArtifactStore: 76 | Type: S3 77 | Location: '{{resolve:ssm:DeploymentArtifactBucketName}}' 78 | Stages: 79 | - Name: CodeCheckout 80 | Actions: 81 | - InputArtifacts: [] 82 | Name: code 83 | RunOrder: 1 84 | ActionTypeId: 85 | Category: Source 86 | Owner: AWS 87 | Version: 1 88 | Provider: CodeCommit 89 | OutputArtifacts: 90 | - Name: SourceCodeOutputArtifact 91 | Configuration: 92 | RepositoryName: !Join 93 | - '-' 94 | - - !Ref 'ProjectName' 95 | - 'Repo' 96 | BranchName: main 97 | PollForSourceChanges: "true" 98 | - Name: Build 99 | Actions: 100 | - Name: ResourceBuild 101 | ActionTypeId: 102 | Category: Build 103 | Owner: AWS 104 | Version: 1 105 | Provider: CodeBuild 106 | InputArtifacts: 107 | - Name: SourceCodeOutputArtifact 108 | OutputArtifacts: [] 109 | Configuration: 110 | ProjectName: !Ref DeployResources 111 | RunOrder: 2 112 | 113 | -------------------------------------------------------------------------------- /step_functions/aws_step_functions.drawio: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /ec2/aws_inspector.drawio: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /s3/encryption_kms/s3_bucket_encryption_kms.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Sid": "VisualEditor0", 6 | "Effect": "Allow", 7 | "Action": [ 8 | "cloudtrail:List*", 9 | "cloudtrail:PutInsightSelectors", 10 | "cloudtrail:PutEventSelectors", 11 | "cloudtrail:StopLogging", 12 | "cloudtrail:StartLogging", 13 | "cloudtrail:AddTags", 14 | "cloudtrail:UpdateTrail", 15 | "cloudtrail:CreateTrail", 16 | "cloudtrail:Describe*", 17 | "cloudtrail:Get*" 18 | ], 19 | "Resource": "*", 20 | "Condition": { 21 | "ForAllValues:StringEquals": { 22 | "aws:RequestedRegion": "us-east-1" 23 | } 24 | } 25 | }, 26 | { 27 | "Sid": "VisualEditor1", 28 | "Effect": "Allow", 29 | "Action": [ 30 | "cloudwatch:List*", 31 | "cloudwatch:Get*", 32 | "cloudwatch:Describe*" 33 | ], 34 | "Resource": "*", 35 | "Condition": { 36 | "ForAllValues:StringEquals": { 37 | "aws:RequestedRegion": "us-east-1" 38 | } 39 | } 40 | }, 41 | { 42 | "Sid": "VisualEditor2", 43 | "Effect": "Allow", 44 | "Action": [ 45 | "config:Get*", 46 | "config:List*", 47 | "config:Describe*" 48 | ], 49 | "Resource": "*", 50 | "Condition": { 51 | "StringEquals": { 52 | "aws:RequestedRegion": "us-east-1" 53 | } 54 | } 55 | }, 56 | { 57 | "Sid": "VisualEditor3", 58 | "Effect": "Allow", 59 | "Action": [ 60 | "iam:Get*", 61 | "iam:List*", 62 | "iam:AttachRolePolicy" 63 | ], 64 | "Resource": "*", 65 | "Condition": { 66 | "StringEquals": { 67 | "aws:RequestedRegion": "us-east-1" 68 | } 69 | } 70 | }, 71 | { 72 | "Sid": "VisualEditor4", 73 | "Effect": "Allow", 74 | "Action": [ 75 | "kms:EnableKeyRotation", 76 | "kms:EnableKey", 77 | "kms:Decrypt", 78 | "kms:TagResource", 79 | "kms:UntagResource", 80 | "kms:List*", 81 | "kms:Encrypt", 82 | "kms:Get*", 83 | "kms:CreateAlias", 84 | "kms:Describe*", 85 | "kms:CreateKey", 86 | "kms:DisableKey" 87 | ], 88 | "Resource": "*", 89 | "Condition": { 90 | "StringEquals": { 91 | "aws:RequestedRegion": "us-east-1" 92 | } 93 | } 94 | }, 95 | { 96 | "Sid": "VisualEditor5", 97 | "Effect": "Allow", 98 | "Action": [ 99 | "organizations:Describe*", 100 | "organizations:List*" 101 | ], 102 | "Resource": "*", 103 | "Condition": { 104 | "StringEquals": { 105 | "aws:RequestedRegion": "us-east-1" 106 | } 107 | } 108 | }, 109 | { 110 | "Sid": "VisualEditor6", 111 | "Effect": "Allow", 112 | "Action": [ 113 | "s3:PutAccountPublicAccessBlock", 114 | "s3:PutBucketPublicAccessBlock", 115 | "s3:PutBucketOwnershipControls", 116 | "s3:Get*", 117 | "s3:CreateBucket", 118 | "s3:List*", 119 | "s3:PutObject", 120 | "s3:PutObjectVersionAcl", 121 | "s3:PutBucketAcl", 122 | "s3:PutBucketPolicy", 123 | "s3:PutAccessPointPolicy", 124 | "s3:PutBucketVersioning", 125 | "s3:PutObjectAcl", 126 | "iam:PassRole", 127 | "iam:CreateServiceLinkedRole" 128 | ], 129 | "Resource": "*" 130 | }, 131 | { 132 | "Sid": "VisualEditor7", 133 | "Effect": "Allow", 134 | "Action": "tag:Get*", 135 | "Resource": "*", 136 | "Condition": { 137 | "StringEquals": { 138 | "aws:RequestedRegion": "us-east-1" 139 | } 140 | } 141 | }, 142 | { 143 | "Sid": "VisualEditor8", 144 | "Effect": "Deny", 145 | "Action": "s3:*", 146 | "Resource": "*", 147 | "Condition": { 148 | "ForAllValues:StringNotEqualsIfExists": { 149 | "aws:RequestedRegion": "us-east-1" 150 | } 151 | } 152 | } 153 | ] 154 | } -------------------------------------------------------------------------------- /ec2/ec2-user-data.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | sudo yum update -y 3 | sudo yum install -y httpd 4 | sudo yum install -y git 5 | export META_INST_ID=`curl http://169.254.169.254/latest/meta-data/instance-id` 6 | export META_INST_TYPE=`curl http://169.254.169.254/latest/meta-data/instance-type` 7 | export META_INST_AZ=`curl http://169.254.169.254/latest/meta-data/placement/availability-zone` 8 | cd /var/www/html 9 | echo "" >> index.html 10 | echo "" >> index.html 11 | echo "" >> index.html 12 | echo " " >> index.html 13 | echo " " >> index.html 14 | echo " " >> index.html 75 | echo " Amazon EC2 Status" >> index.html 76 | echo "" >> index.html 77 | echo "" >> index.html 78 | echo "

" >> index.html 79 | echo "
" >> index.html 80 | echo "
" >> index.html 81 | echo "
Your EC2 Instance is running!
" >> index.html 82 | echo "
" >> index.html 83 | echo "
" >> index.html 84 | echo "
Instance Id
" >> index.html 85 | echo "
" $META_INST_ID "
" >> index.html 86 | echo "
" >> index.html 87 | echo "
" >> index.html 88 | echo "
Instance Type
" >> index.html 89 | echo "
" $META_INST_TYPE "
" >> index.html 90 | echo "
" >> index.html 91 | echo "
" >> index.html 92 | echo "
Availability zone
" >> index.html 93 | echo "
" $META_INST_AZ "
" >> index.html 94 | echo "
" >> index.html 95 | echo "
" >> index.html 96 | echo "
" >> index.html 97 | echo "
" >> index.html 98 | echo "" >> index.html 99 | echo "" >> index.html 100 | sudo service httpd start -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/samplecode/java/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 4.0.0 7 | 8 | com.example 9 | java-maven-junit-helloworld 10 | 2.0-SNAPSHOT 11 | jar 12 | 13 | 14 | UTF-8 15 | UTF-8 16 | 17 | 18 | 19 | 1.8 20 | ${maven.compiler.source} 21 | 22 | 5.2.0 23 | 1.2.0 24 | 1.3 25 | 2.21.0 26 | 0.8.1 27 | 28 | 29 | 30 | 31 | 32 | org.junit.jupiter 33 | junit-jupiter-api 34 | ${junit.jupiter.version} 35 | test 36 | 37 | 38 | org.junit.jupiter 39 | junit-jupiter-params 40 | ${junit.jupiter.version} 41 | test 42 | 43 | 44 | org.junit.jupiter 45 | junit-jupiter-engine 46 | ${junit.jupiter.version} 47 | test 48 | 49 | 50 | org.hamcrest 51 | hamcrest-core 52 | ${hamcrest.version} 53 | 54 | 55 | org.mockito 56 | mockito-junit-jupiter 57 | ${mockito.version} 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | org.apache.maven.plugins 67 | maven-compiler-plugin 68 | 3.8.0 69 | 70 | 71 | -Xlint 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | org.apache.maven.plugins 81 | maven-surefire-plugin 82 | 2.22.0 83 | 84 | 85 | 86 | 87 | 88 | org.apache.maven.plugins 89 | maven-failsafe-plugin 90 | 2.22.0 91 | 92 | 93 | 94 | integration-test 95 | verify 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | org.jacoco 107 | jacoco-maven-plugin 108 | ${jacoco.plugin.version} 109 | 110 | 111 | jacoco-prepare-agent 112 | 113 | prepare-agent 114 | 115 | 116 | 117 | jacoco-prepare-agent-integration 118 | 119 | prepare-agent-integration 120 | 121 | 122 | 123 | jacoco-report 124 | 125 | report 126 | 127 | 128 | 129 | jacoco-check 130 | 131 | check 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | jacoco-merge 140 | 141 | merge 142 | 143 | verify 144 | 145 | 146 | 147 | ${project.build.directory} 148 | 149 | *.exec 150 | 151 | 152 | 153 | ${project.build.directory}/jacoco-both.exec 154 | 155 | 156 | 157 | jacoco-integration 158 | 159 | report-integration 160 | 161 | 162 | 163 | jacoco-reportboth 164 | 165 | report 166 | 167 | 168 | ${project.build.directory}/jacoco-both.exec 169 | ${project.reporting.outputDirectory}/jacoco-both 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | -------------------------------------------------------------------------------- /serverless/backup_codecommit_repos/backups_from_codecommit_to_s3.drawio: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /lambda/s3_event_lambda_trigger/Untitled Diagram.drawio: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /vpc/cloudformation/vpc.yaml: -------------------------------------------------------------------------------- 1 | Description: 2 | This template deploys a VPC, with a pair of public and private subnets spread 3 | across two Availability Zones. It deploys an internet gateway, with a default 4 | route on the public subnets. It deploys a pair of NAT gateways (one in each AZ), 5 | and default routes for them in the private subnets. 6 | 7 | Parameters: 8 | EnvironmentName: 9 | Description: An environment name that is prefixed to resource names 10 | Type: String 11 | 12 | VpcCIDR: 13 | Description: Please enter the IP range (CIDR notation) for this VPC 14 | Type: String 15 | Default: 10.192.0.0/16 16 | 17 | PublicSubnet1CIDR: 18 | Description: Please enter the IP range (CIDR notation) for the public subnet in the first Availability Zone 19 | Type: String 20 | Default: 10.192.10.0/24 21 | 22 | PublicSubnet2CIDR: 23 | Description: Please enter the IP range (CIDR notation) for the public subnet in the second Availability Zone 24 | Type: String 25 | Default: 10.192.11.0/24 26 | 27 | PrivateSubnet1CIDR: 28 | Description: Please enter the IP range (CIDR notation) for the private subnet in the first Availability Zone 29 | Type: String 30 | Default: 10.192.20.0/24 31 | 32 | PrivateSubnet2CIDR: 33 | Description: Please enter the IP range (CIDR notation) for the private subnet in the second Availability Zone 34 | Type: String 35 | Default: 10.192.21.0/24 36 | 37 | Resources: 38 | VPC: 39 | Type: AWS::EC2::VPC 40 | Properties: 41 | CidrBlock: !Ref VpcCIDR 42 | EnableDnsSupport: true 43 | EnableDnsHostnames: true 44 | Tags: 45 | - Key: Name 46 | Value: !Ref EnvironmentName 47 | 48 | InternetGateway: 49 | Type: AWS::EC2::InternetGateway 50 | Properties: 51 | Tags: 52 | - Key: Name 53 | Value: !Ref EnvironmentName 54 | 55 | InternetGatewayAttachment: 56 | Type: AWS::EC2::VPCGatewayAttachment 57 | Properties: 58 | InternetGatewayId: !Ref InternetGateway 59 | VpcId: !Ref VPC 60 | 61 | PublicSubnet1: 62 | Type: AWS::EC2::Subnet 63 | Properties: 64 | VpcId: !Ref VPC 65 | AvailabilityZone: !Select [0, !GetAZs ''] 66 | CidrBlock: !Ref PublicSubnet1CIDR 67 | MapPublicIpOnLaunch: true 68 | Tags: 69 | - Key: Name 70 | Value: !Sub ${EnvironmentName} Public Subnet (AZ1) 71 | 72 | PublicSubnet2: 73 | Type: AWS::EC2::Subnet 74 | Properties: 75 | VpcId: !Ref VPC 76 | AvailabilityZone: !Select [1, !GetAZs ''] 77 | CidrBlock: !Ref PublicSubnet2CIDR 78 | MapPublicIpOnLaunch: true 79 | Tags: 80 | - Key: Name 81 | Value: !Sub ${EnvironmentName} Public Subnet (AZ2) 82 | 83 | PrivateSubnet1: 84 | Type: AWS::EC2::Subnet 85 | Properties: 86 | VpcId: !Ref VPC 87 | AvailabilityZone: !Select [0, !GetAZs ''] 88 | CidrBlock: !Ref PrivateSubnet1CIDR 89 | MapPublicIpOnLaunch: false 90 | Tags: 91 | - Key: Name 92 | Value: !Sub ${EnvironmentName} Private Subnet (AZ1) 93 | 94 | PrivateSubnet2: 95 | Type: AWS::EC2::Subnet 96 | Properties: 97 | VpcId: !Ref VPC 98 | AvailabilityZone: !Select [1, !GetAZs ''] 99 | CidrBlock: !Ref PrivateSubnet2CIDR 100 | MapPublicIpOnLaunch: false 101 | Tags: 102 | - Key: Name 103 | Value: !Sub ${EnvironmentName} Private Subnet (AZ2) 104 | 105 | NatGateway1EIP: 106 | Type: AWS::EC2::EIP 107 | DependsOn: InternetGatewayAttachment 108 | Properties: 109 | Domain: vpc 110 | 111 | NatGateway2EIP: 112 | Type: AWS::EC2::EIP 113 | DependsOn: InternetGatewayAttachment 114 | Properties: 115 | Domain: vpc 116 | 117 | NatGateway1: 118 | Type: AWS::EC2::NatGateway 119 | Properties: 120 | AllocationId: !GetAtt NatGateway1EIP.AllocationId 121 | SubnetId: !Ref PublicSubnet1 122 | 123 | NatGateway2: 124 | Type: AWS::EC2::NatGateway 125 | Properties: 126 | AllocationId: !GetAtt NatGateway2EIP.AllocationId 127 | SubnetId: !Ref PublicSubnet2 128 | 129 | PublicRouteTable: 130 | Type: AWS::EC2::RouteTable 131 | Properties: 132 | VpcId: !Ref VPC 133 | Tags: 134 | - Key: Name 135 | Value: !Sub ${EnvironmentName} Public Routes 136 | 137 | DefaultPublicRoute: 138 | Type: AWS::EC2::Route 139 | DependsOn: InternetGatewayAttachment 140 | Properties: 141 | RouteTableId: !Ref PublicRouteTable 142 | DestinationCidrBlock: 0.0.0.0/0 143 | GatewayId: !Ref InternetGateway 144 | 145 | PublicSubnet1RouteTableAssociation: 146 | Type: AWS::EC2::SubnetRouteTableAssociation 147 | Properties: 148 | RouteTableId: !Ref PublicRouteTable 149 | SubnetId: !Ref PublicSubnet1 150 | 151 | PublicSubnet2RouteTableAssociation: 152 | Type: AWS::EC2::SubnetRouteTableAssociation 153 | Properties: 154 | RouteTableId: !Ref PublicRouteTable 155 | SubnetId: !Ref PublicSubnet2 156 | 157 | PrivateRouteTable1: 158 | Type: AWS::EC2::RouteTable 159 | Properties: 160 | VpcId: !Ref VPC 161 | Tags: 162 | - Key: Name 163 | Value: !Sub ${EnvironmentName} Private Routes (AZ1) 164 | 165 | DefaultPrivateRoute1: 166 | Type: AWS::EC2::Route 167 | Properties: 168 | RouteTableId: !Ref PrivateRouteTable1 169 | DestinationCidrBlock: 0.0.0.0/0 170 | NatGatewayId: !Ref NatGateway1 171 | 172 | PrivateSubnet1RouteTableAssociation: 173 | Type: AWS::EC2::SubnetRouteTableAssociation 174 | Properties: 175 | RouteTableId: !Ref PrivateRouteTable1 176 | SubnetId: !Ref PrivateSubnet1 177 | 178 | PrivateRouteTable2: 179 | Type: AWS::EC2::RouteTable 180 | Properties: 181 | VpcId: !Ref VPC 182 | Tags: 183 | - Key: Name 184 | Value: !Sub ${EnvironmentName} Private Routes (AZ2) 185 | 186 | DefaultPrivateRoute2: 187 | Type: AWS::EC2::Route 188 | Properties: 189 | RouteTableId: !Ref PrivateRouteTable2 190 | DestinationCidrBlock: 0.0.0.0/0 191 | NatGatewayId: !Ref NatGateway2 192 | 193 | PrivateSubnet2RouteTableAssociation: 194 | Type: AWS::EC2::SubnetRouteTableAssociation 195 | Properties: 196 | RouteTableId: !Ref PrivateRouteTable2 197 | SubnetId: !Ref PrivateSubnet2 198 | 199 | NoIngressSecurityGroup: 200 | Type: AWS::EC2::SecurityGroup 201 | Properties: 202 | GroupName: 'no-ingress-sg' 203 | GroupDescription: 'Security group with no ingress rule' 204 | VpcId: !Ref VPC 205 | 206 | Outputs: 207 | VPC: 208 | Description: A reference to the created VPC 209 | Value: !Ref VPC 210 | 211 | PublicSubnets: 212 | Description: A list of the public subnets 213 | Value: !Join [',', [!Ref PublicSubnet1, !Ref PublicSubnet2]] 214 | 215 | PrivateSubnets: 216 | Description: A list of the private subnets 217 | Value: !Join [',', [!Ref PrivateSubnet1, !Ref PrivateSubnet2]] 218 | 219 | PublicSubnet1: 220 | Description: A reference to the public subnet in the 1st Availability Zone 221 | Value: !Ref PublicSubnet1 222 | 223 | PublicSubnet2: 224 | Description: A reference to the public subnet in the 2nd Availability Zone 225 | Value: !Ref PublicSubnet2 226 | 227 | PrivateSubnet1: 228 | Description: A reference to the private subnet in the 1st Availability Zone 229 | Value: !Ref PrivateSubnet1 230 | 231 | PrivateSubnet2: 232 | Description: A reference to the private subnet in the 2nd Availability Zone 233 | Value: !Ref PrivateSubnet2 234 | 235 | NoIngressSecurityGroup: 236 | Description: Security group with no ingress rule 237 | Value: !Ref NoIngressSecurityGroup 238 | -------------------------------------------------------------------------------- /serverless/backup_codecommit_repos/template.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: "2010-09-09" 2 | Transform: AWS::Serverless-2016-10-31 3 | Description: Backup CodeCommit to S3 using EventBridge and CodeBuild 4 | 5 | Resources: 6 | 7 | # Bucket that will store the CodeCommit backups 8 | CodeCommitBackupBucket: 9 | Type: 'AWS::S3::Bucket' 10 | Description: Bucket to store CodeCommit code 11 | Properties: 12 | OwnershipControls: 13 | Rules: 14 | - ObjectOwnership: BucketOwnerEnforced 15 | 16 | # Role with permisions for the CodeBuild project 17 | CodeBuildRole: 18 | Type: AWS::IAM::Role 19 | Properties: 20 | AssumeRolePolicyDocument: 21 | Version: 2012-10-17 22 | Statement: 23 | - Effect: Allow 24 | Principal: 25 | Service: 26 | - codebuild.amazonaws.com 27 | Action: 28 | - sts:AssumeRole 29 | Description: !Sub "IAM Role for ${AWS::StackName}" 30 | Path: '/' 31 | Policies: 32 | - PolicyName: root 33 | PolicyDocument: 34 | Version: '2012-10-17' 35 | Statement: 36 | - Action: 37 | - logs:CreateLogGroup 38 | - logs:CreateLogStream 39 | - logs:PutLogEvents 40 | - codecommit:GitPull 41 | - s3:Get* 42 | - s3:List* 43 | - s3:PutObject 44 | Effect: Allow 45 | Resource: '*' 46 | 47 | # Project that clones the CodeCommit repository, compress the files in a .zip and uploads to S3 48 | CodeBuildProject: 49 | Type: AWS::CodeBuild::Project 50 | Properties: 51 | Description: CodeBuild project to sync CodeCommit repositories to S3 on backup account 52 | ServiceRole: !GetAtt CodeBuildRole.Arn 53 | Artifacts: 54 | Type: NO_ARTIFACTS 55 | Environment: 56 | Type: LINUX_CONTAINER 57 | ComputeType: BUILD_GENERAL1_SMALL 58 | Image: aws/codebuild/standard:4.0 59 | EnvironmentVariables: 60 | - Name: BUCKET 61 | Value: !Ref CodeCommitBackupBucket 62 | Type: PLAINTEXT 63 | - Name: ACCOUNT 64 | Value: !Sub ${AWS::AccountId} 65 | Type: PLAINTEXT 66 | Source: 67 | Location: !Join 68 | - '' 69 | - - !Ref CodeCommitBackupBucket 70 | - '/codebuild-source/' 71 | Type: S3 72 | TimeoutInMinutes: 10 73 | 74 | # Lambda function to create the buildspec.yml in the CodeCommitBackupBucket 75 | CreateBuildspec: 76 | Type: AWS::Serverless::Function 77 | Properties: 78 | Handler: index.handler 79 | Runtime: python3.9 80 | # Python inline code to create a buildspec.yml file in the backup bucket to run CodeBuild 81 | InlineCode: | 82 | import boto3 83 | import os 84 | import cfnresponse 85 | 86 | def handler(event, context): 87 | filename = "buildspec.yml" 88 | # buildspec.yml code inside the string 89 | string = """ 90 | version: 0.2 91 | phases: 92 | install: 93 | commands: 94 | - pip install git-remote-codecommit 95 | build: 96 | commands: 97 | - git clone -b $REFERENCE_NAME codecommit::$REPO_REGION://$REPOSITORY_NAME 98 | - dt=$(date '+%d-%m-%Y-%H:%M:%S'); 99 | - echo "$dt" 100 | - zip -r $dt-$REPOSITORY_NAME-backup.zip $REPOSITORY_NAME 101 | - timestamp=$(date +"%Y-%m-%d_%H-%M-%S") 102 | - aws s3 cp $dt-$REPOSITORY_NAME-backup.zip s3://$BUCKET/repositories/""" 103 | 104 | encoded_string = string.encode("utf-8") 105 | bucket_name = os.environ['bucket'] 106 | s3_path = "codebuild-source/" + filename 107 | s3 = boto3.resource("s3") 108 | responseData = {} 109 | try: 110 | print("Creating buildspec file") 111 | s3.Bucket(bucket_name).put_object(Key=s3_path, Body=encoded_string) 112 | print("File created") 113 | responseData['Data'] = "File created" 114 | cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData) 115 | except Exception as e: 116 | print("There was an error creating the file") 117 | log_exception() 118 | responseData['Data'] = e 119 | cfnresponse.send(event, context, cfnresponse.FAILED, responseData) 120 | return 121 | Environment: 122 | Variables: 123 | bucket: !Ref CodeCommitBackupBucket 124 | Policies: 125 | - AWSLambdaExecute 126 | - Version: '2012-10-17' 127 | Statement: 128 | - Effect: Allow 129 | Action: 130 | - s3:PutObject 131 | Resource: !Join 132 | - '' 133 | - - 'arn:aws:s3:::' 134 | - !Ref CodeCommitBackupBucket 135 | - '/*' 136 | 137 | # Custom resource to trigger the Lambda function at deployment time 138 | TriggerBuildspecCreation: 139 | Type: AWS::CloudFormation::CustomResource 140 | DependsOn: CreateBuildspec 141 | Version: "1.0" 142 | Properties: 143 | ServiceToken: !GetAtt CreateBuildspec.Arn 144 | 145 | # Role for the event 146 | EventRole: 147 | Description: IAM role to allow Amazon CloudWatch Events to trigger AWS CodeBuild build 148 | Properties: 149 | AssumeRolePolicyDocument: 150 | Statement: 151 | - Action: sts:AssumeRole 152 | Effect: Allow 153 | Principal: 154 | Service: 155 | - events.amazonaws.com 156 | Sid: 1 157 | Policies: 158 | - PolicyDocument: 159 | Statement: 160 | - Action: 161 | - codebuild:StartBuild 162 | Effect: Allow 163 | Resource: !GetAtt 'CodeBuildProject.Arn' 164 | PolicyName: !Join 165 | - '-' 166 | - - !Ref 'AWS::StackName' 167 | - CloudWatchEventPolicy 168 | RoleName: !Join 169 | - '-' 170 | - - !Ref 'AWS::StackName' 171 | - CloudWatchEventRule 172 | Type: AWS::IAM::Role 173 | 174 | # Event that triggers the CodeBuild when the content of a CodeCommit repository is modified 175 | EventRule: 176 | Type: "AWS::Events::Rule" 177 | Properties: 178 | Description: "EventRule" 179 | EventPattern: 180 | source: 181 | - aws.codecommit 182 | detail-type: 183 | - CodeCommit Repository State Change 184 | detail: 185 | event: 186 | - referenceCreated 187 | - referenceUpdated 188 | State: "ENABLED" 189 | Targets: 190 | - Arn: !GetAtt 'CodeBuildProject.Arn' 191 | Id: CodeCommit2S3 192 | RoleArn: !GetAtt 'EventRole.Arn' 193 | InputTransformer: 194 | InputPathsMap: 195 | "referenceType": "$.detail.referenceType" 196 | "region": "$.region" 197 | "repositoryName": "$.detail.repositoryName" 198 | "account": "$.account" 199 | "referenceName": "$.detail.referenceName" 200 | InputTemplate: | 201 | {"environmentVariablesOverride": [{"name": "REFERENCE_NAME","value": },{"name": "REFERENCE_TYPE","value": },{"name": "REPOSITORY_NAME","value": },{"name": "REPO_REGION","value": },{"name": "ACCOUNT_ID","value": }]} 202 | 203 | Outputs: 204 | CodeCommitBackupBucket: 205 | Description: "Bucket to store the CodeCommit backup files" 206 | Value: 207 | Ref: CodeCommitBackupBucket 208 | -------------------------------------------------------------------------------- /api_gateway/lambda/vpc/Untitled Diagram.drawio: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /api_gateway/lambda/vpc/vpc_private_apis.drawio: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /lambda/dynamodb/dynamodb-streams.drawio.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | diagrams.net 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /codepipeline.drawio: -------------------------------------------------------------------------------- 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 | 87 | 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /lambda/s3_event_lambda_trigger/s3_event_trigger_lambda.drawio.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | diagrams.net 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /automated_ci_cd_pipelines/pipeline_dependencies.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: Creation of IAM Roles & Policies for Codepipeline and Codebuild, Deployment Artifact bucket, SNS Notification topic and SSM Parameters for CSSP Pipelines 3 | 4 | Resources: 5 | DeploymentArtifactBucket: 6 | Type: AWS::S3::Bucket 7 | Metadata: 8 | #checkov:skip=CKV_AWS_18:Bucket logging configuration set as private 9 | cfn_nag: 10 | rules_to_suppress: 11 | - id: W35 12 | reason: Bucket logging configuration set as private 13 | DeletionPolicy: Delete 14 | Properties: 15 | BucketName: !Join 16 | - "-" 17 | - - "deployment-artifact-bucket" 18 | - !Select 19 | - 0 20 | - !Split 21 | - "-" 22 | - !Select 23 | - 2 24 | - !Split 25 | - "/" 26 | - !Ref "AWS::StackId" 27 | AccessControl: Private 28 | PublicAccessBlockConfiguration: 29 | BlockPublicAcls: true 30 | BlockPublicPolicy: true 31 | IgnorePublicAcls: true 32 | RestrictPublicBuckets: true 33 | BucketEncryption: 34 | ServerSideEncryptionConfiguration: 35 | - ServerSideEncryptionByDefault: 36 | SSEAlgorithm: AES256 37 | VersioningConfiguration: 38 | Status: Enabled 39 | 40 | 41 | DeploymentArtifactBucketName: 42 | Type: AWS::SSM::Parameter 43 | Properties: 44 | Name: DeploymentArtifactBucketName 45 | Type: String 46 | Value: !Ref 'DeploymentArtifactBucket' 47 | Description: Deployment Artifiact bucket Name for the pipelines 48 | 49 | DeploymentArtifactBucketARN: 50 | Type: AWS::SSM::Parameter 51 | Properties: 52 | Name: DeploymentArtifactBucketARN 53 | Type: String 54 | Value: !GetAtt DeploymentArtifactBucket.Arn 55 | Description: Deployment Artifiact bucket ARN for the pipelines 56 | 57 | DeploymentArtifactBucketPolicy: 58 | Type: AWS::S3::BucketPolicy 59 | Properties: 60 | Bucket: !Ref DeploymentArtifactBucket 61 | PolicyDocument: 62 | Version: 2012-10-17 63 | Statement: 64 | - Sid: PolicyforAllowtoUploadObjects 65 | Action: 66 | - s3:GetObject 67 | - s3:GetObjectVersion 68 | - s3:PutObject 69 | Effect: Allow 70 | Resource: !Join 71 | - '' 72 | - - !GetAtt 'DeploymentArtifactBucket.Arn' 73 | - /* 74 | Principal: 75 | AWS: 76 | - !GetAtt CodeBuildRole.Arn 77 | - !GetAtt CodePipelineServiceRole.Arn 78 | - !GetAtt CloudFormationServiceRole.Arn 79 | 80 | - Sid: PolicyforAllowVersioning 81 | Effect: Allow 82 | Principal: 83 | AWS: 84 | - !GetAtt CodeBuildRole.Arn 85 | - !GetAtt CodePipelineServiceRole.Arn 86 | - !GetAtt CloudFormationServiceRole.Arn 87 | Action: s3:PutBucketVersioning 88 | Resource: !GetAtt 'DeploymentArtifactBucket.Arn' 89 | 90 | 91 | CodeBuildPolicy: 92 | Type: AWS::IAM::ManagedPolicy 93 | Metadata: 94 | cfn_nag: 95 | rules_to_suppress: 96 | - id: W28 97 | reason: Explicit names are used for this policy to restrict the access of the statemachine role in the main template. 98 | Properties: 99 | ManagedPolicyName: !Join 100 | - '-' 101 | - - 'codebuild-policy' 102 | - !Ref 'AWS::Region' 103 | PolicyDocument: 104 | Version: 2012-10-17 105 | Statement: 106 | - Action: 107 | - logs:CreateLogGroup 108 | - logs:CreateLogStream 109 | - logs:PutLogEvents 110 | Effect: Allow 111 | Resource: 112 | - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:*" 113 | - Action: 114 | - codecommit:GitPull 115 | - codecommit:ListRepositories 116 | - codecommit:GetBranch 117 | Effect: Allow 118 | Resource: 119 | - !Sub "arn:aws:codecommit:${AWS::Region}:${AWS::AccountId}:*" 120 | - Action: 121 | - s3:PutObject 122 | - s3:PutBucketVersioning 123 | Effect: Allow 124 | Resource: 125 | - !GetAtt DeploymentArtifactBucket.Arn 126 | - !Join 127 | - '' 128 | - - !GetAtt DeploymentArtifactBucket.Arn 129 | - /* 130 | - Action: 131 | - s3:GetObject 132 | - s3:GetObjectVersion 133 | - s3:ListBucket 134 | Effect: Allow 135 | Resource: 136 | - 'arn:aws:s3:::*' 137 | - Action: 138 | - ssm:GetParameter 139 | - ssm:GetParameters 140 | Effect: Allow 141 | Resource: 142 | - !Sub "arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:*" 143 | - Action: 144 | - iam:GetPolicy 145 | - iam:ListPolicyVersions 146 | - iam:GetRole 147 | Effect: Allow 148 | Resource: 149 | - "arn:aws:iam:::*" 150 | - Action: 151 | - iam:PassRole 152 | - iam:CreateRole 153 | - iam:PutRolePolicy 154 | - iam:CreatePolicy 155 | - iam:AttachRolePolicy 156 | Effect: Allow 157 | Resource: 158 | - !Sub "arn:aws:iam::${AWS::AccountId}:role/Codebuild-Role-${AWS::Region}" 159 | - !Sub "arn:aws:iam::${AWS::AccountId}:role/Codepipeline-Role-${AWS::Region}" 160 | - !Sub "arn:aws:iam::${AWS::AccountId}:role/Pipeline-CFT-Role-${AWS::Region}" 161 | - !Sub "arn:aws:iam::${AWS::AccountId}:policy/codebuild-policy-${AWS::Region}" 162 | - !Sub "arn:aws:iam::${AWS::AccountId}:policy/codepipeline-policy-${AWS::Region}" 163 | - Action: 164 | - codebuild:CreateReportGroup 165 | - codebuild:CreateReport 166 | - codebuild:UpdateReport 167 | - codebuild:BatchPutTestCases 168 | - codebuild:BatchPutCodeCoverages 169 | Effect: Allow 170 | Resource: 171 | - !Sub "arn:aws:codebuild:${AWS::Region}:${AWS::AccountId}:*" 172 | Roles: 173 | - !Ref 'CodeBuildRole' 174 | CodeBuildRole: 175 | Properties: 176 | AssumeRolePolicyDocument: 177 | Version: 2012-10-17 178 | Statement: 179 | - Action: sts:AssumeRole 180 | Effect: Allow 181 | Principal: 182 | Service: codebuild.amazonaws.com 183 | Path: / 184 | RoleName: !Join 185 | - '-' 186 | - - 'Codebuild-Role' 187 | - !Ref 'AWS::Region' 188 | Type: AWS::IAM::Role 189 | Metadata: 190 | cfn_nag: 191 | rules_to_suppress: 192 | - id: W28 193 | reason: Explicit names are used for this iam role. 194 | 195 | CodePipelineServiceRole: 196 | Type: AWS::IAM::Role 197 | Metadata: 198 | cfn_nag: 199 | rules_to_suppress: 200 | - id: W28 201 | reason: Explicit names are used for this iam role. 202 | Properties: 203 | AssumeRolePolicyDocument: 204 | Version: 2012-10-17 205 | Statement: 206 | - Effect: Allow 207 | Action: 208 | - sts:AssumeRole 209 | Principal: 210 | Service: 211 | - codepipeline.amazonaws.com 212 | RoleName: !Join 213 | - '-' 214 | - - 'Codepipeline-Role' 215 | - !Ref 'AWS::Region' 216 | CodePipelineServicePolicy: 217 | # This policy orchestrates CloudFormation and CodeBuild. 218 | Type: AWS::IAM::ManagedPolicy 219 | Metadata: 220 | cfn_nag: 221 | rules_to_suppress: 222 | - id: W28 223 | reason: Explicit names are used for this policy to restrict the access of the statemachine role in the main template. 224 | 225 | Properties: 226 | ManagedPolicyName: !Join 227 | - '-' 228 | - - 'codepipeline-policy' 229 | - !Ref 'AWS::Region' 230 | Roles: 231 | - !Ref CodePipelineServiceRole 232 | PolicyDocument: 233 | Version: 2012-10-17 234 | Statement: 235 | - Effect: Allow 236 | Action: 237 | - logs:CreateLogGroup 238 | - logs:CreateLogStream 239 | - logs:PutLogEvents 240 | Resource: "arn:aws:logs:*:*:*" 241 | - Action: 242 | - s3:PutObject 243 | - s3:PutBucketVersioning 244 | Effect: Allow 245 | Resource: 246 | - !GetAtt DeploymentArtifactBucket.Arn 247 | - !Join 248 | - '' 249 | - - !GetAtt DeploymentArtifactBucket.Arn 250 | - /* 251 | - Action: 252 | - s3:GetObject 253 | - s3:GetObjectVersion 254 | - s3:ListBucket 255 | Effect: Allow 256 | Resource: 257 | - 'arn:aws:s3:::*' 258 | - Effect: Allow 259 | Action: 260 | - codebuild:ListProjects 261 | - codebuild:RetryBuild 262 | - codebuild:StartBuild 263 | - codebuild:StopBuild 264 | - codebuild:BatchGetBuilds 265 | Resource: 266 | - !Sub "arn:aws:codebuild:${AWS::Region}:${AWS::AccountId}:*" 267 | - Effect: Allow 268 | Action: 269 | - codecommit:BatchGetCommits 270 | - codecommit:BatchGetRepositories 271 | - codecommit:GetBranch 272 | - codecommit:GetCommit 273 | - codecommit:GetRepository 274 | - codecommit:GetUploadArchiveStatus 275 | - codecommit:GitPull 276 | - codecommit:ListBranches 277 | - codecommit:ListRepositories 278 | - codecommit:UploadArchive 279 | Resource: 280 | - !Sub "arn:aws:codecommit:${AWS::Region}:${AWS::AccountId}:*" 281 | - Effect: Allow 282 | Action: 283 | - iam:PassRole 284 | Resource: !GetAtt CloudFormationServiceRole.Arn 285 | CloudFormationServiceRole: 286 | Type: AWS::IAM::Role 287 | Metadata: 288 | cfn_nag: 289 | rules_to_suppress: 290 | - id: W28 291 | reason: Explicit names are used for this iam role. 292 | Properties: 293 | AssumeRolePolicyDocument: 294 | Version: 2012-10-17 295 | Statement: 296 | - Effect: Allow 297 | Action: 298 | - sts:AssumeRole 299 | Principal: 300 | Service: 301 | - cloudformation.amazonaws.com 302 | RoleName: !Join 303 | - '-' 304 | - - 'Pipeline-CFT-Role' 305 | - !Ref 'AWS::Region' 306 | 307 | 308 | CodePipelineServiceARN: 309 | Type: AWS::SSM::Parameter 310 | Properties: 311 | Name: CodePipelineServiceRoleARN 312 | Type: String 313 | Value: !GetAtt CodePipelineServiceRole.Arn 314 | Description: SSM Parameter for storing CodePipelineServiceRole ARN 315 | CodeBuildRoleARN: 316 | Type: AWS::SSM::Parameter 317 | Properties: 318 | Name: CodeBuildRoleARN 319 | Type: String 320 | Value: !GetAtt CodeBuildRole.Arn 321 | Description: SSM Parameter for storing CodeBuildRole ARN 322 | CodeBuildRoleName: 323 | Type: AWS::SSM::Parameter 324 | Properties: 325 | Name: CodeBuildRoleName 326 | Type: String 327 | Value: !Ref 'CodeBuildRole' 328 | Description: SSM Parameter for storing CodeBuildRole Name 329 | --------------------------------------------------------------------------------