public UnicornStoreFargateStack(Construct parent, string id, UnicornStoreDeploymentEnvStackProps settings) : base(parent, id, settings)
        {
            this.settings = settings;

            var vpc = new Vpc(this, $"{settings.ScopeName}VPC", new VpcProps {
                MaxAzs = settings.MaxAzs
            });

            SecMan.SecretProps databasePasswordSecretSettings =
                Helpers.CreateAutoGenPasswordSecretDef($"{settings.ScopeName}DatabasePassword", passwordLength: 8);
            SecMan.Secret databasePasswordSecretConstruct = databasePasswordSecretSettings.CreateSecretConstruct(this);

            var dbConstructFactory = settings.CreateDbConstructFactory();

            DatabaseConstructOutput dbConstructOutput =
                dbConstructFactory.CreateDatabaseConstruct(this, vpc, databasePasswordSecretConstruct.SecretValue);

            var ecsCluster = new Cluster(this, $"Application{settings.Infrastructure}Cluster", new ClusterProps
            {
                Vpc         = vpc,
                ClusterName = settings.EcsClusterName
            }
                                         );

            ApplicationLoadBalancedFargateService ecsService = this.CreateEcsService(
                ecsCluster,
                Secret.FromSecretsManager(databasePasswordSecretConstruct),
                dbConstructFactory,
                dbConstructOutput
                );

            // Update RDS Security Group to allow inbound database connections from the Fargate Service Security Group
            dbConstructOutput.Connections.AllowDefaultPortFrom(ecsService.Service.Connections.SecurityGroups[0]);
        }
