Пример #1
0
        static void Main(string[] args)
        {
            var app   = new App(null);
            var stack = new Stack(app, "mystack");
            var rule  = new Rule(stack, "myrule", new RuleProps
            {
                Targets  = new IRuleTarget[] { new MyEventTarget() },
                Schedule = Schedule.Cron(new CronOptions
                {
                    Day = "20"
                })
            });
            var lb = new ApplicationLoadBalancer(stack, "myapplb", new ApplicationLoadBalancerProps
            {
                Vpc = new Vpc(stack, "myvpc")
            });
            var listener = lb.AddListener("Listener", new ApplicationListenerProps
            {
                Port = 80
            });

            listener.AddTargets("mylbtarget", new AddApplicationTargetsProps
            {
                Targets = new IApplicationLoadBalancerTarget[] { new MyLBTarget() },
                Port    = 80
            });
            app.Synth();
        }
Пример #2
0
        internal InternalLoadBalancerStack(Construct scope, string id, IInternalLoadBalancerStackProps props) : base(scope, id, props)
        {
            var loadBalancer = new ApplicationLoadBalancer(this, "LoadBalancer", new ApplicationLoadBalancerProps
            {
                Vpc            = props.Vpc,
                InternetFacing = true
            });

            var defaultTarget = new ApplicationTargetGroup(this, "TargetGroup", new ApplicationTargetGroupProps
            {
                Vpc  = props.Vpc,
                Port = 80
            });

            Listener = loadBalancer.AddListener("Listener", new BaseApplicationListenerProps
            {
                Port = 80,
                DefaultTargetGroups = new ApplicationTargetGroup[] { defaultTarget }
            });

            new CfnOutput(this, "LoadBalancerDNS", new CfnOutputProps
            {
                Value = loadBalancer.LoadBalancerDnsName
            });
        }
Пример #3
0
        private IApplicationTargetGroup AddHttpsTargetGroup(BenchNetwork benchNetwork, Vpc vpc, DnsValidatedCertificate certificate, ApplicationLoadBalancer lb)
        {
            var targetGroup = new ApplicationTargetGroup(this, $"{StackName}-https-target-group", new ApplicationTargetGroupProps
            {
                Port        = benchNetwork.AlbHttpsPort.targetgroupPort,
                Protocol    = ApplicationProtocol.HTTP,
                Vpc         = vpc,
                TargetType  = TargetType.INSTANCE,
                HealthCheck = new Amazon.CDK.AWS.ElasticLoadBalancingV2.HealthCheck
                {
                    Enabled  = true,
                    Protocol = Amazon.CDK.AWS.ElasticLoadBalancingV2.Protocol.HTTP,
                    HealthyThresholdCount = 2,
                    Interval = Duration.Seconds(15),
                    Timeout  = Duration.Seconds(10),
                    Path     = "/health",
                },
                DeregistrationDelay = Duration.Seconds(30),
            });
            var listener = lb.AddListener("HttpsListener", new BaseApplicationListenerProps
            {
                Port         = benchNetwork.AlbHttpsPort.listenerPort,
                Protocol     = ApplicationProtocol.HTTPS,
                Certificates = new[] { new ListenerCertificate(certificate.CertificateArn) },
            });

            listener.AddTargetGroups("HttpsTargetGroupAttachment", new AddApplicationTargetGroupsProps
            {
                TargetGroups = new[] { targetGroup },
            });
            return(targetGroup);
        }
        private ApplicationListener AddListener(ApplicationLoadBalancer lb, int port, string certArn = null)
        {
            var certs = (certArn == null) ? null : new ListenerCertificate[] { new ListenerCertificate(certArn) };


            var listener = lb.AddListener($"App2BalancerListener_{port}", new BaseApplicationListenerProps
            {
                Open         = true,
                Certificates = certs,
                Port         = port,
            });


            return(listener);
        }
