private static void BasicDatabaseInfra(IVpc vpc)
 {
     if (vpc == null)
     {
         throw new ArgumentException("The VPC provided to create the database is not valid");
     }
 }
Пример #2
0
        public static InstanceProps InstanceProps(IVpc vpc, ISubnet subnet, IRole role, ISecurityGroup securityGroup, IvrInstanceProps props, string privateIpAddress = null)
        {
            var instanceProps = new InstanceProps
            {
                Vpc        = vpc,
                VpcSubnets = new SubnetSelection
                {
                    //SubnetType = SubnetType.PUBLIC,
                    //SubnetGroupName = subnetGroupName,
                    Subnets = new ISubnet[] { subnet },
                },
                InstanceType = InstanceType.Of(props.InstanceClass, props.InstanceSize),
                MachineImage = new WindowsImage(props.WindowsVersion),
                BlockDevices = new BlockDevice[] {
                    new BlockDevice {
                        DeviceName = "/dev/sda1",
                        Volume     = BlockDeviceVolume.Ebs(props.VolumeSize, new EbsDeviceOptions {
                            VolumeType = props.VolumeType,
                            Encrypted  = true,
                        }),
                    },
                },
                Role          = role,
                SecurityGroup = securityGroup,
            };

            if (!string.IsNullOrWhiteSpace(privateIpAddress))
            {
                instanceProps.PrivateIpAddress = privateIpAddress;
            }
            return(instanceProps);
        }
Пример #3
0
 internal HelloWorldHandler(Construct scope, string id, IVpc vpc, RustlambProps props) : base(scope, id, CreateProps(vpc, props))
 {
     this.Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AmazonDynamoDBFullAccess"));
     // Add event sources here, pass in other items created, tables, streams, queues, etc.
     // Or setup a API Gateway integration
     var logGroup = this.CreateLogGroup();
 }
        private void BasicDatabaseInfraWithHardcodedPassword(IVpc vpc,
                                                             SubnetType subnetType, string defaultSubnetDomainSeparator, string subnets, out ISubnetSelection subnetSelection)
        {
            if (vpc == null)
            {
                throw new ArgumentException($"The VPC provided to create the database is not valid");
            }

            subnetSelection = AwsCdkVpcHandler.GetVpcSubnetSelection(vpc, subnets, defaultSubnetDomainSeparator, subnetType);
        }
Пример #5
0
        private SecurityGroup createLambdaSecurityGroup(IVpc theVpc)
        {
            var sg = new SecurityGroup(this, "LambdaSG", new SecurityGroupProps()
            {
                Vpc = theVpc,
                SecurityGroupName = "LambdaSG",
            });

            return(sg);
        }
Пример #6
0
        internal Cluster AddECSCluster(string id, IVpc vpc)
        {
            var cluster = new Cluster(this, $"{id}-ecs-cluster", new ClusterProps
            {
                ClusterName       = $"{id}",
                ContainerInsights = false,
                Vpc = vpc,
            });

            return(cluster);
        }
Пример #7
0
        public ISecurityGroup Create(string identification, string groupName, IVpc vpc, bool allowAllOutbound = false, bool disableInlineRules = false)
        {
            var securityGroup = new SecurityGroup(Scope, identification, new SecurityGroupProps
            {
                AllowAllOutbound  = allowAllOutbound,
                SecurityGroupName = groupName,
                Vpc = vpc,
                DisableInlineRules = disableInlineRules
            });

            TagHandler.LogTag($"{ApplicationName}{EnvironmentName}{groupName}SecurityGroup", securityGroup);
            return(securityGroup);
        }
Пример #8
0
 private static FunctionProps CreateProps(IVpc vpc, RustlambProps props)
 {
     return(new FunctionProps
     {
         Vpc = vpc,
         Runtime = Runtime.PROVIDED,
         Code = Code.FromAsset("./rustlamb_hello_world/target", new AssetOptions {
         }),
         Handler = "bootstrap",
         VpcSubnets = new SubnetSelection {
             SubnetType = SubnetType.PRIVATE
         },
     });
 }
        private void BasicDatabaseInfra(IVpc vpc, string secretName, string securityId, string securityGroupId, SubnetType subnetType, string defaultSubnetDomainSeparator, string subnets, out ISecurityGroup securityGroup, out ISecret secret, out ISubnetSelection subnetSelection)                         //NOSONAR number of params
        {
            if (vpc == null)
            {
                throw new ArgumentException("The VPC provided to create the database is not valid");
            }

            securityGroup = AwsSecurityGroupHandler.Locate(securityId, securityGroupId);

            if (securityGroup == null)
            {
                throw new ArgumentException($"The Security group id {securityGroupId} provided to create the database is not valid");
            }

            secret          = AwsCdkSecretHandler.Create(secretName);
            subnetSelection = AwsCdkVpcHandler.GetVpcSubnetSelection(vpc, subnets, defaultSubnetDomainSeparator, subnetType);
        }