Exemple #2
0
        public FargateStack(Construct scope, string id, FargateStackProps props = null) : base(scope, id, props)
        {
            var cluster = new Cluster(this, "WhatDayOfWeekCluster", new ClusterProps
            {
                Vpc = props.Vpc
            });

            var logging = new AwsLogDriver(new AwsLogDriverProps()
            {
                StreamPrefix = "WhatDayOfWeek",
                LogRetention = Amazon.CDK.AWS.Logs.RetentionDays.ONE_DAY
            });

            //container

            /*
             * var repo = Repository.FromRepositoryName(this, "myrepo","MyRepositoryName");
             *
             * var containerOptions = new ContainerDefinitionOptions
             * {
             *   Image =  ContainerImage.FromEcrRepository(repo)
             * };
             */
            // to build the container image from the app in the local folder, replace lines 29-35 with


            //var rootDirectory = Directory.GetCurrentDirectory();
            //var path = Path.GetFullPath(Path.Combine(rootDirectory, @"App/WhatDayOfWeek"));

            var containerOptions = new ContainerDefinitionOptions
            {
                Image   = ContainerImage.FromAsset(@"App/WhatDayOfWeek"),
                Logging = logging
            };

            var portMapping = new PortMapping()
            {
                ContainerPort = 80,
                HostPort      = 80
            };

            var taskDef = new FargateTaskDefinition(this, "WhatDayOfWeekTaskDefinition");

            taskDef.AddContainer("WhatDayOfWeekContainer", containerOptions).AddPortMappings(portMapping);

            var serviceProps = new ApplicationLoadBalancedFargateServiceProps()
            {
                ServiceName    = "WhatDayOfWeekService",
                MemoryLimitMiB = 512,
                Cpu            = 256,
                TaskDefinition = taskDef,
                Cluster        = cluster
            };

            ApplicationLoadBalancedFargateService service = new ApplicationLoadBalancedFargateService(this, "WhatDayOfWeekService", serviceProps);
        }
        internal Stack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            //setup the image
            var asset = new DockerImageAsset(this, $"{Config.AppName}Image", new DockerImageAssetProps {
                Directory = Path.Combine(System.Environment.CurrentDirectory, "api"),
            });

            //Create the Fargate service
            var vpc = Vpc.FromLookup(
                this, "sandbox", new VpcLookupOptions
            {
                VpcName = "sandbox_vpc"
            }
                );

            var cluster = new Cluster(this, $"{Config.AppName}Cluster", new ClusterProps
            {
                Vpc = vpc
            });

            var applicationDomain = $"{Config.ApplicationSubdomain}.{Config.DomainName}";
            var hostedZone        = HostedZone.FromLookup(
                this, "HostedZone", new HostedZoneProviderProps
            {
                DomainName  = $"{Config.DomainName}.",
                PrivateZone = false
            }
                );

            // Create a load-balanced Fargate service and make it public
            var fargateService = new ApplicationLoadBalancedFargateService(this, $"{Config.AppName}Service",
                                                                           new ApplicationLoadBalancedFargateServiceProps
            {
                Cluster          = cluster,     // Required
                DesiredCount     = 1,           // Default is 1
                TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions
                {
                    Image = ContainerImage.FromDockerImageAsset(asset)
                },
                MemoryLimitMiB     = 1024,      // Default is 256
                PublicLoadBalancer = true,      // Default is false
                DomainName         = applicationDomain,
                DomainZone         = hostedZone,
            }
                                                                           );

            new CfnOutput(
                this, "Route53Url", new CfnOutputProps
            {
                Value       = applicationDomain,
                Description = "Nice Route53 Url"
            }
                );
        }
        internal MyDotNetCoreServerlessWebAppEcsFargateCdkAppStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var         imageTagParameter = this.Node.TryGetContext("ImageTag");
            string      imageTag          = imageTagParameter.ToString() ?? "latest";
            IRepository ecrRepository     = Repository.FromRepositoryArn(this, "MyDotNetCorServerlessWebAppServiceContainerRepository", "arn:aws:ecr:eu-west-1:098208531922:repository/mydotnetcorewebapp");

            var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "MyDotNetCorServerlessWebAppService", new ApplicationLoadBalancedFargateServiceProps()
            {
                AssignPublicIp   = true,
                TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions()
                {
                    Image = ContainerImage.FromEcrRepository(ecrRepository, imageTag),
                }
            });;
        }
        private ApplicationLoadBalancedFargateService CreateEcsService(
            Cluster ecsCluster,
            Secret dbPasswordSecret,
            DatabaseConstructFactory dbConstructFactory,
            DatabaseConstructOutput dbConstructOutput
            )
        {
            var imageRepository = Repository.FromRepositoryName(this, "ExistingEcrRepository", settings.DockerImageRepository);

            var ecsService = new ApplicationLoadBalancedFargateService(this, $"{settings.ScopeName}FargateService",
                                                                       new ApplicationLoadBalancedFargateServiceProps
            {
                Cluster            = ecsCluster,
                DesiredCount       = settings.DesiredComputeReplicaCount,
                Cpu                = settings.CpuMillicores,
                MemoryLimitMiB     = settings.MemoryMiB,
                PublicLoadBalancer = settings.PublicLoadBalancer,
                LoadBalancer       = new ApplicationLoadBalancer(this, $"{settings.ScopeName}-ALB", new ApplicationLoadBalancerProps {
                    LoadBalancerName = "unicorn-store",
                    Vpc                = ecsCluster.Vpc,
                    InternetFacing     = true,
                    DeletionProtection = false,
                }),
                TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions
                {
                    Image       = ContainerImage.FromEcrRepository(imageRepository, settings.ImageTag),
                    Environment = new Dictionary <string, string>()
                    {
                        { "ASPNETCORE_ENVIRONMENT", settings.DotNetEnvironment ?? "Production" },
                        { "DefaultAdminUsername", settings.DefaultSiteAdminUsername },
                        { $"UnicornDbConnectionStringBuilder__{dbConstructFactory.DbConnStrBuilderServerPropName}",
                          dbConstructOutput.EndpointAddress },
                        { $"UnicornDbConnectionStringBuilder__Port", dbConstructOutput.Port },
                        { $"UnicornDbConnectionStringBuilder__{dbConstructFactory.DBConnStrBuilderUserPropName}",
                          settings.DbUsername },
                    },
                    Secrets = new Dictionary <string, Secret>
                    {
                        { "DefaultAdminPassword", Helpers.CreateAutoGenPasswordSecretDef($"{settings.ScopeName}DefaultSiteAdminPassword").CreateSecret(this) },
                        { $"UnicornDbConnectionStringBuilder__{dbConstructFactory.DBConnStrBuilderPasswordPropName}", dbPasswordSecret }
                    }
                },
            }
                                                                       );

            return(ecsService);
        }