Пример #5
0
        private IApplicationTargetGroup AddGrpcTargetGroup(BenchNetwork benchNetwork, Vpc vpc, DnsValidatedCertificate certificate, ApplicationLoadBalancer lb)
        {
            var grpcTargetGroupResource = CreateGrpcTargetGroup(vpc, new Dictionary <string, object>()
            {
                { "Name", "MagicOnionBench-grpc-target" },
                { "Port", benchNetwork.AlbGrpcPort.targetgroupPort },
                { "Protocol", ApplicationProtocol.HTTP.ToString() },
                { "ProtocolVersion", "GRPC" },
                { "VpcId", vpc.VpcId },
                { "TargetType", "instance" },
                { "HealthCheckEnabled", true },
                { "HealthCheckProtocol", Amazon.CDK.AWS.ElasticLoadBalancingV2.Protocol.HTTP.ToString() },
                { "HealthyThresholdCount", 2 },
                { "HealthCheckIntervalSeconds", 15 },
                { "HealthCheckTimeoutSeconds", 10 },
                { "HealthCheckPath", "/grpc.health.v1.Health/Check" },
                { "Matcher", new Dictionary <string, string> {
                      { "GrpcCode", "0-99" }
                  } },
            });
            var targetGroup = ApplicationTargetGroup.FromTargetGroupAttributes(this, "grpc-target-group", new TargetGroupAttributes
            {
                TargetGroupArn = grpcTargetGroupResource.Ref,
            });
            var listener = lb.AddListener("GrpcListener", new BaseApplicationListenerProps
            {
                Port         = benchNetwork.AlbGrpcPort.listenerPort,
                Protocol     = ApplicationProtocol.HTTPS,
                Certificates = new[] { new ListenerCertificate(certificate.CertificateArn) },
            });

            listener.AddTargetGroups("GrpcTargetGroupAttachment", new AddApplicationTargetGroupsProps
            {
                TargetGroups = new[] { targetGroup },
            });
            listener.Node.AddDependency(grpcTargetGroupResource);

            return(targetGroup);
        }