Пример #10
0
        public ISubnetSelection GetVpcSubnetSelection(IVpc vpc, string subnetDomainToCheck, string defaultSubnetDomainSeparator = ",", SubnetType defaultSubnetType = SubnetType.PRIVATE)
        {
            if (string.IsNullOrEmpty(subnetDomainToCheck))
            {
                return new SubnetSelection {
                           SubnetType = defaultSubnetType
                }
            }
            ;

            var subnetIds = subnetDomainToCheck.Split(defaultSubnetDomainSeparator).ToList();

            return(new SubnetSelection {
                Subnets = vpc.PrivateSubnets.Where(x => subnetIds.Contains(x.SubnetId)).ToArray()
            });
        }
    }
        public NetworkStack(Construct parent, string id, IStackProps props) : base(parent, id, props)
        {
            var ingressSubnet = new SubnetConfiguration
            {
                Name       = "Ingress",
                SubnetType = SubnetType.PUBLIC,
                CidrMask   = 24,
            };

            var applicationSubnet = new SubnetConfiguration
            {
                Name       = "Application",
                SubnetType = SubnetType.PRIVATE,
                CidrMask   = 24,
            };

            var databaseSubnet = new SubnetConfiguration
            {
                Name       = "Database",
                SubnetType = SubnetType.ISOLATED,
                CidrMask   = 24,
            };

            Vpc = new Vpc(
                this,
                "Primary",
                new VpcProps
            {
                Cidr                = "10.1.0.0/16",
                MaxAzs              = 2,
                NatGateways         = 1,
                SubnetConfiguration = new ISubnetConfiguration[]
                {
                    ingressSubnet,
                    applicationSubnet,
                    databaseSubnet,
                },
            });

            PrintPublicSubnetIds();
            PrintPrivateSubnetIds();
            PrintIsolatedSubnetIds();
        }
Пример #12
0
        internal Amazon.CDK.AWS.ServiceDiscovery.PrivateDnsNamespace CreateCloudMapNamespace(string id, IVpc vpc)
        {
            var privateNamespace = new PrivateDnsNamespace(this, $"{id}-cloudmap-private-namespace", new PrivateDnsNamespaceProps
            {
                Description = $"Cloudmap Namespace for {id}",
                Vpc         = vpc,
                Name        = $"{id}"
            });

            return(privateNamespace);
        }
