From 81eb2f478d7879134fcb33af9164ce5d843e2736 Mon Sep 17 00:00:00 2001 From: John Culkin Date: Sat, 13 Feb 2021 20:25:43 -0500 Subject: [PATCH] Updated READMEs --- .../cdk-AWS-Cookbook-605/.gitignore | 11 + .../DockerBlue/Dockerfile | 2 + .../DockerBlue/index.html | 1 + .../DockerGreen/Dockerfile | 2 + .../DockerGreen/index.html | 1 + .../cdk-AWS-Cookbook-605/README.md | 58 ++++ .../cdk-AWS-Cookbook-605/app.py | 11 + .../cdk-AWS-Cookbook-605/cdk.json | 12 + .../cdk_aws_cookbook_605/__init__.py | 0 .../cdk_aws_cookbook_605_stack.py | 298 ++++++++++++++++++ .../cdk-AWS-Cookbook-605/helper.py | 33 ++ .../cdk-AWS-Cookbook-605/requirements.txt | 58 ++++ .../cdk-AWS-Cookbook-605/setup.py | 45 +++ .../cdk-AWS-Cookbook-605/source.bat | 13 + .../cdk-AWS-Cookbook-606/.gitignore | 11 + .../cdk-AWS-Cookbook-606/Docker/Dockerfile | 7 + .../cdk-AWS-Cookbook-606/Docker/README.md | 12 + .../Docker/app/WebContent/WEB-INF/web.xml | 14 + .../cdk-AWS-Cookbook-606/Docker/app/pom.xml | 51 +++ .../net/zengineering/LoadtestServlet.java | 84 +++++ .../cdk-AWS-Cookbook-606/Docker/build.sh | 5 + .../cdk-AWS-Cookbook-606/README.md | 58 ++++ .../cdk-AWS-Cookbook-606/app.py | 11 + .../cdk-AWS-Cookbook-606/cdk.json | 12 + .../cdk_aws_cookbook_606/__init__.py | 0 .../cdk_aws_cookbook_606_stack.py | 182 +++++++++++ .../cdk-AWS-Cookbook-606/helper.py | 33 ++ .../cdk-AWS-Cookbook-606/requirements.txt | 57 ++++ .../cdk-AWS-Cookbook-606/setup.py | 45 +++ .../cdk-AWS-Cookbook-606/source.bat | 13 + .../cdk-AWS-Cookbook-607/.gitignore | 11 + .../cdk-AWS-Cookbook-607/README.md | 58 ++++ .../cdk-AWS-Cookbook-607/app.py | 11 + .../cdk-AWS-Cookbook-607/cdk.json | 12 + .../cdk_aws_cookbook_607/__init__.py | 0 .../cdk_aws_cookbook_607_stack.py | 126 ++++++++ .../cdk-AWS-Cookbook-607/helper.py | 33 ++ .../cdk-AWS-Cookbook-607/requirements.txt | 60 ++++ .../cdk-AWS-Cookbook-607/setup.py | 45 +++ .../cdk-AWS-Cookbook-607/source.bat | 13 + .../cdk-AWS-Cookbook-608/.gitignore | 11 + .../cdk-AWS-Cookbook-608/README.md | 58 ++++ .../cdk-AWS-Cookbook-608/app.py | 11 + .../cdk-AWS-Cookbook-608/cdk.json | 12 + .../cdk_aws_cookbook_608/__init__.py | 0 .../cdk_aws_cookbook_608_stack.py | 66 ++++ .../cdk-AWS-Cookbook-608/helper.py | 33 ++ .../cdk-AWS-Cookbook-608/requirements.txt | 57 ++++ .../cdk-AWS-Cookbook-608/setup.py | 45 +++ .../cdk-AWS-Cookbook-608/source.bat | 13 + 50 files changed, 1815 insertions(+) create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/.gitignore create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerBlue/Dockerfile create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerBlue/index.html create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerGreen/Dockerfile create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerGreen/index.html create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/README.md create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/app.py create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/cdk.json create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/cdk_aws_cookbook_605/__init__.py create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/cdk_aws_cookbook_605/cdk_aws_cookbook_605_stack.py create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/helper.py create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/requirements.txt create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/setup.py create mode 100644 605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/source.bat create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/.gitignore create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/Dockerfile create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/README.md create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/app/WebContent/WEB-INF/web.xml create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/app/pom.xml create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/app/src/main/java/net/zengineering/LoadtestServlet.java create mode 100755 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/build.sh create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/README.md create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/app.py create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/cdk.json create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/cdk_aws_cookbook_606/__init__.py create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/cdk_aws_cookbook_606/cdk_aws_cookbook_606_stack.py create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/helper.py create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/requirements.txt create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/setup.py create mode 100644 606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/source.bat create mode 100644 607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/.gitignore create mode 100644 607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/README.md create mode 100644 607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/app.py create mode 100644 607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/cdk.json create mode 100644 607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/cdk_aws_cookbook_607/__init__.py create mode 100644 607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/cdk_aws_cookbook_607/cdk_aws_cookbook_607_stack.py create mode 100644 607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/helper.py create mode 100644 607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/requirements.txt create mode 100644 607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/setup.py create mode 100644 607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/source.bat create mode 100644 608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/.gitignore create mode 100644 608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/README.md create mode 100644 608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/app.py create mode 100644 608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/cdk.json create mode 100644 608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/cdk_aws_cookbook_608/__init__.py create mode 100644 608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/cdk_aws_cookbook_608/cdk_aws_cookbook_608_stack.py create mode 100644 608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/helper.py create mode 100644 608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/requirements.txt create mode 100644 608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/setup.py create mode 100644 608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/source.bat diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/.gitignore b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/.gitignore new file mode 100644 index 0000000..58505a0 --- /dev/null +++ b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/.gitignore @@ -0,0 +1,11 @@ +*.swp +package-lock.json +__pycache__ +.pytest_cache +.env +.venv +*.egg-info + +# CDK asset staging directory +.cdk.staging +cdk.out diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerBlue/Dockerfile b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerBlue/Dockerfile new file mode 100644 index 0000000..99fe1a8 --- /dev/null +++ b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerBlue/Dockerfile @@ -0,0 +1,2 @@ +FROM httpd:latest +COPY index.html /usr/local/apache2/htdocs/index.html \ No newline at end of file diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerBlue/index.html b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerBlue/index.html new file mode 100644 index 0000000..cb97896 --- /dev/null +++ b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerBlue/index.html @@ -0,0 +1 @@ + AWSCookbook

AWS Cookbook BLUE

This HTML is running in an apache container on Fargate!

\ No newline at end of file diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerGreen/Dockerfile b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerGreen/Dockerfile new file mode 100644 index 0000000..99fe1a8 --- /dev/null +++ b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerGreen/Dockerfile @@ -0,0 +1,2 @@ +FROM httpd:latest +COPY index.html /usr/local/apache2/htdocs/index.html \ No newline at end of file diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerGreen/index.html b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerGreen/index.html new file mode 100644 index 0000000..9af5fd0 --- /dev/null +++ b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/DockerGreen/index.html @@ -0,0 +1 @@ + AWSCookbook

AWS Cookbook GREEN

This HTML is running in an apache container on Fargate!