Пример #6
0
        internal InfraStack(Construct scope, string id, CustomStackProps props = null)
            : base(scope, id, props)
        {
            var vpc = props.Vpc;

            var cluster = new Cluster(this, "Cluster",
                                      new ClusterProps
            {
                Vpc         = vpc,
                ClusterName = Globals.GetDeployEnvironment(this).PutEnvNamePrefixWithDash("Cluster")
            });

            var albSecurityGroup = new SecurityGroup(this, "AlbSecurityGroup",
                                                     new SecurityGroupProps
            {
                Vpc = vpc,
                AllowAllOutbound = true
            });

            albSecurityGroup.AddIngressRule(Peer.AnyIpv4(), Port.Tcp(80));

            var alb = new ApplicationLoadBalancer(this, "ALB",
                                                  new ApplicationLoadBalancerProps
            {
                Vpc            = vpc,
                InternetFacing = true,
                Http2Enabled   = true,
                IdleTimeout    = Duration.Seconds(60),
                IpAddressType  = IpAddressType.IPV4,
                SecurityGroup  = albSecurityGroup
            });

            var webApiServiceSecurityGroup = new SecurityGroup(this, "WebApiServiceSecurityGroup",
                                                               new SecurityGroupProps
            {
                Vpc = vpc,
                AllowAllOutbound = true
            });

            webApiServiceSecurityGroup.AddIngressRule(albSecurityGroup, Port.Tcp(80));

            var appListener = alb.AddListener("AppListener",
                                              new BaseApplicationListenerProps
            {
                Port          = 80,
                Protocol      = ApplicationProtocol.HTTP,
                DefaultAction = ListenerAction.FixedResponse(404,
                                                             new FixedResponseOptions
                {
                    ContentType = "text/plain",
                    MessageBody = "This is not here..."
                })
            });

            new CfnOutput(this, "ClusterName",
                          new CfnOutputProps
            {
                ExportName = Globals.GetDeployEnvironment(this).PutEnvNamePrefixWithDash("ClusterName"),
                Value      = cluster.ClusterName
            });

            new CfnOutput(this, "WebApiServiceSecurityGroupId",
                          new CfnOutputProps
            {
                ExportName = Globals.GetDeployEnvironment(this).PutEnvNamePrefixWithDash("WebApiServiceSecurityGroupId"),
                Value      = albSecurityGroup.SecurityGroupId
            });

            new CfnOutput(this, "AppListenerArn",
                          new CfnOutputProps
            {
                ExportName = Globals.GetDeployEnvironment(this).PutEnvNamePrefixWithDash("AppListenerArn"),
                Value      = appListener.ListenerArn
            });
        }
        internal AppdeploymentStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            #region Application hosting resources

            var vpc = new Vpc(this, "appVpc", new VpcProps
            {
                MaxAzs = 3
            });

            var image = new LookupMachineImage(new LookupMachineImageProps
            {
                // maps to "Amazon Linux 2 with .NET Core 3.0 and Mono 5.18"
                Name   = "amzn2-ami-hvm-2.0.*-x86_64-gp2-mono-*",
                Owners = new [] { "amazon" }
            });

            var userData = UserData.ForLinux();
            userData.AddCommands(new string[]
            {
                "sudo yum install -y httpd",
                "sudo systemctl start httpd",
                "sudo systemctl enable httpd"
            });

            var scalingGroup = new AutoScalingGroup(this, "appASG", new AutoScalingGroupProps
            {
                Vpc              = vpc,
                InstanceType     = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.MEDIUM),
                MachineImage     = image,
                MinCapacity      = 1,
                MaxCapacity      = 4,
                AllowAllOutbound = true,
                UserData         = userData
            });

            var alb = new ApplicationLoadBalancer(this, "appLB", new ApplicationLoadBalancerProps
            {
                Vpc            = vpc,
                InternetFacing = true
            });

            var albListener = alb.AddListener("Port80Listener", new BaseApplicationListenerProps
            {
                Port = 80
            });

            albListener.AddTargets("Port80ListenerTargets", new AddApplicationTargetsProps
            {
                Port    = 80,
                Targets = new [] { scalingGroup }
            });

            albListener.Connections.AllowDefaultPortFromAnyIpv4("Open access to port 80");

            scalingGroup.ScaleOnRequestCount("ScaleOnModestLoad", new RequestCountScalingProps
            {
                TargetRequestsPerSecond = 1
            });

            #endregion

            #region CI/CD resources

            var _sourceOutput = new Artifact_("Source");
            var _buildOutput  = new Artifact_("Build");

            var build = new PipelineProject(this, "CodeBuild", new PipelineProjectProps
            {
                // relative path to sample app's file (single html page for now)
                BuildSpec   = BuildSpec.FromSourceFilename("talk-demos/appdeployment/SimplePage/buildspec.yml"),
                Environment = new BuildEnvironment
                {
                    BuildImage = LinuxBuildImage.AMAZON_LINUX_2_2
                },
            });

            var appDeployment = new ServerApplication(this, "appDeployment");
            // we will use CodeDeploy's default one-at-a-time deployment mode as we are
            // not specifying a deployment config
            var deploymentGroup = new ServerDeploymentGroup(this, "appDeploymentGroup", new ServerDeploymentGroupProps
            {
                Application  = appDeployment,
                InstallAgent = true,
                AutoRollback = new AutoRollbackConfig
                {
                    FailedDeployment = true
                },
                AutoScalingGroups = new [] { scalingGroup }
            });

            // SecretValue.SsmSecure is not currently supported for setting OauthToken,
            // and haven't gotten the SecretsManager approach to work either so
            // resorting to keeping my token in an environment var for now!
            var oauthToken = SecretValue.PlainText(System.Environment.GetEnvironmentVariable("GitHubPersonalToken"));

            var pipeline = new Pipeline(this, "sampleappPipeline", new PipelineProps
            {
                Stages = new StageProps[]
                {
                    new StageProps
                    {
                        StageName = "Source",
                        Actions   = new IAction[]
                        {
                            new GitHubSourceAction(new GitHubSourceActionProps
                            {
                                ActionName = "GitHubSource",
                                Branch     = "master",
                                Repo       = this.Node.TryGetContext("repo-name").ToString(),
                                Owner      = this.Node.TryGetContext("repo-owner").ToString(),
                                OauthToken = oauthToken,
                                Output     = _sourceOutput
                            })
                        }
                    },

                    new StageProps
                    {
                        StageName = "Build",
                        Actions   = new IAction[]
                        {
                            new CodeBuildAction(new CodeBuildActionProps
                            {
                                ActionName = "Build-app",
                                Project    = build,
                                Input      = _sourceOutput,
                                Outputs    = new Artifact_[] { _buildOutput },
                                RunOrder   = 1
                            })
                        }
                    },

                    new StageProps
                    {
                        StageName = "Deploy",
                        Actions   = new IAction[]
                        {
                            new CodeDeployServerDeployAction(new CodeDeployServerDeployActionProps
                            {
                                ActionName      = "Deploy-app",
                                Input           = _buildOutput,
                                RunOrder        = 2,
                                DeploymentGroup = deploymentGroup
                            })
                        }
                    }
                }
            });

            #endregion
        }