Пример #13
0
        public IvrStack(Construct scope, string stackId, StackProps stackProps, IvrSiteSchema schema, IEnumerable <SecurityGroupRule> securityGroupRules) : base(scope, stackId, stackProps)
        {
            IVpc vpc             = null;
            var  MaxIpsPerSubnet = IvrVpcProps.MaxIpsPerSubnet;

            if (!string.IsNullOrWhiteSpace(schema.VpcName))
            {
                vpc = Vpc.FromLookup(this, "$VPC", new VpcLookupOptions {
                    VpcName = schema.VpcName,
                });                                                                                     // will error if not found
                //MaxIpsPerSubnet = ???;
            }
            else if (!string.IsNullOrWhiteSpace(schema.VpcId))
            {
                vpc = Vpc.FromLookup(this, "$VPC", new VpcLookupOptions {
                    VpcId = schema.VpcId,
                });                                                                                 // will error if not found
                //MaxIpsPerSubnet = ???;
            }
            else if (null != schema.VpcProps)
            {
                // use provided props to create brand new VPC
                vpc = new IvrVpc(this, $"VPC", schema.VpcProps);
            }

            if (schema.AddVpcS3Gateway)
            {
                var s3gw = new GatewayVpcEndpoint(this, $"S3GW", new GatewayVpcEndpointProps
                {
                    Vpc     = vpc,
                    Service = GatewayVpcEndpointAwsService.S3,
                    Subnets = new SubnetSelection[] { new SubnetSelection {
                                                          SubnetType = SubnetType.PUBLIC,
                                                      } },
                });
            }

            var role = new Role(this, "IVR", new RoleProps
            {
                AssumedBy      = new ServicePrincipal("ec2.amazonaws.com"),
                InlinePolicies = new IvrInlinePolicies(stackProps.Env.Account, stackId, schema),
            });

            // Configure inbound security for RDP (and more?)
            var securityGroup = new SecurityGroup(this, $"Ingress", new SecurityGroupProps
            {
                Vpc = vpc,
                AllowAllOutbound = schema.AllowAllOutbound,
            });

            securityGroupRules.ForEach(rule => securityGroup.WithSecurityGroupRule(rule));
            if (schema.AllowAllIntranet)
            {
                securityGroup.WithSecurityGroupRule(new IngressRule(Peer.Ipv4($"{vpc.VpcCidrBlock}"), Port.AllTraffic()).WithDescription($"All intranet traffic"));
            }

            // Finally - create our instances!
            var hosts = new List <HostInstance>();

            for (var subnetIndex = 0; ++subnetIndex <= Math.Min(vpc.PublicSubnets.Length, schema.MaxSubnets);)
            {
                var hostIndexInSubnet = 0;
                foreach (var group in schema.HostGroups)
                {
                    var numberOfHosts = Math.Min(group.HostCount, MaxIpsPerSubnet);
                    if (numberOfHosts != group.HostCount)
                    {
                        Console.WriteLine($"Group({group.Name}) host count changed from {group.HostCount} to {numberOfHosts}");
                        group.HostCount = numberOfHosts;
                    }
                    var instanceProps = IvrInstanceProps.InstanceProps(vpc, vpc.PublicSubnets[subnetIndex - 1], role, securityGroup, group.InstanceProps);
                    for (var hostCount = 0; ++hostCount <= numberOfHosts; ++hostIndexInSubnet)
                    {
                        var hostName         = $"{schema.HostNamePrefix}{subnetIndex}{hostIndexInSubnet:00}";
                        var hostPrimingProps = new HostPrimingProps
                        {
                            HostName           = hostName.AsWindowsComputerName(), // must fit into 15 chars
                            WorkingFolder      = $"{stackId}".AsWindowsFolder(),
                            AwsAccount         = stackProps.Env.Account,
                            AwsRoleName        = role.RoleName,
                            RdpProps           = schema.RdpProps,
                            EC2Users           = schema.EC2Users,
                            DownloadAndInstall = group.DownloadAndInstall,
                            S3iArgs            = $"{group.InstallS3i} --verbose",
                        };
                        var hostCommands = HostPriming.PrimeForS3i(hostPrimingProps)
                                           .WithFirewallAllowInbound($"{vpc.VpcCidrBlock}");
                        hostCommands.WithRenameAndRestart(hostPrimingProps.HostName);
                        instanceProps.KeyName  = schema.KeyPairName;
                        instanceProps.UserData = hostCommands.UserData;
                        hosts.Add(new HostInstance
                        {
                            Group    = group,
                            Instance = new Instance_(this, hostName.AsCloudFormationId(), instanceProps),
                        });
                    }
                }
            }
            // associate pre-allocated EIPs
            var preAllocatedEIPs    = schema.PreAllocatedElasticIPs?.SelectMany(s => s.Csv()).ToList() ?? new List <string> {
            };
            var hostsThatRequireEIP = hosts.Where(h => h.Group.UsePreAllocatedElasticIPs).ToList();

            if (preAllocatedEIPs.Count < hostsThatRequireEIP.Count)
            {
                throw new ArgumentException($"Pre-Allocated Elastic IPs needed: {hostsThatRequireEIP.Count()}, but only {preAllocatedEIPs.Count()} configured in schema.{nameof(IvrSiteSchema.PreAllocatedElasticIPs)}");
            }
            var elasticIPAssociations = hostsThatRequireEIP.Zip(preAllocatedEIPs, (h, a) =>
            {
                return(new CfnEIPAssociation(this, $"EIPA{h.Instance.InstancePrivateIp}".AsCloudFormationId(), new CfnEIPAssociationProps
                {
                    AllocationId = a,
                    InstanceId = h.Instance.InstanceId,
                }));
            }).ToList();    // execute LINQ now

            // We have schema.Domain registered in advance
            if (!string.IsNullOrWhiteSpace(schema.HostedZoneDomain))
            {
                var theZone = HostedZone.FromLookup(this, $"{stackId}_Zone_", new HostedZoneProviderProps
                {
                    DomainName = schema.HostedZoneDomain,
                    //Comment = "HostedZone created by Route53 Registrar",
                });
                // assign new Elastic IPs as needed
                if (!string.IsNullOrWhiteSpace(schema.SubdomainEIPs))
                {
                    var newElasticIPs = hosts.Where(h => h.Group.AllocateNewElasticIPs).Select(h =>
                    {
                        return(new CfnEIP(this, $"EIP{h.Instance.InstancePrivateIp}".AsCloudFormationId(), new CfnEIPProps
                        {
                            // 'standard' or 'vpc': https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html#cfn-ec2-eip-domain
                            Domain = "vpc",
                            InstanceId = h.Instance.InstanceId,
                        }));
                    }).ToList();   // collect them now to prevent LINQ side effects
                    if (newElasticIPs.Any())
                    {
                        // Register public Elastic IPs
                        var arNewPublic = new ARecord(this, $"ARecord_Public_NewAlloc".AsCloudFormationId(), new ARecordProps
                        {
                            Zone       = theZone,
                            RecordName = $"{schema.SubdomainEIPs}.{theZone.ZoneName}",
                            Target     = RecordTarget.FromValues(newElasticIPs.Select(eip => eip.Ref).ToArray()),
                            Ttl        = Duration.Seconds(300),
                        });
                    }
                    else if (elasticIPAssociations.Any())
                    {
                        // Register public Elastic IPs

                        /*
                         * var arPrePublic = new ARecord(this, $"ARecord_Public_PreAlloc".AsCloudFormationId(), new ARecordProps
                         * {
                         *  Zone = theZone,
                         *  RecordName = $"{schema.SubdomainEIPs}.{theZone.ZoneName}",
                         *  Target = RecordTarget.FromValues(elasticIPAssociations.Select(eipa => eipa.Ref).ToArray()), // ***** how to do that?
                         *  Ttl = Duration.Seconds(300),
                         * });
                         */
                        foreach (var a in elasticIPAssociations)
                        {
                            Console.WriteLine($"Pre-Allocated Elastic IP Associations: {a.AllocationId}/{a.InstanceId}, {a.Eip}/{a.PrivateIpAddress}, {a.Ref} - please put it to {schema.SubdomainEIPs}.{theZone.ZoneName} ARecord manually");
                        }
                    }
                }
                if (0 < hosts.Count && !string.IsNullOrWhiteSpace(schema.SubdomainHosts))
                {
                    // Register private IPs (never changing, as opposed to public - which change on stop/start) addresses of all hosts
                    var arPrivate = new ARecord(this, $"ARecord_Private_".AsCloudFormationId(), new ARecordProps
                    {
                        Zone       = theZone,
                        RecordName = $"{schema.SubdomainHosts}.{theZone.ZoneName}",
                        Target     = RecordTarget.FromIpAddresses(hosts.Select(h => h.Instance.InstancePrivateIp).ToArray()),
                        Ttl        = Duration.Seconds(300),
                    });
                }
                //throw new Exception();
            }
        }