Exemple #6
0
        public ContainersStack(Construct parent, string id, IStackProps props) : base(parent, id, props)
        {
            var vpc = Vpc.FromLookup(this, id = "DefaultVpc", new VpcLookupOptions
            {
                IsDefault = true
            });

            if (vpc == null)
            {
                throw new System.NullReferenceException($"Unable to determine default VPC in region {this.Region}");
            }

            var cluster = new Cluster(this, "Cluster", new ClusterProps
            {
                Vpc = vpc
            });

            var taskDef = new FargateTaskDefinition(this, "FargateTaskDefinition");

            var currentDir = Directory.GetCurrentDirectory();
            var path       = Path.GetFullPath(Path.Combine(currentDir, @"dotnetapp/"));

            var containerOptions = new ContainerDefinitionOptions
            {
                Image = ContainerImage.FromAsset("dotnetapp")
            };

            var portMapping = new PortMapping()
            {
                ContainerPort = 80,
                HostPort      = 80
            };

            taskDef.AddContainer("Container", containerOptions).AddPortMappings(portMapping);

            var serviceProps = new ApplicationLoadBalancedFargateServiceProps()
            {
                MemoryLimitMiB = 512,
                Cpu            = 256,
                TaskDefinition = taskDef
            };

            ApplicationLoadBalancedFargateService service
                = new ApplicationLoadBalancedFargateService(this, "DotnetFargateApp", serviceProps);
        }
Exemple #7
0
        public ContainersStack(Construct parent, string id, IStackProps props) : base(parent, id, props)
        {
            // The code that defines your stack goes here
            var vpc = new Vpc(this, "VPC");

            var cluster = new Cluster(this, "Cluster", new ClusterProps
            {
                Vpc = vpc
            });

            var taskDef = new FargateTaskDefinition(this, "FargateTaskDefinition");

            var rootDirectory = Directory.GetCurrentDirectory();
            var path          = Path.GetFullPath(Path.Combine(rootDirectory, @"dotnetapp/"));

            var containerOptions = new ContainerDefinitionOptions
            {
                Image = ContainerImage.FromAsset("dotnetapp")
            };

            var portMapping = new PortMapping()
            {
                ContainerPort = 80,
                HostPort      = 80
            };

            taskDef.AddContainer("Container", containerOptions).AddPortMappings(portMapping);

            var serviceProps = new ApplicationLoadBalancedFargateServiceProps()
            {
                MemoryLimitMiB = 512,
                Cpu            = 256,
                TaskDefinition = taskDef
            };

            ApplicationLoadBalancedFargateService service = new ApplicationLoadBalancedFargateService(this, "DotnetFargateApp", serviceProps);
        }
        internal Example3Stack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var vpcStack = new VpcStack(this, "someTestVpc");

            var cluster = new Cluster(this, "WhatDayOfWeekCluster", new ClusterProps
            {
                Vpc = vpcStack.Vpc
            });

            var taskDef = new FargateTaskDefinition(this, "WhatDayOfWeekTaskDefinition");

            var rootDirectory = Directory.GetCurrentDirectory();

            var path = Path.GetFullPath(Path.Combine(rootDirectory, @"App/WhatDayOfWeek"));

            var containerOptions = new ContainerDefinitionOptions
            {
                Image = ContainerImage.FromAsset("App/WhatDayOfWeek")
            };

            var portMapping = new PortMapping()
            {
                ContainerPort = 80,
                HostPort      = 80
            };

            taskDef.AddContainer("WhatDayOfWeekContainer", containerOptions).AddPortMappings(portMapping);

            var serviceProps = new ApplicationLoadBalancedFargateServiceProps()
            {
                MemoryLimitMiB = 512,
                Cpu            = 256,
                TaskDefinition = taskDef
            };

            ApplicationLoadBalancedFargateService service = new ApplicationLoadBalancedFargateService(this, "WhatDayOfWeekApp", serviceProps);
        }