Пример #8
0
        public CdkExampleStack(Construct parent, string id, IStackProps props) : base(parent, id, props)
        {
            var vpc = new Vpc(this, "MainVPC", new VpcProps
            {
                Cidr = "192.168.0.0/16"
            });

            var loadBalancer = new ApplicationLoadBalancer(this, "PublicALB", new ApplicationLoadBalancerProps
            {
                InternetFacing = true,
                Vpc            = vpc
            });

            var listener = loadBalancer.AddListener("MyListener", new ApplicationListenerProps
            {
                Port = 80
            });

            var userData = UserData.ForLinux(new LinuxUserDataOptions
            {
                Shebang = "#!/bin/bash"
            });

            userData.AddCommands(
                "yum update -y",
                "yum install httpd -y",
                "echo \"Hello World\" >> /var/www/html/index.html",
                "service httpd start",
                "chkconfig httpd on");


            var ec2SG = new SecurityGroup(this, "Ec2SecurityGroup", new SecurityGroupProps
            {
                Vpc = vpc,
                SecurityGroupName = "Ec2SG"
            });

            ec2SG.Connections.AllowFrom(loadBalancer, Port.Tcp(80), "FROM ALB");

            var instanceIds = new List <string>();

            for (var ix = 0; ix < vpc.PrivateSubnets.Length; ix++)
            {
                var instance = new Instance_(this, $"Instance-{ix}", new InstanceProps
                {
                    InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.MICRO),
                    VpcSubnets   = new SubnetSelection()
                    {
                        SubnetType = SubnetType.PRIVATE
                    },
                    AvailabilityZone = vpc.PrivateSubnets[ix].AvailabilityZone,
                    Vpc           = vpc,
                    MachineImage  = new AmazonLinuxImage(),
                    UserData      = userData,
                    KeyName       = "test-cdk",
                    SecurityGroup = ec2SG
                });

                instanceIds.Add(instance.InstanceId);
            }

            listener.AddTargets("Targets", new AddApplicationTargetsProps
            {
                Port    = 80,
                Targets = instanceIds.Select(i => new InstanceIdTarget(i, 80)).ToArray()
            });
        }