Пример #14
0
 public IFunctionProps CreateLambdaProperties(string codeFilePath, string lambdaHandler, IRole lambdaRole, Runtime runtime, string lambdaName, IVpc vpc, ISecurityGroup securityGroup, ISubnet[] subnets, double memorySize = 512, int timeOutSeconds = 30, IDictionary <string, string> environmentVariables = null)
 {
     return(HandlerResources.AwsCdkLambdaHandler.CreateLambdaProperties(codeFilePath, lambdaHandler, lambdaRole, runtime, lambdaName, vpc, securityGroup, subnets, memorySize, timeOutSeconds, environmentVariables));
 }
 public IFunctionProps CreateLambdaProperties(string codeFilePath, string lambdaHandler, IRole lambdaRole, Runtime runtime, string lambdaName, IVpc vpc, ISecurityGroup securityGroup, ISubnet[] subnets, double memorySize = 512, int timeOutSeconds = 30, IDictionary <string, string> environmentVariables = null)
 {
     return(new FunctionProps
     {
         Code = Code.FromAsset(codeFilePath),
         Handler = lambdaHandler,
         Runtime = runtime,
         MemorySize = memorySize,
         Timeout = Duration.Seconds(timeOutSeconds),
         FunctionName = lambdaName,
         Role = lambdaRole,
         Vpc = vpc,
         SecurityGroups = new ISecurityGroup[]
         {
             securityGroup
         },
         VpcSubnets = new SubnetSelection
         {
             Subnets = subnets
         },
         Environment = environmentVariables
     });
 }