Exemple #9
0
        public ApiStack(Construct scope, string id, ApiProps props = null) : base(scope, id, props)
        {
            var hostedZone = HostedZone.FromHostedZoneAttributes(this, "HostedZone", new HostedZoneAttributes
            {
                ZoneName     = props.HostedZoneName,
                HostedZoneId = props.HostedZoneId
            });

            FargateService = new ApplicationLoadBalancedFargateService(this, $"{props.ServiceName}-fargate-service", new ApplicationLoadBalancedFargateServiceProps
            {
                ServiceName      = props.ServiceName,
                Cluster          = props.EcsCluster,
                TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions
                {
                    ContainerName = props.ServiceName,
                    Image         = ContainerImage.FromEcrRepository(props.EcrRepository),
                    Environment   = props.ContainerEnvVars,
                    Secrets       = props.ContainerSecrets,
                    EnableLogging = true
                },
                Certificate = props.Certificate,
                DomainName  = $"{props.SubDomain}.{props.HostedZoneName}",
                DomainZone  = hostedZone,
                //this has an internet-facing ALB open to the world - could enhance security by hiding behind an API gateway
            });

            FargateService.TargetGroup.ConfigureHealthCheck(new HealthCheck
            {
                Path = "/health"
            });

            ApiUrl = $"https://{props.SubDomain}.{props.HostedZoneName}";

            //seems handy https://github.com/aws/aws-cdk/issues/8352
            //also handy https://chekkan.com/iam-policy-perm-for-public-load-balanced-ecs-fargate-on-cdk/
        }
        public ApiStack(Construct parent, string id, IApiStackProps props) : base(parent, id, props)
        {
            var cluster = new Cluster(
                this,
                "Example",
                new ClusterProps
            {
                Vpc = props.Vpc,
            });

            var logging = new AwsLogDriver(new AwsLogDriverProps
            {
                StreamPrefix = "Example",
            });

            var taskDef = new FargateTaskDefinition(
                this,
                "Task",
                new FargateTaskDefinitionProps
            {
                MemoryLimitMiB = 512,
                Cpu            = 256,
            });

            var repo = Repository.FromRepositoryName(
                this,
                "EcrRepository",
                props.Repository.RepositoryName);

            var imageTag = new CfnParameter(
                this,
                props.ApiImageTag,
                new CfnParameterProps
            {
                Default = "latest",
            });

            var container = new ContainerDefinition(
                this,
                "ApiContainer",
                new ContainerDefinitionProps
            {
                TaskDefinition = taskDef,
                Image          = ContainerImage.FromEcrRepository(repo, imageTag.ValueAsString),
                Logging        = logging,
            });

            container.AddPortMappings(new PortMapping
            {
                ContainerPort = 80,
                HostPort      = 80,
                Protocol      = Amazon.CDK.AWS.ECS.Protocol.TCP,
            });

            var loadBalancer = new ApplicationLoadBalancer(
                this,
                "LoadBalancer",
                new ApplicationLoadBalancerProps
            {
                Vpc            = props.Vpc,
                Http2Enabled   = false,
                IdleTimeout    = Duration.Seconds(5),
                InternetFacing = true,
                IpAddressType  = IpAddressType.IPV4,
                VpcSubnets     = new SubnetSelection
                {
                    Subnets = props.Vpc.PublicSubnets,
                },
            });

            var ecsService = new ApplicationLoadBalancedFargateService(
                this,
                "Service",
                new ApplicationLoadBalancedFargateServiceProps
            {
                Cluster            = cluster,
                TaskDefinition     = taskDef,
                AssignPublicIp     = false,
                PublicLoadBalancer = true,
                LoadBalancer       = loadBalancer,
            });

            PrintLoadBalancerDnsName(ecsService);
        }