\ No newline at end of file diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/README.md b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/README.md new file mode 100644 index 0000000..17cb0bb --- /dev/null +++ b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/README.md @@ -0,0 +1,58 @@ + +# Welcome to your CDK Python project! + +This is a blank project for Python development with CDK. + +The `cdk.json` file tells the CDK Toolkit how to execute your app. + +This project is set up like a standard Python project. The initialization +process also creates a virtualenv within this project, stored under the `.venv` +directory. To create the virtualenv it assumes that there is a `python3` +(or `python` for Windows) executable in your path with access to the `venv` +package. If for any reason the automatic creation of the virtualenv fails, +you can create the virtualenv manually. + +To manually create a virtualenv on MacOS and Linux: + +``` +$ python3 -m venv .venv +``` + +After the init process completes and the virtualenv is created, you can use the following +step to activate your virtualenv. + +``` +$ source .venv/bin/activate +``` + +If you are a Windows platform, you would activate the virtualenv like this: + +``` +% .venv\Scripts\activate.bat +``` + +Once the virtualenv is activated, you can install the required dependencies. + +``` +$ pip install -r requirements.txt +``` + +At this point you can now synthesize the CloudFormation template for this code. + +``` +$ cdk synth +``` + +To add additional dependencies, for example other CDK libraries, just add +them to your `setup.py` file and rerun the `pip install -r requirements.txt` +command. + +## Useful commands + + * `cdk ls` list all stacks in the app + * `cdk synth` emits the synthesized CloudFormation template + * `cdk deploy` deploy this stack to your default AWS account/region + * `cdk diff` compare deployed stack with current state + * `cdk docs` open CDK documentation + +Enjoy! diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/app.py b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/app.py new file mode 100644 index 0000000..20eeecf --- /dev/null +++ b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/app.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python3 + +from aws_cdk import core + +from cdk_aws_cookbook_605.cdk_aws_cookbook_605_stack import CdkAwsCookbook605Stack + + +app = core.App() +CdkAwsCookbook605Stack(app, "cdk-aws-cookbook-605") + +app.synth() diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/cdk.json b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/cdk.json new file mode 100644 index 0000000..552b09f --- /dev/null +++ b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/cdk.json @@ -0,0 +1,12 @@ +{ + "app": "python3 app.py", + "context": { + "@aws-cdk/core:enableStackNameDuplicates": "true", + "aws-cdk:enableDiffNoFail": "true", + "@aws-cdk/core:stackRelativeExports": "true", + "@aws-cdk/aws-ecr-assets:dockerIgnoreSupport": true, + "@aws-cdk/aws-secretsmanager:parseOwnedSecretName": true, + "@aws-cdk/aws-kms:defaultKeyPolicies": true, + "@aws-cdk/aws-s3:grantWriteWithoutAcl": true + } +} diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/cdk_aws_cookbook_605/__init__.py b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/cdk_aws_cookbook_605/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/cdk_aws_cookbook_605/cdk_aws_cookbook_605_stack.py b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/cdk_aws_cookbook_605/cdk_aws_cookbook_605_stack.py new file mode 100644 index 0000000..4888007 --- /dev/null +++ b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/cdk_aws_cookbook_605/cdk_aws_cookbook_605_stack.py @@ -0,0 +1,298 @@ +from aws_cdk import ( + aws_ec2 as ec2, + aws_ecs as ecs, + aws_s3 as s3, + aws_ecr_assets as ecr_assets, + aws_elasticloadbalancingv2 as alb, + core, +) + + +class CdkAwsCookbook605Stack(core.Stack): + + def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) + + ecr_asset_blue = ecr_assets.DockerImageAsset( + self, + 'ecr_asset_blue', + directory='DockerBlue', + ) + + ecr_asset_green = ecr_assets.DockerImageAsset( + self, + 'ecr_asset_green', + directory='DockerGreen', + ) + + # create VPC + vpc = ec2.Vpc( + self, + 'AWS-Cookbook-VPC' + ) + + albSecurityGroup = ec2.SecurityGroup( + self, + 'albSecurityGroup', + description='Security Group for the ALB', + allow_all_outbound=True, + vpc=vpc + ) + + albSecurityGroup.add_ingress_rule( + peer=ec2.Peer.ipv4("0.0.0.0/0"), + connection=ec2.Port.tcp(80), + description='Allow HTTP from the world', + remote_rule=False + ) + + albSecurityGroup.add_ingress_rule( + peer=ec2.Peer.ipv4("0.0.0.0/0"), + connection=ec2.Port.tcp(8080), + description='Allow 8080 from the world', + remote_rule=False + ) + + fargate_service_security_group = ec2.SecurityGroup( + self, + 'fargate_service_security_group', + description='Security Group for the Fargate Service', + allow_all_outbound=True, + vpc=vpc + ) + + fargate_service_security_group.connections.allow_from( + albSecurityGroup, ec2.Port.tcp(80), "Ingress") + + # create ECS Cluster + ecs_cluster = ecs.Cluster( + self, + 'AWS-Cookbook-EcsCluster', + cluster_name='awscookbook605', + vpc=vpc + ) + + FargateTaskBlue = ecs.FargateTaskDefinition( + self, + 'FargateTaskBlue', + cpu=256, + memory_limit_mib=512, + ) + + ContainerDefBlue = ecs.ContainerDefinition( + self, + 'ContainerDefBlue', + image=ecs.ContainerImage.from_docker_image_asset(ecr_asset_blue), + task_definition=FargateTaskBlue, + ) + + ContainerDefBlue.add_port_mappings( + ecs.PortMapping( + container_port=80 + ) + ) + + FargateTaskGreen = ecs.FargateTaskDefinition( + self, + 'FargateTaskGreen', + cpu=256, + memory_limit_mib=512, + ) + + ContainerDefGreen = ecs.ContainerDefinition( + self, + 'ContainerDefGreen', + image=ecs.ContainerImage.from_docker_image_asset(ecr_asset_green), + task_definition=FargateTaskGreen, + ) + + ContainerDefGreen.add_port_mappings( + ecs.PortMapping( + container_port=80 + ) + ) + + FargateService = ecs.FargateService( + self, + 'awscookbook605', + cluster=ecs_cluster, + task_definition=FargateTaskBlue, + assign_public_ip=False, + desired_count=2, + enable_ecs_managed_tags=False, + # health_check_grace_period=core.Duration.seconds(60), + max_healthy_percent=100, + min_healthy_percent=0, + platform_version=ecs.FargatePlatformVersion('LATEST'), + security_group=fargate_service_security_group, + service_name='AWSCookbook605', + deployment_controller=ecs.DeploymentController( + type=ecs.DeploymentControllerType('CODE_DEPLOY') + ), + vpc_subnets=ec2.SubnetSelection( + one_per_az=False, + subnet_type=ec2.SubnetType('PRIVATE') + ) + ) + + lb = alb.ApplicationLoadBalancer( + self, + 'LB', + vpc=vpc, + deletion_protection=False, + http2_enabled=True, + idle_timeout=core.Duration.seconds(60), + internet_facing=True, + ip_address_type=alb.IpAddressType('IPV4'), + load_balancer_name='FargateServiceALB', + security_group=albSecurityGroup, + vpc_subnets=ec2.SubnetSelection( + one_per_az=False, + subnet_type=ec2.SubnetType('PUBLIC') + ) + ) + + DefaultTargetGroup = alb.ApplicationTargetGroup( + self, + "DefaultTargetGroup", + port=80, + vpc=vpc, + target_group_name="DefaultTG", + target_type=alb.TargetType('IP'), + ) + + listener80 = alb.ApplicationListener( + self, + 'listener80', + load_balancer=lb, + open=False, + port=80, + protocol=alb.ApplicationProtocol('HTTP'), + default_target_groups=[DefaultTargetGroup] + ) + + BlueTargetGroup = listener80.add_targets( + 'BlueTargetGroup', + deregistration_delay=core.Duration.seconds(60), + health_check=alb.HealthCheck( + healthy_http_codes='200', + healthy_threshold_count=2, + interval=core.Duration.seconds(10), + path='/', + port='traffic-port', + protocol=alb.Protocol('HTTP'), + unhealthy_threshold_count=2 + ), + host_header="*.*.*", + port=80, + priority=1, + protocol=alb.ApplicationProtocol('HTTP'), + target_group_name="BlueTG", + targets=[FargateService] + ) + + listener8080 = alb.ApplicationListener( + self, + 'listener8080', + load_balancer=lb, + open=False, + port=8080, + protocol=alb.ApplicationProtocol('HTTP'), + default_target_groups=[BlueTargetGroup] + ) + + # create s3 bucket + s3_Bucket = s3.Bucket( + self, + "AWS-Cookbook-Recipe605", + removal_policy=core.RemovalPolicy.DESTROY, + auto_delete_objects=True + ) + + # outputs + + core.CfnOutput( + self, + 'BlueImage', + value=ecr_asset_blue.image_uri + ) + + core.CfnOutput( + self, + 'GreenImage', + value=ecr_asset_green.image_uri + ) + + core.CfnOutput( + self, + 'VPCId', + value=vpc.vpc_id + ) + + core.CfnOutput( + self, + 'LoadBalancerDNS', + value=lb.load_balancer_dns_name + ) + + core.CfnOutput( + self, + 'ECSClusterName', + value=ecs_cluster.cluster_name + ) + + public_subnets = vpc.select_subnets(subnet_type=ec2.SubnetType.PUBLIC) + + core.CfnOutput( + self, + 'VPCPublicSubnets', + value=', '.join(map(str, public_subnets.subnet_ids)) + ) + + core.CfnOutput( + self, + 'VPCDefaultSecurityGroup', + value=vpc.vpc_default_security_group + ) + + core.CfnOutput( + self, + 'S3BucketName', + value=s3_Bucket.bucket_name + ) + + core.CfnOutput( + self, + 'BlueTargetGroupName', + value=BlueTargetGroup.target_group_arn + ) + + core.CfnOutput( + self, + 'ProdListenerArn', + value=listener80.listener_arn + ) + + core.CfnOutput( + self, + 'TestListenerArn', + value=listener8080.listener_arn + ) + + core.CfnOutput( + self, + 'DefaultTargetGroupArn', + value=DefaultTargetGroup.target_group_arn + ) + + core.CfnOutput( + self, + 'FargateTaskBlueArn', + value=FargateTaskBlue.task_definition_arn + ) + + core.CfnOutput( + self, + 'FargateTaskGreenArn', + value=FargateTaskGreen.task_definition_arn + ) diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/helper.py b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/helper.py new file mode 100644 index 0000000..b584031 --- /dev/null +++ b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/helper.py @@ -0,0 +1,33 @@ +import os +import boto3 +import argparse + +parser = argparse.ArgumentParser(description="Generate commands to set and unset environment variables") +parser.add_argument('--unset', action='store_true', help="Generate commands to unset environment variables by setting this flag") + +args = parser.parse_args() + +os.environ['AWS_DEFAULT_REGION'] = os.environ.get('AWS_REGION') + +cfn = boto3.client('cloudformation') +stackname = os.path.basename(os.getcwd()).lower() +response = cfn.describe_stacks(StackName=stackname) +unsets = [] +sets = [] + +outputs = response["Stacks"][0]["Outputs"] +print("Copy and paste the commands below into your terminal") +print("") +for output in outputs: + if ', ' in output["OutputValue"]: + sets.append(output["OutputKey"] + "='" + ', '.join('"{}"'.format(word) for word in output["OutputValue"].split(", ")) + "'") + else: + sets.append(output["OutputKey"] + "='" + output["OutputValue"] + "'") + unsets.append("unset " + output["OutputKey"]) + +if (args.unset): + print('\n'.join(map(str, unsets))) +else: + print('\n'.join(map(str, sets))) + +print("") diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/requirements.txt b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/requirements.txt new file mode 100644 index 0000000..46fa954 --- /dev/null +++ b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/requirements.txt @@ -0,0 +1,58 @@ +-e . +boto3 +botocore +jsii +attr +attrs +cattrs +constructs +typing_extensions +jmespath +publication +python-dateutil +s3transfer +six +typing-extensions +urllib3 +aws_cdk.core +aws-cdk.assets +aws-cdk.aws-apigateway +aws-cdk.aws-apigatewayv2 +aws-cdk.aws-applicationautoscaling +aws-cdk.aws-autoscaling +aws-cdk.aws-autoscaling-common +aws-cdk.aws-autoscaling-hooktargets +aws-cdk.aws-certificatemanager +aws-cdk.aws-cloudformation +aws-cdk.aws-cloudfront +aws-cdk.aws-cloudwatch +aws-cdk.aws-codeguruprofiler +aws-cdk.aws-cognito +aws-cdk.aws-ecr +aws-cdk.aws-efs +aws-cdk.aws-elasticloadbalancing +aws-cdk.aws-elasticloadbalancingv2 +aws-cdk.aws-events +aws-cdk.aws-iam +aws-cdk.aws-kms +aws-cdk.aws-lambda +aws-cdk.aws-logs +aws-cdk.aws-route53 +aws-cdk.aws-route53-targets +aws-cdk.aws-s3 +aws-cdk.aws-s3-assets +aws-cdk.aws-sam +aws-cdk.aws-secretsmanager +aws-cdk.aws-servicediscovery +aws-cdk.aws-sns +aws-cdk.aws-sns-subscriptions +aws-cdk.aws-sqs +aws-cdk.aws-ssm +aws-cdk.cloud-assembly-schema +aws-cdk.custom-resources +aws-cdk.cx-api +aws-cdk.region-info +aws_cdk.aws_ec2 +aws_cdk.aws_ecs +aws_cdk.aws_ecr_assets +aws_cdk.aws_elasticloadbalancingv2 diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/setup.py b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/setup.py new file mode 100644 index 0000000..6990738 --- /dev/null +++ b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/setup.py @@ -0,0 +1,45 @@ +import setuptools + + +with open("README.md") as fp: + long_description = fp.read() + + +setuptools.setup( + name="cdk_aws_cookbook_605", + version="0.0.1", + + description="An empty CDK Python app", + long_description=long_description, + long_description_content_type="text/markdown", + + author="author", + + package_dir={"": "cdk_aws_cookbook_605"}, + packages=setuptools.find_packages(where="cdk_aws_cookbook_605"), + + install_requires=[ + "aws-cdk.core==1.88.0", + ], + + python_requires=">=3.6", + + classifiers=[ + "Development Status :: 4 - Beta", + + "Intended Audience :: Developers", + + "License :: OSI Approved :: Apache Software License", + + "Programming Language :: JavaScript", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + + "Topic :: Software Development :: Code Generators", + "Topic :: Utilities", + + "Typing :: Typed", + ], +) diff --git a/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/source.bat b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/source.bat new file mode 100644 index 0000000..9e1a834 --- /dev/null +++ b/605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/source.bat @@ -0,0 +1,13 @@ +@echo off + +rem The sole purpose of this script is to make the command +rem +rem source .venv/bin/activate +rem +rem (which activates a Python virtualenv on Linux or Mac OS X) work on Windows. +rem On Windows, this command just runs this batch file (the argument is ignored). +rem +rem Now we don't need to document a Windows command for activating a virtualenv. + +echo Executing .venv\Scripts\activate.bat for you +.venv\Scripts\activate.bat diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/.gitignore b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/.gitignore new file mode 100644 index 0000000..58505a0 --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/.gitignore @@ -0,0 +1,11 @@ +*.swp +package-lock.json +__pycache__ +.pytest_cache +.env +.venv +*.egg-info + +# CDK asset staging directory +.cdk.staging +cdk.out diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/Dockerfile b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/Dockerfile new file mode 100644 index 0000000..945177e --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/Dockerfile @@ -0,0 +1,7 @@ +FROM maven:3.6.3-jdk-8 AS build +COPY app/ /opt/app +RUN cd /opt/app && mvn clean install + +FROM tomcat:8.5-jdk8-slim +RUN rm -rf /usr/local/tomcat/webapps/ROOT +COPY --from=build /opt/app/target/loadtest.war /usr/local/tomcat/webapps/ROOT.war \ No newline at end of file diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/README.md b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/README.md new file mode 100644 index 0000000..5f62d5b --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/README.md @@ -0,0 +1,12 @@ +# aws loadtest api +java servlet and tomcat 8.5 implementation of a load test API for containers +java sdk8 and maven 3.x for build + +Easily demonstrate ECS AutoScaling and simulate container CPU, Memory and request loads on container infrastructure + +## Usage +* Run locally using "docker run -rm --it -p 8080:8080 mzazon/loadtest" +* HTTP GET "/loadtest/cpu" +* Initiates an HTTP call which will load CPU to 100% +* Returns JSON +* Healthcheck path for load balancers HTTP GET "/loadtest/healthcheck" \ No newline at end of file diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/app/WebContent/WEB-INF/web.xml b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/app/WebContent/WEB-INF/web.xml new file mode 100644 index 0000000..4f3b3e5 --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/app/WebContent/WEB-INF/web.xml @@ -0,0 +1,14 @@ + + + loadtest + + + LoadtestServlet + LoadtestServlet + net.zengineering.java.loadtest.LoadtestServlet + + + LoadtestServlet + /* + + \ No newline at end of file diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/app/pom.xml b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/app/pom.xml new file mode 100644 index 0000000..5da6660 --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/app/pom.xml @@ -0,0 +1,51 @@ + + 4.0.0 + net.zengineering.java.loadtest + loadtest + 2.1 + war + + loadtest + + + maven-war-plugin + 2.3 + + WebContent + false + + + + + + + javax.servlet + servlet-api + 2.5 + provided + + + + + diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/app/src/main/java/net/zengineering/LoadtestServlet.java b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/app/src/main/java/net/zengineering/LoadtestServlet.java new file mode 100644 index 0000000..753e3eb --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/app/src/main/java/net/zengineering/LoadtestServlet.java @@ -0,0 +1,84 @@ +package net.zengineering.java.loadtest; + +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; + +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.net.InetAddress; +import java.net.UnknownHostException; + +public class LoadtestServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + private DateFormat httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); + + public LoadtestServlet() { + httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + long now = System.currentTimeMillis(); + String timeStr = request.getParameter("time"); + String httpStatusStr = request.getParameter("http-status"); + int httpStatus = (httpStatusStr!=null?Integer.parseInt(httpStatusStr):200); + long maxTime = (timeStr != null ? Long.parseLong(timeStr) : 0L); + + long time = maxTime; + + if (request.getRequestURI().endsWith("/cpu")) { + + double value = 9.9; + while (System.currentTimeMillis() <= (now + 99999999)) { + value = value / 1.0000001; + value = value * 1.00000015; + if (value > Double.MAX_VALUE / 2) { + value = 1.0; + } + } + finishTest(request, response, (System.currentTimeMillis() - now), httpStatus, "success", "value=" + value); + + } else if (request.getRequestURI().endsWith("/healthcheck")) { + // aws load balancer health check + + double value = 9.9; + while (System.currentTimeMillis() <= (now + 3000)) { + value = value / 1.0000001; + value = value * 1.00000015; + if (value > Double.MAX_VALUE / 2) { + value = 1.0; + } + } + finishTest(request, response, (System.currentTimeMillis() - now), httpStatus, "success", "value=" + value); + + } else { + finishTest(request, response, (System.currentTimeMillis() - now), 400, "error", + ""); + } + + } + + private void finishTest(HttpServletRequest request, HttpServletResponse response, long timeElapsed, int statusCode, String result, String info) { + try { + response.setContentType("application/json"); + response.setStatus(statusCode); + ServletOutputStream responseOS = response.getOutputStream(); + InetAddress ip; + ip = InetAddress.getLocalHost(); + String hostname = ip.getHostName(); + String body = "{\n \"URL\":\"" + request.getRequestURL() + "\",\n \"ContainerLocalAddress\":\"" + request.getLocalAddr() + ":" + request.getLocalPort() + "\",\n \"ProcessingTimeTotalMilliseconds\":\"" + timeElapsed + "\",\n \"LoadBalancerPrivateIP\":\"" + request.getRemoteHost() + "\",\n \"ContainerHostname\":\"" + hostname + "\",\n \"CurrentTime\":\"" + System.currentTimeMillis() + "\"\n}"; + responseOS.print(body); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/build.sh b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/build.sh new file mode 100755 index 0000000..6199612 --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/Docker/build.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +set -e + +docker build -t mzazon/loadtest:latest . \ No newline at end of file diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/README.md b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/README.md new file mode 100644 index 0000000..17cb0bb --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/README.md @@ -0,0 +1,58 @@ + +# Welcome to your CDK Python project! + +This is a blank project for Python development with CDK. + +The `cdk.json` file tells the CDK Toolkit how to execute your app. + +This project is set up like a standard Python project. The initialization +process also creates a virtualenv within this project, stored under the `.venv` +directory. To create the virtualenv it assumes that there is a `python3` +(or `python` for Windows) executable in your path with access to the `venv` +package. If for any reason the automatic creation of the virtualenv fails, +you can create the virtualenv manually. + +To manually create a virtualenv on MacOS and Linux: + +``` +$ python3 -m venv .venv +``` + +After the init process completes and the virtualenv is created, you can use the following +step to activate your virtualenv. + +``` +$ source .venv/bin/activate +``` + +If you are a Windows platform, you would activate the virtualenv like this: + +``` +% .venv\Scripts\activate.bat +``` + +Once the virtualenv is activated, you can install the required dependencies. + +``` +$ pip install -r requirements.txt +``` + +At this point you can now synthesize the CloudFormation template for this code. + +``` +$ cdk synth +``` + +To add additional dependencies, for example other CDK libraries, just add +them to your `setup.py` file and rerun the `pip install -r requirements.txt` +command. + +## Useful commands + + * `cdk ls` list all stacks in the app + * `cdk synth` emits the synthesized CloudFormation template + * `cdk deploy` deploy this stack to your default AWS account/region + * `cdk diff` compare deployed stack with current state + * `cdk docs` open CDK documentation + +Enjoy! diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/app.py b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/app.py new file mode 100644 index 0000000..b660d24 --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/app.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python3 + +from aws_cdk import core + +from cdk_aws_cookbook_606.cdk_aws_cookbook_606_stack import CdkAwsCookbook606Stack + + +app = core.App() +CdkAwsCookbook606Stack(app, "cdk-aws-cookbook-606") + +app.synth() diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/cdk.json b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/cdk.json new file mode 100644 index 0000000..552b09f --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/cdk.json @@ -0,0 +1,12 @@ +{ + "app": "python3 app.py", + "context": { + "@aws-cdk/core:enableStackNameDuplicates": "true", + "aws-cdk:enableDiffNoFail": "true", + "@aws-cdk/core:stackRelativeExports": "true", + "@aws-cdk/aws-ecr-assets:dockerIgnoreSupport": true, + "@aws-cdk/aws-secretsmanager:parseOwnedSecretName": true, + "@aws-cdk/aws-kms:defaultKeyPolicies": true, + "@aws-cdk/aws-s3:grantWriteWithoutAcl": true + } +} diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/cdk_aws_cookbook_606/__init__.py b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/cdk_aws_cookbook_606/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/cdk_aws_cookbook_606/cdk_aws_cookbook_606_stack.py b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/cdk_aws_cookbook_606/cdk_aws_cookbook_606_stack.py new file mode 100644 index 0000000..2b6ed39 --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/cdk_aws_cookbook_606/cdk_aws_cookbook_606_stack.py @@ -0,0 +1,182 @@ +from aws_cdk import ( + aws_ec2 as ec2, + aws_ecs as ecs, + aws_elasticloadbalancingv2 as alb, + aws_ecr_assets as ecr_assets, + core, +) + + +class CdkAwsCookbook606Stack(core.Stack): + + def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) + + ecr_asset = ecr_assets.DockerImageAsset( + self, + 'ecr_asset', + directory='Docker', + ) + + # create VPC + vpc = ec2.Vpc( + self, + 'AWS-Cookbook-VPC' + ) + + InterfaceEndpointSecurityGroup = ec2.SecurityGroup( + self, + 'InterfaceEndpointSecurityGroup', + description='Security Group for the VPC Endpoints', + allow_all_outbound=True, + vpc=vpc + ) + + InterfaceEndpointSecurityGroup.connections.allow_from( + ec2.Peer.ipv4(vpc.vpc_cidr_block), ec2.Port.tcp(443), "Ingress") + + vpc.add_interface_endpoint( + 'CloudWatchLogsEndpoint', + service=ec2.InterfaceVpcEndpointAwsService('logs'), + private_dns_enabled=True, + security_groups=[InterfaceEndpointSecurityGroup], + subnets=ec2.SubnetSelection( + one_per_az=True, + subnet_type=ec2.SubnetType.PRIVATE + ), + ) + + albSecurityGroup = ec2.SecurityGroup( + self, + 'albSecurityGroup', + description='Security Group for the ALB', + allow_all_outbound=True, + vpc=vpc + ) + + albSecurityGroup.add_ingress_rule( + peer=ec2.Peer.ipv4("0.0.0.0/0"), + connection=ec2.Port.tcp(80), + description='Allow HTTP from the world', + remote_rule=False + ) + + fargate_service_security_group = ec2.SecurityGroup( + self, + 'fargate_service_security_group', + description='Security Group for the Fargate Service', + allow_all_outbound=True, + vpc=vpc + ) + + fargate_service_security_group.connections.allow_from( + albSecurityGroup, ec2.Port.tcp(8080), "Ingress") + + # create ECS Cluster + ecs_cluster = ecs.Cluster( + self, + 'AWS-Cookbook-EcsCluster', + vpc=vpc + ) + + FargateTask = ecs.FargateTaskDefinition( + self, + 'FargateTask', + cpu=256, + memory_limit_mib=512, + ) + + ContainerDef = ecs.ContainerDefinition( + self, + 'ContainerDef', + image=ecs.ContainerImage.from_docker_image_asset(ecr_asset), + task_definition=FargateTask, + ) + + ContainerDef.add_port_mappings( + ecs.PortMapping( + container_port=8080 + ) + ) + + FargateService = ecs.FargateService( + self, + 'awscookbook606', + cluster=ecs_cluster, + task_definition=FargateTask, + assign_public_ip=False, + desired_count=2, + enable_ecs_managed_tags=False, + max_healthy_percent=100, + min_healthy_percent=0, + platform_version=ecs.FargatePlatformVersion('LATEST'), + security_group=fargate_service_security_group, + service_name='AWSCookbook606', + vpc_subnets=ec2.SubnetSelection( + one_per_az=False, + subnet_type=ec2.SubnetType('PRIVATE') + ) + ) + + lb = alb.ApplicationLoadBalancer( + self, + 'LB', + vpc=vpc, + deletion_protection=False, + http2_enabled=True, + idle_timeout=core.Duration.seconds(60), + internet_facing=True, + ip_address_type=alb.IpAddressType('IPV4'), + load_balancer_name='FargateServiceALB', + security_group=albSecurityGroup, + vpc_subnets=ec2.SubnetSelection( + one_per_az=False, + subnet_type=ec2.SubnetType('PUBLIC') + ) + ) + + DefaultTargetGroup = alb.ApplicationTargetGroup( + self, + "DefaultTargetGroup", + deregistration_delay=core.Duration.seconds(60), + health_check=alb.HealthCheck( + healthy_http_codes='200', + healthy_threshold_count=2, + interval=core.Duration.seconds(10), + path='/loadtest/healthcheck', + port='traffic-port', + protocol=alb.Protocol('HTTP'), + unhealthy_threshold_count=10 + ), + port=80, + vpc=vpc, + target_group_name="DefaultTG", + target_type=alb.TargetType('IP'), + targets=[FargateService] + ) + + alb.ApplicationListener( + self, + 'listener80', + load_balancer=lb, + open=False, + port=80, + protocol=alb.ApplicationProtocol('HTTP'), + default_target_groups=[DefaultTargetGroup] + ) + + core.CfnOutput( + self, 'LoadBalancerDNS', + value=lb.load_balancer_dns_name + ) + + core.CfnOutput( + self, 'ECSClusterName', + value=ecs_cluster.cluster_name + ) + + core.CfnOutput( + self, + 'ECRImage', + value=ecr_asset.image_uri + ) diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/helper.py b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/helper.py new file mode 100644 index 0000000..b584031 --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/helper.py @@ -0,0 +1,33 @@ +import os +import boto3 +import argparse + +parser = argparse.ArgumentParser(description="Generate commands to set and unset environment variables") +parser.add_argument('--unset', action='store_true', help="Generate commands to unset environment variables by setting this flag") + +args = parser.parse_args() + +os.environ['AWS_DEFAULT_REGION'] = os.environ.get('AWS_REGION') + +cfn = boto3.client('cloudformation') +stackname = os.path.basename(os.getcwd()).lower() +response = cfn.describe_stacks(StackName=stackname) +unsets = [] +sets = [] + +outputs = response["Stacks"][0]["Outputs"] +print("Copy and paste the commands below into your terminal") +print("") +for output in outputs: + if ', ' in output["OutputValue"]: + sets.append(output["OutputKey"] + "='" + ', '.join('"{}"'.format(word) for word in output["OutputValue"].split(", ")) + "'") + else: + sets.append(output["OutputKey"] + "='" + output["OutputValue"] + "'") + unsets.append("unset " + output["OutputKey"]) + +if (args.unset): + print('\n'.join(map(str, unsets))) +else: + print('\n'.join(map(str, sets))) + +print("") diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/requirements.txt b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/requirements.txt new file mode 100644 index 0000000..6287533 --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/requirements.txt @@ -0,0 +1,57 @@ +-e . +boto3 +botocore +jsii +attr +attrs +cattrs +constructs +typing_extensions +jmespath +publication +python-dateutil +s3transfer +six +typing-extensions +urllib3 +aws_cdk.core +aws-cdk.assets +aws-cdk.aws-apigateway +aws-cdk.aws-apigatewayv2 +aws-cdk.aws-applicationautoscaling +aws-cdk.aws-autoscaling +aws-cdk.aws-autoscaling-common +aws-cdk.aws-autoscaling-hooktargets +aws-cdk.aws-certificatemanager +aws-cdk.aws-cloudformation +aws-cdk.aws-cloudfront +aws-cdk.aws-cloudwatch +aws-cdk.aws-codeguruprofiler +aws-cdk.aws-cognito +aws-cdk.aws-ecr +aws-cdk.aws-efs +aws-cdk.aws-elasticloadbalancing +aws-cdk.aws-elasticloadbalancingv2 +aws-cdk.aws-events +aws-cdk.aws-iam +aws-cdk.aws-kms +aws-cdk.aws-lambda +aws-cdk.aws-logs +aws-cdk.aws-route53 +aws-cdk.aws-route53-targets +aws-cdk.aws-s3 +aws-cdk.aws-s3-assets +aws-cdk.aws-sam +aws-cdk.aws-secretsmanager +aws-cdk.aws-servicediscovery +aws-cdk.aws-sns +aws-cdk.aws-sns-subscriptions +aws-cdk.aws-sqs +aws-cdk.aws-ssm +aws-cdk.cloud-assembly-schema +aws-cdk.custom-resources +aws-cdk.cx-api +aws-cdk.region-info +aws_cdk.aws_ec2 +aws_cdk.aws_ecs +aws_cdk.aws_ecr_assets \ No newline at end of file diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/setup.py b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/setup.py new file mode 100644 index 0000000..c5f6688 --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/setup.py @@ -0,0 +1,45 @@ +import setuptools + + +with open("README.md") as fp: + long_description = fp.read() + + +setuptools.setup( + name="cdk_aws_cookbook_606", + version="0.0.1", + + description="An empty CDK Python app", + long_description=long_description, + long_description_content_type="text/markdown", + + author="author", + + package_dir={"": "cdk_aws_cookbook_606"}, + packages=setuptools.find_packages(where="cdk_aws_cookbook_606"), + + install_requires=[ + "aws-cdk.core==1.88.0", + ], + + python_requires=">=3.6", + + classifiers=[ + "Development Status :: 4 - Beta", + + "Intended Audience :: Developers", + + "License :: OSI Approved :: Apache Software License", + + "Programming Language :: JavaScript", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + + "Topic :: Software Development :: Code Generators", + "Topic :: Utilities", + + "Typing :: Typed", + ], +) diff --git a/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/source.bat b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/source.bat new file mode 100644 index 0000000..9e1a834 --- /dev/null +++ b/606-Autoscaling-Container-Workloads/cdk-AWS-Cookbook-606/source.bat @@ -0,0 +1,13 @@ +@echo off + +rem The sole purpose of this script is to make the command +rem +rem source .venv/bin/activate +rem +rem (which activates a Python virtualenv on Linux or Mac OS X) work on Windows. +rem On Windows, this command just runs this batch file (the argument is ignored). +rem +rem Now we don't need to document a Windows command for activating a virtualenv. + +echo Executing .venv\Scripts\activate.bat for you +.venv\Scripts\activate.bat diff --git a/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/.gitignore b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/.gitignore new file mode 100644 index 0000000..58505a0 --- /dev/null +++ b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/.gitignore @@ -0,0 +1,11 @@ +*.swp +package-lock.json +__pycache__ +.pytest_cache +.env +.venv +*.egg-info + +# CDK asset staging directory +.cdk.staging +cdk.out diff --git a/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/README.md b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/README.md new file mode 100644 index 0000000..17cb0bb --- /dev/null +++ b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/README.md @@ -0,0 +1,58 @@ + +# Welcome to your CDK Python project! + +This is a blank project for Python development with CDK. + +The `cdk.json` file tells the CDK Toolkit how to execute your app. + +This project is set up like a standard Python project. The initialization +process also creates a virtualenv within this project, stored under the `.venv` +directory. To create the virtualenv it assumes that there is a `python3` +(or `python` for Windows) executable in your path with access to the `venv` +package. If for any reason the automatic creation of the virtualenv fails, +you can create the virtualenv manually. + +To manually create a virtualenv on MacOS and Linux: + +``` +$ python3 -m venv .venv +``` + +After the init process completes and the virtualenv is created, you can use the following +step to activate your virtualenv. + +``` +$ source .venv/bin/activate +``` + +If you are a Windows platform, you would activate the virtualenv like this: + +``` +% .venv\Scripts\activate.bat +``` + +Once the virtualenv is activated, you can install the required dependencies. + +``` +$ pip install -r requirements.txt +``` + +At this point you can now synthesize the CloudFormation template for this code. + +``` +$ cdk synth +``` + +To add additional dependencies, for example other CDK libraries, just add +them to your `setup.py` file and rerun the `pip install -r requirements.txt` +command. + +## Useful commands + + * `cdk ls` list all stacks in the app + * `cdk synth` emits the synthesized CloudFormation template + * `cdk deploy` deploy this stack to your default AWS account/region + * `cdk diff` compare deployed stack with current state + * `cdk docs` open CDK documentation + +Enjoy! diff --git a/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/app.py b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/app.py new file mode 100644 index 0000000..16812cc --- /dev/null +++ b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/app.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python3 + +from aws_cdk import core + +from cdk_aws_cookbook_607.cdk_aws_cookbook_607_stack import CdkAwsCookbook607Stack + + +app = core.App() +CdkAwsCookbook607Stack(app, "cdk-aws-cookbook-607") + +app.synth() diff --git a/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/cdk.json b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/cdk.json new file mode 100644 index 0000000..552b09f --- /dev/null +++ b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/cdk.json @@ -0,0 +1,12 @@ +{ + "app": "python3 app.py", + "context": { + "@aws-cdk/core:enableStackNameDuplicates": "true", + "aws-cdk:enableDiffNoFail": "true", + "@aws-cdk/core:stackRelativeExports": "true", + "@aws-cdk/aws-ecr-assets:dockerIgnoreSupport": true, + "@aws-cdk/aws-secretsmanager:parseOwnedSecretName": true, + "@aws-cdk/aws-kms:defaultKeyPolicies": true, + "@aws-cdk/aws-s3:grantWriteWithoutAcl": true + } +} diff --git a/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/cdk_aws_cookbook_607/__init__.py b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/cdk_aws_cookbook_607/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/cdk_aws_cookbook_607/cdk_aws_cookbook_607_stack.py b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/cdk_aws_cookbook_607/cdk_aws_cookbook_607_stack.py new file mode 100644 index 0000000..ba57e80 --- /dev/null +++ b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/cdk_aws_cookbook_607/cdk_aws_cookbook_607_stack.py @@ -0,0 +1,126 @@ +from aws_cdk import ( + aws_ec2 as ec2, + aws_ecs as ecs, + aws_s3 as s3, + aws_iam as iam, + aws_cloudtrail as cloudtrail, + core, +) + + +class CdkAwsCookbook607Stack(core.Stack): + + def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) + + cloud_trail_bucket = s3.Bucket( + self, + "AWS-Cookbok-Recipe607-Cloud-trail", + removal_policy=core.RemovalPolicy.DESTROY, + auto_delete_objects=True + ) + + trail = cloudtrail.Trail( + self, + 'Cloudtrail', + bucket=cloud_trail_bucket + ) + + s3_Bucket = s3.Bucket( + self, + "AWS-Cookbok-Recipe607", + removal_policy=core.RemovalPolicy.DESTROY, + auto_delete_objects=True + ) + + # create VPC + vpc = ec2.Vpc( + self, + 'AWS-Cookbook-VPC' + ) + + # create ECS Cluster + ecs_cluster = ecs.Cluster( + self, + 'AWS-Cookbook-EcsCluster', + vpc=vpc + ) + + # create Fargate Task Definition + FargateTask = ecs.FargateTaskDefinition( + self, + 'AWS-Cookbook-FargateTask', + cpu=1024, + memory_limit_mib=2048, + ) + + # create Container Definition + ContainerDefinition = ecs.ContainerDefinition( + self, + 'AWS-Cookbook-ContainerDefinition', + image=ecs.ContainerImage.from_registry("public.ecr.aws/x4e8a6b6/mazesolver:1.0.7"), + task_definition=FargateTask, + ) + + ContainerDefinition.add_port_mappings( + ecs.PortMapping( + container_port=80 + ) + ) + + # Grant the container access to the s3 bucket by adding an IAM policy to the execution role + FargateTask.add_to_task_role_policy(iam.PolicyStatement( + effect=iam.Effect.ALLOW, + resources=[s3_Bucket.bucket_arn + '/*'], + actions=["s3:*"]) + ) + + core.CfnOutput( + self, + 'CloudTrailArn', + value=trail.trail_arn + ) + + core.CfnOutput( + self, + 'S3BucketARN', + value=s3_Bucket.bucket_arn + ) + + core.CfnOutput( + self, + 'CloudTrailS3BucketName', + value=cloud_trail_bucket.bucket_name + ) + + core.CfnOutput( + self, + 'S3BucketName', + value=s3_Bucket.bucket_name + ) + + core.CfnOutput( + self, + 'ECSClusterARN', + value=ecs_cluster.cluster_arn + ) + + core.CfnOutput( + self, + 'TaskDefinitionARN', + value=FargateTask.task_definition_arn + ) + + private_subnets = vpc.select_subnets(subnet_type=ec2.SubnetType.PRIVATE) + + core.CfnOutput( + self, + 'VPCPrivateSubnets', + value=', '.join(map(str, private_subnets.subnet_ids)) + ) + + core.CfnOutput( + self, + 'VPCDefaultSecurityGroup', + value=vpc.vpc_default_security_group + ) diff --git a/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/helper.py b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/helper.py new file mode 100644 index 0000000..b584031 --- /dev/null +++ b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/helper.py @@ -0,0 +1,33 @@ +import os +import boto3 +import argparse + +parser = argparse.ArgumentParser(description="Generate commands to set and unset environment variables") +parser.add_argument('--unset', action='store_true', help="Generate commands to unset environment variables by setting this flag") + +args = parser.parse_args() + +os.environ['AWS_DEFAULT_REGION'] = os.environ.get('AWS_REGION') + +cfn = boto3.client('cloudformation') +stackname = os.path.basename(os.getcwd()).lower() +response = cfn.describe_stacks(StackName=stackname) +unsets = [] +sets = [] + +outputs = response["Stacks"][0]["Outputs"] +print("Copy and paste the commands below into your terminal") +print("") +for output in outputs: + if ', ' in output["OutputValue"]: + sets.append(output["OutputKey"] + "='" + ', '.join('"{}"'.format(word) for word in output["OutputValue"].split(", ")) + "'") + else: + sets.append(output["OutputKey"] + "='" + output["OutputValue"] + "'") + unsets.append("unset " + output["OutputKey"]) + +if (args.unset): + print('\n'.join(map(str, unsets))) +else: + print('\n'.join(map(str, sets))) + +print("") diff --git a/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/requirements.txt b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/requirements.txt new file mode 100644 index 0000000..4c2a455 --- /dev/null +++ b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/requirements.txt @@ -0,0 +1,60 @@ +-e . +boto3 +botocore +jsii +attr +attrs +cattrs +constructs +typing_extensions +jmespath +publication +python-dateutil +s3transfer +six +typing-extensions +urllib3 +aws_cdk.core +aws-cdk.assets +aws-cdk.aws-apigateway +aws-cdk.aws-apigatewayv2 +aws-cdk.aws-applicationautoscaling +aws-cdk.aws-autoscaling +aws-cdk.aws-autoscaling-common +aws-cdk.aws-autoscaling-hooktargets +aws-cdk.aws-certificatemanager +aws-cdk.aws-cloudformation +aws-cdk.aws-cloudfront +aws-cdk.aws-cloudwatch +aws-cdk.aws-codeguruprofiler +aws-cdk.aws-cognito +aws-cdk.aws-ecr +aws-cdk.aws-efs +aws-cdk.aws-elasticloadbalancing +aws-cdk.aws-elasticloadbalancingv2 +aws-cdk.aws-events +aws-cdk.aws-iam +aws-cdk.aws-kms +aws-cdk.aws-lambda +aws-cdk.aws-logs +aws-cdk.aws-route53 +aws-cdk.aws-route53-targets +aws-cdk.aws-s3 +aws-cdk.aws-s3-assets +aws-cdk.aws-sam +aws-cdk.aws-secretsmanager +aws-cdk.aws-servicediscovery +aws-cdk.aws-sns +aws-cdk.aws-sns-subscriptions +aws-cdk.aws-sqs +aws-cdk.aws-ssm +aws-cdk.cloud-assembly-schema +aws-cdk.custom-resources +aws-cdk.cx-api +aws-cdk.region-info +aws_cdk.aws_ec2 +aws_cdk.aws_ecs +aws_cdk.aws_s3 +aws_cdk.aws_iam +aws_cdk.aws_cloudtrail +aws_cdk.aws_ecr_assets diff --git a/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/setup.py b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/setup.py new file mode 100644 index 0000000..7efced8 --- /dev/null +++ b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/setup.py @@ -0,0 +1,45 @@ +import setuptools + + +with open("README.md") as fp: + long_description = fp.read() + + +setuptools.setup( + name="cdk_aws_cookbook_607", + version="0.0.1", + + description="An empty CDK Python app", + long_description=long_description, + long_description_content_type="text/markdown", + + author="author", + + package_dir={"": "cdk_aws_cookbook_607"}, + packages=setuptools.find_packages(where="cdk_aws_cookbook_607"), + + install_requires=[ + "aws-cdk.core==1.88.0", + ], + + python_requires=">=3.6", + + classifiers=[ + "Development Status :: 4 - Beta", + + "Intended Audience :: Developers", + + "License :: OSI Approved :: Apache Software License", + + "Programming Language :: JavaScript", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + + "Topic :: Software Development :: Code Generators", + "Topic :: Utilities", + + "Typing :: Typed", + ], +) diff --git a/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/source.bat b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/source.bat new file mode 100644 index 0000000..9e1a834 --- /dev/null +++ b/607-Fargate-Task-With-Event/cdk-AWS-Cookbook-607/source.bat @@ -0,0 +1,13 @@ +@echo off + +rem The sole purpose of this script is to make the command +rem +rem source .venv/bin/activate +rem +rem (which activates a Python virtualenv on Linux or Mac OS X) work on Windows. +rem On Windows, this command just runs this batch file (the argument is ignored). +rem +rem Now we don't need to document a Windows command for activating a virtualenv. + +echo Executing .venv\Scripts\activate.bat for you +.venv\Scripts\activate.bat diff --git a/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/.gitignore b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/.gitignore new file mode 100644 index 0000000..58505a0 --- /dev/null +++ b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/.gitignore @@ -0,0 +1,11 @@ +*.swp +package-lock.json +__pycache__ +.pytest_cache +.env +.venv +*.egg-info + +# CDK asset staging directory +.cdk.staging +cdk.out diff --git a/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/README.md b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/README.md new file mode 100644 index 0000000..17cb0bb --- /dev/null +++ b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/README.md @@ -0,0 +1,58 @@ + +# Welcome to your CDK Python project! + +This is a blank project for Python development with CDK. + +The `cdk.json` file tells the CDK Toolkit how to execute your app. + +This project is set up like a standard Python project. The initialization +process also creates a virtualenv within this project, stored under the `.venv` +directory. To create the virtualenv it assumes that there is a `python3` +(or `python` for Windows) executable in your path with access to the `venv` +package. If for any reason the automatic creation of the virtualenv fails, +you can create the virtualenv manually. + +To manually create a virtualenv on MacOS and Linux: + +``` +$ python3 -m venv .venv +``` + +After the init process completes and the virtualenv is created, you can use the following +step to activate your virtualenv. + +``` +$ source .venv/bin/activate +``` + +If you are a Windows platform, you would activate the virtualenv like this: + +``` +% .venv\Scripts\activate.bat +``` + +Once the virtualenv is activated, you can install the required dependencies. + +``` +$ pip install -r requirements.txt +``` + +At this point you can now synthesize the CloudFormation template for this code. + +``` +$ cdk synth +``` + +To add additional dependencies, for example other CDK libraries, just add +them to your `setup.py` file and rerun the `pip install -r requirements.txt` +command. + +## Useful commands + + * `cdk ls` list all stacks in the app + * `cdk synth` emits the synthesized CloudFormation template + * `cdk deploy` deploy this stack to your default AWS account/region + * `cdk diff` compare deployed stack with current state + * `cdk docs` open CDK documentation + +Enjoy! diff --git a/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/app.py b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/app.py new file mode 100644 index 0000000..abec631 --- /dev/null +++ b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/app.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python3 + +from aws_cdk import core + +from cdk_aws_cookbook_608.cdk_aws_cookbook_608_stack import CdkAwsCookbook608Stack + + +app = core.App() +CdkAwsCookbook608Stack(app, "cdk-aws-cookbook-608") + +app.synth() diff --git a/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/cdk.json b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/cdk.json new file mode 100644 index 0000000..552b09f --- /dev/null +++ b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/cdk.json @@ -0,0 +1,12 @@ +{ + "app": "python3 app.py", + "context": { + "@aws-cdk/core:enableStackNameDuplicates": "true", + "aws-cdk:enableDiffNoFail": "true", + "@aws-cdk/core:stackRelativeExports": "true", + "@aws-cdk/aws-ecr-assets:dockerIgnoreSupport": true, + "@aws-cdk/aws-secretsmanager:parseOwnedSecretName": true, + "@aws-cdk/aws-kms:defaultKeyPolicies": true, + "@aws-cdk/aws-s3:grantWriteWithoutAcl": true + } +} diff --git a/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/cdk_aws_cookbook_608/__init__.py b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/cdk_aws_cookbook_608/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/cdk_aws_cookbook_608/cdk_aws_cookbook_608_stack.py b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/cdk_aws_cookbook_608/cdk_aws_cookbook_608_stack.py new file mode 100644 index 0000000..a3a6827 --- /dev/null +++ b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/cdk_aws_cookbook_608/cdk_aws_cookbook_608_stack.py @@ -0,0 +1,66 @@ +from aws_cdk import ( + aws_ec2 as ec2, + aws_ecs as ecs, + core, +) + + +class CdkAwsCookbook608Stack(core.Stack): + + def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) + + # create VPC + vpc = ec2.Vpc( + self, + 'AWS-Cookbook-VPC' + ) + + InterfaceEndpointSecurityGroup = ec2.SecurityGroup( + self, + 'InterfaceEndpointSecurityGroup', + description='Security Group for the VPC Endpoints', + allow_all_outbound=True, + vpc=vpc + ) + + InterfaceEndpointSecurityGroup.connections.allow_from( + ec2.Peer.ipv4(vpc.vpc_cidr_block), ec2.Port.tcp(443), "Ingress") + + vpc.add_interface_endpoint( + 'CloudWatchLogsEndpoint', + service=ec2.InterfaceVpcEndpointAwsService('logs'), + private_dns_enabled=True, + security_groups=[InterfaceEndpointSecurityGroup], + subnets=ec2.SubnetSelection( + one_per_az=True, + subnet_type=ec2.SubnetType.PRIVATE + ), + ) + + # create ECS Cluster + ecs_cluster = ecs.Cluster( + self, + 'AWS-Cookbook-EcsCluster', + vpc=vpc + ) + + core.CfnOutput( + self, + 'ECSClusterName', + value=ecs_cluster.cluster_name + ) + + public_subnets = vpc.select_subnets(subnet_type=ec2.SubnetType.PUBLIC) + + core.CfnOutput( + self, + 'VPCPublicSubnets', + value=', '.join(map(str, public_subnets.subnet_ids)) + ) + + core.CfnOutput( + self, + 'VPCDefaultSecurityGroup', + value=vpc.vpc_default_security_group + ) diff --git a/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/helper.py b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/helper.py new file mode 100644 index 0000000..b584031 --- /dev/null +++ b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/helper.py @@ -0,0 +1,33 @@ +import os +import boto3 +import argparse + +parser = argparse.ArgumentParser(description="Generate commands to set and unset environment variables") +parser.add_argument('--unset', action='store_true', help="Generate commands to unset environment variables by setting this flag") + +args = parser.parse_args() + +os.environ['AWS_DEFAULT_REGION'] = os.environ.get('AWS_REGION') + +cfn = boto3.client('cloudformation') +stackname = os.path.basename(os.getcwd()).lower() +response = cfn.describe_stacks(StackName=stackname) +unsets = [] +sets = [] + +outputs = response["Stacks"][0]["Outputs"] +print("Copy and paste the commands below into your terminal") +print("") +for output in outputs: + if ', ' in output["OutputValue"]: + sets.append(output["OutputKey"] + "='" + ', '.join('"{}"'.format(word) for word in output["OutputValue"].split(", ")) + "'") + else: + sets.append(output["OutputKey"] + "='" + output["OutputValue"] + "'") + unsets.append("unset " + output["OutputKey"]) + +if (args.unset): + print('\n'.join(map(str, unsets))) +else: + print('\n'.join(map(str, sets))) + +print("") diff --git a/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/requirements.txt b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/requirements.txt new file mode 100644 index 0000000..6287533 --- /dev/null +++ b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/requirements.txt @@ -0,0 +1,57 @@ +-e . +boto3 +botocore +jsii +attr +attrs +cattrs +constructs +typing_extensions +jmespath +publication +python-dateutil +s3transfer +six +typing-extensions +urllib3 +aws_cdk.core +aws-cdk.assets +aws-cdk.aws-apigateway +aws-cdk.aws-apigatewayv2 +aws-cdk.aws-applicationautoscaling +aws-cdk.aws-autoscaling +aws-cdk.aws-autoscaling-common +aws-cdk.aws-autoscaling-hooktargets +aws-cdk.aws-certificatemanager +aws-cdk.aws-cloudformation +aws-cdk.aws-cloudfront +aws-cdk.aws-cloudwatch +aws-cdk.aws-codeguruprofiler +aws-cdk.aws-cognito +aws-cdk.aws-ecr +aws-cdk.aws-efs +aws-cdk.aws-elasticloadbalancing +aws-cdk.aws-elasticloadbalancingv2 +aws-cdk.aws-events +aws-cdk.aws-iam +aws-cdk.aws-kms +aws-cdk.aws-lambda +aws-cdk.aws-logs +aws-cdk.aws-route53 +aws-cdk.aws-route53-targets +aws-cdk.aws-s3 +aws-cdk.aws-s3-assets +aws-cdk.aws-sam +aws-cdk.aws-secretsmanager +aws-cdk.aws-servicediscovery +aws-cdk.aws-sns +aws-cdk.aws-sns-subscriptions +aws-cdk.aws-sqs +aws-cdk.aws-ssm +aws-cdk.cloud-assembly-schema +aws-cdk.custom-resources +aws-cdk.cx-api +aws-cdk.region-info +aws_cdk.aws_ec2 +aws_cdk.aws_ecs +aws_cdk.aws_ecr_assets \ No newline at end of file diff --git a/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/setup.py b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/setup.py new file mode 100644 index 0000000..65ed1be --- /dev/null +++ b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/setup.py @@ -0,0 +1,45 @@ +import setuptools + + +with open("README.md") as fp: + long_description = fp.read() + + +setuptools.setup( + name="cdk_aws_cookbook_608", + version="0.0.1", + + description="An empty CDK Python app", + long_description=long_description, + long_description_content_type="text/markdown", + + author="author", + + package_dir={"": "cdk_aws_cookbook_608"}, + packages=setuptools.find_packages(where="cdk_aws_cookbook_608"), + + install_requires=[ + "aws-cdk.core==1.88.0", + ], + + python_requires=">=3.6", + + classifiers=[ + "Development Status :: 4 - Beta", + + "Intended Audience :: Developers", + + "License :: OSI Approved :: Apache Software License", + + "Programming Language :: JavaScript", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + + "Topic :: Software Development :: Code Generators", + "Topic :: Utilities", + + "Typing :: Typed", + ], +) diff --git a/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/source.bat b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/source.bat new file mode 100644 index 0000000..9e1a834 --- /dev/null +++ b/608-Capturing-Logs-From-Containers-Running-On-ECS/cdk-AWS-Cookbook-608/source.bat @@ -0,0 +1,13 @@ +@echo off + +rem The sole purpose of this script is to make the command +rem +rem source .venv/bin/activate +rem +rem (which activates a Python virtualenv on Linux or Mac OS X) work on Windows. +rem On Windows, this command just runs this batch file (the argument is ignored). +rem +rem Now we don't need to document a Windows command for activating a virtualenv. + +echo Executing .venv\Scripts\activate.bat for you +.venv\Scripts\activate.bat