Пример #16
0
 public ICluster CreateEC2Cluster(string id, string clusterName, IVpc vpc)
 {
     return(HandlerResources.AwsCdkEcsHandler.CreateEC2Cluster(id, clusterName, vpc));
 }
        public IDatabaseInstance CreateDatabase(DeputyBase databaseEngineVersion, string identification, string databaseName, double?port, string userName, string secretName, StorageType storageType, InstanceClass instanceClass, InstanceSize instanceSize, IVpc vpc, string securityId, string securityGroupId, string parameterGroupId = null, IRole[] roles = null, double?allocatedStorageGb = 5, RemovalPolicy removalPolicy = RemovalPolicy.DESTROY, bool deleteAutomatedBackups = false, int backupRetentionDays = 1, bool deletionProtection = false, SubnetType subnetType = SubnetType.PRIVATE_ISOLATED, string defaultSubnetDomainSeparator = ",", string subnets = "", bool multiAZEnabled = true, bool autoMinorVersionUpgrade = false, bool?storageEncrypted = true)
        {
            BasicDatabaseInfra(vpc, secretName, securityId, securityGroupId, subnetType, defaultSubnetDomainSeparator, subnets, out var securityGroup, out var secret, out var subnetSelection);
            var engine = GetInstanceEngine(databaseEngineVersion);

            return(new DatabaseInstance(Scope, identification, new DatabaseInstanceProps
            {
                Engine = engine,
                RemovalPolicy = removalPolicy,
                DeletionProtection = deletionProtection,
                Credentials = Credentials.FromPassword(userName, secret.SecretValue),
                StorageType = storageType,
                DatabaseName = databaseName,
                Port = port,
                VpcSubnets = subnetSelection,
                Vpc = vpc,
                SecurityGroups = new[]
                {
                    securityGroup
                },
                DeleteAutomatedBackups = deleteAutomatedBackups,
                BackupRetention = Duration.Days(backupRetentionDays),
                AllocatedStorage = allocatedStorageGb,
                InstanceType = InstanceType.Of(instanceClass, instanceSize),
                ParameterGroup = CreateClusterParameterGroup(parameterGroupId, engine, roles),
                MultiAz = multiAZEnabled,
                AutoMinorVersionUpgrade = autoMinorVersionUpgrade,
                StorageEncrypted = storageEncrypted
            }));
        }
        /// <summary>
        /// AwsCdkDatabaseHandler
        /// </summary>
        /// <param name="databaseEngineVersion"></param>
        /// <param name="identification"></param>
        /// <param name="clusterIdentifier"></param>
        /// <param name="instanceIdentifierBase"></param>
        /// <param name="databaseName"></param>
        /// <param name="port"></param>
        /// <param name="instances"></param>
        /// <param name="userName"></param>
        /// <param name="secretName"></param>
        /// <param name="vpc"></param>
        /// <param name="instanceClass"></param>
        /// <param name="instanceSize"></param>
        /// <param name="securityId"></param>
        /// <param name="securityGroupId"></param>
        /// <param name="parameterGroupId"></param>
        /// <param name="roles"></param>
        /// <param name="storageEncrypted"></param>
        /// <param name="subnetType"></param>
        /// <param name="defaultSubnetDomainSeparator"></param>
        /// <param name="subnets"></param>
        /// <param name="removalPolicy"></param>
        /// <param name="backupRetentionDays"></param>
        /// <param name="deletionProtection"></param>
        public IDatabaseCluster CreateDatabaseCluster(DeputyBase databaseEngineVersion, string identification, string clusterIdentifier, string instanceIdentifierBase, string databaseName, double?port, double?instances, string userName, string secretName, IVpc vpc, InstanceClass instanceClass, InstanceSize instanceSize, string securityId, string securityGroupId, string parameterGroupId = null, IRole[] roles = null, bool storageEncrypted = true, SubnetType subnetType = SubnetType.PRIVATE_ISOLATED, string defaultSubnetDomainSeparator = ",", string subnets = "", RemovalPolicy removalPolicy = RemovalPolicy.DESTROY, int backupRetentionDays = 1, bool deletionProtection = false)
        {
            BasicDatabaseInfra(vpc, secretName, securityId, securityGroupId, subnetType, defaultSubnetDomainSeparator, subnets, out var securityGroup, out var secret, out var subnetSelection);
            var engine = GetClusterEngine(databaseEngineVersion);

            return(new DatabaseCluster(Scope, identification, new DatabaseClusterProps
            {
                ClusterIdentifier = clusterIdentifier,
                InstanceIdentifierBase = instanceIdentifierBase,
                Engine = engine,
                RemovalPolicy = removalPolicy,
                DeletionProtection = deletionProtection,
                Port = port,
                InstanceProps = new Amazon.CDK.AWS.RDS.InstanceProps
                {
                    InstanceType = InstanceType.Of(instanceClass, instanceSize),
                    VpcSubnets = subnetSelection,
                    Vpc = vpc,
                    SecurityGroups = new[]
                    {
                        securityGroup
                    }
                },
                StorageEncrypted = storageEncrypted,
                Instances = instances,
                Credentials = Credentials.FromPassword(userName, secret.SecretValue),
                DefaultDatabaseName = databaseName,
                ParameterGroup = CreateClusterParameterGroup(parameterGroupId, engine, roles),
                Backup = new BackupProps
                {
                    Retention = Duration.Days(backupRetentionDays)
                }
            }));
        }
        public IAutoScalingGroup Create(string id, string instanceName, string instanceType, string machineImageType, string machineAmiImage, IVpc vpc, bool allowAllOutbound, int minCapacity, int maxCapacity, int desiredCapacity, string region, ISecurityGroup securityGroup, string timeOutCreation, IRole role, ISubnet[] subnets, string keyPairName, bool enableProtectionFromScaleIn, List <BlockDevicesOptions> blockDevicesOptions, List <string> userData)
        {
            var result = CreateInstance(new AutoScalingGroupEntity
            {
                Id      = id,
                Vpc     = vpc,
                Subnets = subnets,
                AutoScalingGroupName = instanceName,
                InstanceType         = new InstanceType(instanceType),
                MachineImage         = GetMachineImage(machineImageType, new Dictionary <string, string> {
                    { region, machineAmiImage }
                }),
                AllowAllOutbound            = allowAllOutbound,
                MinCapacity                 = minCapacity,
                MaxCapacity                 = maxCapacity,
                DesiredCapacity             = desiredCapacity,
                SecurityGroup               = securityGroup,
                TimeOutCreation             = timeOutCreation,
                Role                        = role,
                KeyPairName                 = keyPairName,
                BlockDevices                = CreateBlockDevices(blockDevicesOptions),
                EnableProtectionFromScaleIn = enableProtectionFromScaleIn,
                UserData                    = userData
            });

            TagHandler.LogTag(ApplicationName + EnvironmentName + instanceName, result);
            return(result);
        }
        public INetworkTargetGroup CreateNetworkTargetGroup(string id, string name, double port, IVpc vpc, int healthCheckCount)
        {
            var targetGroup = new NetworkTargetGroup(Scope, id, new NetworkTargetGroupProps
            {
                Port            = port,
                TargetType      = TargetType.INSTANCE,
                TargetGroupName = name,
                Vpc             = vpc,
                HealthCheck     = new HealthCheck
                {
                    HealthyThresholdCount   = healthCheckCount,
                    UnhealthyThresholdCount = healthCheckCount,
                }
            });

            return(targetGroup);
        }