Пример #9
0
        private void ConfigureLoadBalancer(Configuration settings)
        {
            if (AppVpc == null)
            {
                throw new InvalidOperationException($"{nameof(AppVpc)} has not been set. The {nameof(ConfigureVpc)} method should be called before {nameof(ConfigureLoadBalancer)}");
            }
            if (EcsCluster == null)
            {
                throw new InvalidOperationException($"{nameof(EcsCluster)} has not been set. The {nameof(ConfigureECSClusterAndService)} method should be called before {nameof(ConfigureLoadBalancer)}");
            }
            if (AppFargateService == null)
            {
                throw new InvalidOperationException($"{nameof(AppFargateService)} has not been set. The {nameof(ConfigureECSClusterAndService)} method should be called before {nameof(ConfigureLoadBalancer)}");
            }

            if (settings.LoadBalancer.CreateNew)
            {
                ServiceLoadBalancer = new ApplicationLoadBalancer(this, nameof(ServiceLoadBalancer), InvokeCustomizeCDKPropsEvent(nameof(ServiceLoadBalancer), this, new ApplicationLoadBalancerProps
                {
                    Vpc            = AppVpc,
                    InternetFacing = true
                }));

                LoadBalancerListener = ServiceLoadBalancer.AddListener(nameof(LoadBalancerListener), InvokeCustomizeCDKPropsEvent(nameof(LoadBalancerListener), this, new ApplicationListenerProps
                {
                    Protocol = ApplicationProtocol.HTTP,
                    Port     = 80,
                    Open     = true
                }));

                ServiceTargetGroup = LoadBalancerListener.AddTargets(nameof(ServiceTargetGroup), InvokeCustomizeCDKPropsEvent(nameof(ServiceTargetGroup), this, new AddApplicationTargetsProps
                {
                    Protocol            = ApplicationProtocol.HTTP,
                    DeregistrationDelay = Duration.Seconds(settings.LoadBalancer.DeregistrationDelayInSeconds)
                }));
            }
            else
            {
                ServiceLoadBalancer = ApplicationLoadBalancer.FromLookup(this, nameof(ServiceLoadBalancer), InvokeCustomizeCDKPropsEvent(nameof(ServiceLoadBalancer), this, new ApplicationLoadBalancerLookupOptions
                {
                    LoadBalancerArn = settings.LoadBalancer.ExistingLoadBalancerArn
                }));

                LoadBalancerListener = ApplicationListener.FromLookup(this, nameof(LoadBalancerListener), InvokeCustomizeCDKPropsEvent(nameof(LoadBalancerListener), this, new ApplicationListenerLookupOptions
                {
                    LoadBalancerArn = settings.LoadBalancer.ExistingLoadBalancerArn,
                    ListenerPort    = 80
                }));

                ServiceTargetGroup = new ApplicationTargetGroup(this, nameof(ServiceTargetGroup), InvokeCustomizeCDKPropsEvent(nameof(ServiceTargetGroup), this, new ApplicationTargetGroupProps
                {
                    Port = 80,
                    Vpc  = EcsCluster.Vpc,
                }));


                var addApplicationTargetGroupsProps = new AddApplicationTargetGroupsProps
                {
                    TargetGroups = new[] { ServiceTargetGroup }
                };

                if (settings.LoadBalancer.ListenerConditionType != LoadBalancerConfiguration.ListenerConditionTypeEnum.None)
                {
                    addApplicationTargetGroupsProps.Priority = settings.LoadBalancer.ListenerConditionPriority;
                }

                if (settings.LoadBalancer.ListenerConditionType == LoadBalancerConfiguration.ListenerConditionTypeEnum.Path)
                {
                    if (settings.LoadBalancer.ListenerConditionPathPattern == null)
                    {
                        throw new ArgumentNullException("Listener condition type was set to \"Path\" but no value was set for the \"TargetPathPattern\"");
                    }
                    addApplicationTargetGroupsProps.Conditions = new ListenerCondition[]
                    {
                        ListenerCondition.PathPatterns(new [] { settings.LoadBalancer.ListenerConditionPathPattern })
                    };
                }

                LoadBalancerListener.AddTargetGroups("AddTargetGroup", InvokeCustomizeCDKPropsEvent("AddTargetGroup", this, addApplicationTargetGroupsProps));
            }

            // Configure health check for ALB Target Group
            var healthCheck = new Amazon.CDK.AWS.ElasticLoadBalancingV2.HealthCheck();

            if (settings.LoadBalancer.HealthCheckPath != null)
            {
                var path = settings.LoadBalancer.HealthCheckPath;
                if (!path.StartsWith("/"))
                {
                    path = "/" + path;
                }
                healthCheck.Path = path;
            }
            if (settings.LoadBalancer.HealthCheckInternval.HasValue)
            {
                healthCheck.Interval = Duration.Seconds(settings.LoadBalancer.HealthCheckInternval.Value);
            }
            if (settings.LoadBalancer.HealthyThresholdCount.HasValue)
            {
                healthCheck.HealthyThresholdCount = settings.LoadBalancer.HealthyThresholdCount.Value;
            }
            if (settings.LoadBalancer.UnhealthyThresholdCount.HasValue)
            {
                healthCheck.UnhealthyThresholdCount = settings.LoadBalancer.UnhealthyThresholdCount.Value;
            }

            ServiceTargetGroup.ConfigureHealthCheck(healthCheck);

            ServiceTargetGroup.AddTarget(AppFargateService);
        }