Пример #21
0
        private (FargateService, Amazon.CDK.AWS.ServiceDiscovery.IService) CreateService(string id,
                                                                                         string serviceName,
                                                                                         string branch,
                                                                                         IVpc vpc,
                                                                                         Cluster cluster,
                                                                                         PrivateDnsNamespace cloudMapNamespace,
                                                                                         string appMeshVirtualNodeName,
                                                                                         Mesh mesh,
                                                                                         IRole taskExecutionRole,
                                                                                         RepositoryImage envoyImage,
                                                                                         ContainerImage containerImage)
        {
            var taskDefinition = new TaskDefinition(this, $"{id}_{serviceName}-{branch}-task-definiton", new TaskDefinitionProps
            {
                Compatibility      = Compatibility.FARGATE,
                MemoryMiB          = "512",
                Cpu                = "256",
                ProxyConfiguration = new AppMeshProxyConfiguration(new AppMeshProxyConfigurationConfigProps()
                {
                    ContainerName = "envoy",
                    Properties    = new AppMeshProxyConfigurationProps()
                    {
                        AppPorts = new double[1] {
                            5000
                        },
                        ProxyIngressPort = 15000,
                        ProxyEgressPort  = 15001,
                        IgnoredUID       = 1337,
                        EgressIgnoredIPs = new string[2] {
                            "169.254.170.2", "169.254.169.254"
                        }
                    }
                }),
                Family        = $"{id}_{serviceName}-task-definition",
                ExecutionRole = taskExecutionRole
            });
            var envoyContainer = taskDefinition.AddContainer("envoy", new ContainerDefinitionOptions
            {
                User        = "******",
                Image       = envoyImage,
                Essential   = true,
                Environment = new Dictionary <string, string>
                {
                    { "APPMESH_VIRTUAL_NODE_NAME", $"mesh/{mesh.MeshName}/virtualNode/{appMeshVirtualNodeName}" }
                },
                HealthCheck = new Amazon.CDK.AWS.ECS.HealthCheck()
                {
                    Command     = new string[] { "CMD-SHELL", "curl -s http://localhost:9901/server_info | grep state | grep -q LIVE" },
                    Interval    = Duration.Seconds(5),
                    Timeout     = Duration.Seconds(2),
                    StartPeriod = Duration.Seconds(10),
                    Retries     = 3
                },
                MemoryLimitMiB = 500,
                Logging        = new AwsLogDriver(new AwsLogDriverProps()
                {
                    StreamPrefix = $"{id}_{serviceName}-{branch}-envoy",
                    LogRetention = RetentionDays.ONE_DAY
                }),
            });
            var container = taskDefinition.AddContainer($"{serviceName}-container", new ContainerDefinitionOptions()
            {
                Image   = containerImage,
                Logging = new AwsLogDriver(new AwsLogDriverProps()
                {
                    StreamPrefix = $"{id}_{serviceName}-{branch}-service",
                    LogRetention = RetentionDays.ONE_DAY
                }),
                Essential   = true,
                Environment = new Dictionary <string, string>
                {
                    { "BRANCH", branch },
                    { "APPMESH_NAMESPACE", cloudMapNamespace.PrivateDnsNamespaceName }
                }
            });

            container.AddPortMappings(new Amazon.CDK.AWS.ECS.PortMapping()
            {
                ContainerPort = 5000
            });
            container.AddContainerDependencies(new ContainerDependency()
            {
                Condition = ContainerDependencyCondition.HEALTHY,
                Container = envoyContainer
            });
            // Cloudmap will append the namespace to the dns entry in R53.
            // We're explicitly checking for master here because for service to service lookups to go via the envoy proxy, the DNS name must resolve.
            // see https://github.com/aws/aws-app-mesh-roadmap/issues/65
            // i.e I want the ping service to call http://pong-service.{namespace}:5000/ and for this to be routed correctly by the proxy.
            // If you create the fargate task with cloudmap service integration with a more specific (branched) DNS name then pong-service.{namespace} r53 entry will never be created
            // and routing doesn't work through envoy.
            var dnsName = $"{serviceName}-service{(branch == "master" ? "" : "-" + branch)}";
            var sg      = new SecurityGroup(this, $"{id}_{serviceName}-{branch}-sg", new SecurityGroupProps()
            {
                AllowAllOutbound  = true,
                SecurityGroupName = $"{id}_{serviceName}-{branch}-sg",
                Vpc = vpc,
            });

            sg.AddIngressRule(Peer.AnyIpv4(), new Port(new PortProps()
            {
                Protocol = Amazon.CDK.AWS.EC2.Protocol.TCP, FromPort = 5000, ToPort = 5000, StringRepresentation = "tcp:5000:5000"
            }), "allow access from outside.");
            var fargateService = new Amazon.CDK.AWS.ECS.FargateService(this, $"{serviceName}-{branch}-service", new FargateServiceProps
            {
                ServiceName    = $"{serviceName}-{branch}-service",
                AssignPublicIp = true,
                Cluster        = cluster,
                TaskDefinition = taskDefinition,
                VpcSubnets     = new SubnetSelection()
                {
                    Subnets = vpc.PublicSubnets
                },
                CloudMapOptions = new CloudMapOptions()
                {
                    Name              = dnsName,
                    DnsRecordType     = DnsRecordType.A,
                    CloudMapNamespace = cloudMapNamespace
                },
                SecurityGroup = sg
            });

            return(fargateService, fargateService.CloudMapService);
        }
Пример #22
0
 public ISecurityGroup AddSecurityGroup(string identification, string securityGroupName, bool allowGroupAllOutbound, IPeer egressPeer, Port egreessPort, IPeer ingressPeer, Port ingressPort, IVpc vpcId)
 {
     return(AwsSecurityGroupHandler.Create(identification, securityGroupName, allowGroupAllOutbound, vpcId, ingressPeer, ingressPort, egressPeer, egreessPort));
 }
Пример #23
0
 public IDatabaseCluster AddDatabase(AuroraPostgresEngineVersion databaseEngineVersion, string identification, string clusterIdentifier, string instanceIdentifierBase, string databaseName, double?port, double?instances, string userName, string secretName, IVpc vpc, InstanceClass instanceClass, InstanceSize instanceSize, string securityId, string securityGroupId, string parameterGroupId = null, IRole[] roles = null, bool storageEncrypted = true, SubnetType subnetType = SubnetType.PRIVATE, string subnets = "", RemovalPolicy removalPolicy = RemovalPolicy.DESTROY, int backupRetentionDays = 1, bool deletionProtection = false, string defaultSubnetDomainSeparator = ",")
 {
     return(AwsCdkDatabaseHandler.CreateDatabaseCluster(databaseEngineVersion, identification, clusterIdentifier,
                                                        instanceIdentifierBase, databaseName, port, instances, userName, secretName, vpc, instanceClass,
                                                        instanceSize, securityId, securityGroupId, parameterGroupId, roles, storageEncrypted, subnetType, defaultSubnetDomainSeparator, subnets, removalPolicy, backupRetentionDays));
 }
Пример #24
0
 public INetworkTargetGroup AddNetworkTargetGroup(string id, string name, double port, IVpc vpc, int healthCheckCount)
 {
     return(HandlerResources.AwsCdkElbHandler.CreateNetworkTargetGroup(id, name, port, vpc, healthCheckCount));
 }
Пример #25
0
 public INetworkLoadBalancer CreateNetworkLoadBalancer(string loadBalancerId, bool crossZoneEnabled, bool deletionProtection, bool internetFacing, string loadBalancerName, IVpc vpc, ISubnet[] subnets = null, ISubnetMappingProperty[] subnetMappingProperties = null) //NOSONAR number of params
 {
     return(HandlerResources.AwsCdkNetworkLoadBalancerHandler.Create(loadBalancerId, crossZoneEnabled, deletionProtection, internetFacing, loadBalancerName, vpc, subnets, subnetMappingProperties));
 }
Пример #26
0
        private void GetDatabaseResources(DatabaseOptions databaseOption, out double?databasePort, out IVpc vpc, out ISecurityGroup securityGroup, out ISubnetGroup subnetGroup, out bool deletionProtection, out Duration enchancedMonitoringInterval, out ISecret passwordSecret, out IParameterGroup parameterGroup)  //NOSONAR number of params
        {
            // Parse database port
            databasePort = ParseDatabasePort(databaseOption);

            // Locate vpc
            vpc = LocateVPC(databaseOption);

            // Locate security group
            securityGroup = LocateSecurityGroup(databaseOption);

            // Locate subnet group
            subnetGroup = LocateSubnetGroup(databaseOption);

            // Locate parameter group
            parameterGroup = LocateParameterGroup(databaseOption);

            deletionProtection = databaseOption.DeletionProtection ?? false;

            enchancedMonitoringInterval = databaseOption.EnhancedMonitoringIntervalSeconds.HasValue ? Duration.Seconds(databaseOption.EnhancedMonitoringIntervalSeconds.Value) : null;

            passwordSecret = SetDatabasePassword(databaseOption);
        }
Пример #27
0
 public IDatabaseInstance AddDatabase(PostgresEngineVersion databaseEngineVersion, string identification, string databaseName, string userName, string password, StorageType storageType, InstanceClass instanceClass, InstanceSize instanceSize, IVpc vpc, string securityGroupId, string securityGroupName, string parameterGroupId = null, IRole[] roles = null, double?allocatedStorageGb = 5, RemovalPolicy removalPolicy = RemovalPolicy.DESTROY, bool deleteAutomatedBackups = false, int backupRetentionDays = 1, bool deletionProtection = false, SubnetType subnetType = SubnetType.PUBLIC, bool allowGroupAllOutbound = true, string defaultSubnetDomainSeparator = ",")
 {
     return(AwsCdkDatabaseHandler.CreateDatabase(databaseEngineVersion, identification, databaseName, userName, password, storageType,
                                                 instanceClass, instanceSize, vpc, securityGroupId, securityGroupName, parameterGroupId, roles, allocatedStorageGb, removalPolicy, deleteAutomatedBackups,
                                                 backupRetentionDays, deletionProtection, subnetType, defaultSubnetDomainSeparator));
 }
        public IDatabaseInstance CreateDatabase(DeputyBase databaseEngineVersion, string identification, string databaseName, double?port, string userName, ISecret passwordSecret, StorageType storageType, InstanceClass instanceClass, InstanceSize instanceSize, IVpc vpc, ISecurityGroup securityGroup, ISubnetGroup subnetGroup, IParameterGroup parameterGroup = null, double?allocatedStorageGb = 5, RemovalPolicy removalPolicy = RemovalPolicy.DESTROY, bool deleteAutomatedBackups = false, int backupRetentionDays = 1, bool deletionProtection = false, string[] logTypes = null, bool?storageEncrypted = null, bool?enableIamAuthentication = false, Duration enhancedMonitoringInterval = null, bool multiAZEnabled = true, bool autoMinorVersionUpgrade = false)
        {
            BasicDatabaseInfra(vpc);
            var engine = GetInstanceEngine(databaseEngineVersion);

            return(new DatabaseInstance(Scope, identification, new DatabaseInstanceProps
            {
                Engine = engine,
                RemovalPolicy = removalPolicy,
                DeletionProtection = deletionProtection,
                Credentials = Credentials.FromPassword(userName, passwordSecret.SecretValue),
                StorageType = storageType,
                DatabaseName = databaseName,
                Port = port,
                SubnetGroup = subnetGroup,
                Vpc = vpc,
                SecurityGroups = new[]
                {
                    securityGroup
                },
                DeleteAutomatedBackups = deleteAutomatedBackups,
                BackupRetention = Duration.Days(backupRetentionDays),
                AllocatedStorage = allocatedStorageGb,
                InstanceType = InstanceType.Of(instanceClass, instanceSize),
                ParameterGroup = parameterGroup,
                CloudwatchLogsExports = logTypes,
                StorageEncrypted = storageEncrypted,
                IamAuthentication = enableIamAuthentication,
                MonitoringInterval = enhancedMonitoringInterval,
                MultiAz = multiAZEnabled,
                AutoMinorVersionUpgrade = autoMinorVersionUpgrade
            }));
        }
Пример #29
0
        public ISecurityGroup Create(string identification, string groupName, bool allowGroupAllOutbound, IVpc vpc, IPeer ingressPeer, Port ingressPort, IPeer egressPeer, Port egressPort)
        {
            var securityGroup = new SecurityGroup(Scope, identification, new SecurityGroupProps
            {
                AllowAllOutbound  = allowGroupAllOutbound,
                SecurityGroupName = groupName,
                Vpc = vpc
            });

            securityGroup.AddIngressRule(ingressPeer, ingressPort);
            securityGroup.AddEgressRule(egressPeer, egressPort);
            return(securityGroup);
        }
        public IDatabaseInstance CreateDatabaseSqlServer(DeputyBase databaseEngineVersion, string identification, string databaseName, string userName, string password, StorageType storageType, InstanceClass instanceClass, string instanceSize, IVpc vpc, ISecurityGroup security, string securityGroupId, string parameterGroupId = null, IRole[] roles = null, double?allocatedStorageGb = 5, RemovalPolicy removalPolicy = RemovalPolicy.DESTROY, bool deleteAutomatedBackups = false, int backupRetentionDays = 1, bool?deletionProtection = false, SubnetType subnetType = SubnetType.PRIVATE_ISOLATED, string defaultSubnetDomainSeparator = ",", string subnets = "", bool multiAZEnabled = true, bool?autoMinorVersionUpgrade = false, bool?storageEncrypted = true, string licenseOption = "LICENSE_INCLUDED", string edition = "ex")
        {
            BasicDatabaseInfraWithHardcodedPassword(vpc, subnetType, defaultSubnetDomainSeparator, subnets, out var subnetSelection);
            var engine = GetInstanceEngine(databaseEngineVersion, edition);

            return(new DatabaseInstance(Scope, identification, new DatabaseInstanceProps
            {
                Engine = engine,
                RemovalPolicy = removalPolicy,
                DeletionProtection = deletionProtection,
                Credentials = Credentials.FromPassword(userName, SecretValue.PlainText(password)),
                StorageType = storageType,
                DatabaseName = licenseOption == LicenseModel.LICENSE_INCLUDED.ToString() ? null : databaseName,
                VpcSubnets = subnetSelection,
                Vpc = vpc,
                SecurityGroups = new[]
                {
                    security
                },
                DeleteAutomatedBackups = deleteAutomatedBackups,
                BackupRetention = Duration.Days(backupRetentionDays),
                AllocatedStorage = allocatedStorageGb,
                InstanceType = InstanceType.Of(instanceClass, GetInstanceSize(instanceSize)),
                ParameterGroup = CreateClusterParameterGroup(parameterGroupId, engine, roles),
                MultiAz = multiAZEnabled,
                AutoMinorVersionUpgrade = autoMinorVersionUpgrade,
                StorageEncrypted = storageEncrypted,
                LicenseModel = GetLicenseModel(licenseOption)
            }));
        }