public Role GetRole(Construct scope, string roleId,
                            string[] ManagedPolicyArns,
                            string[] PrincipalServices,
                            string PolicyName)
        {
            var roleProps = new RoleProps {
                Path      = "/",
                AssumedBy = new ServicePrincipal(PrincipalServices[0])
            };

            if (PrincipalServices.Length > 0)
            {
                List <PrincipalBase> principalBases = new List <PrincipalBase>();
                foreach (string service in PrincipalServices)
                {
                    PrincipalBase principalBase = new ServicePrincipal(service);
                    principalBases.Add(principalBase);
                }
                var compositePrincipal = new CompositePrincipal(principalBases.ToArray());
                roleProps = new RoleProps {
                    Path      = "/",
                    AssumedBy = compositePrincipal
                };
            }

            var iamRole = new Role(scope, roleId, roleProps);

            foreach (string arn in ManagedPolicyArns)
            {
                iamRole.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName(arn));
            }

            return(iamRole);
        }
예제 #2
0
        private void ConfigureIAM(Configuration settings)
        {
            if (settings.ApplicationIAMRole.CreateNew)
            {
                AppIAMRole = new Role(this, nameof(AppIAMRole), InvokeCustomizeCDKPropsEvent(nameof(AppIAMRole), this, new RoleProps
                {
                    AssumedBy = new ServicePrincipal("ec2.amazonaws.com"),

                    // https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-instanceprofile.html
                    ManagedPolicies = new[]
                    {
                        ManagedPolicy.FromAwsManagedPolicyName("AWSElasticBeanstalkWebTier"),
                        ManagedPolicy.FromAwsManagedPolicyName("AWSElasticBeanstalkWorkerTier")
                    }
                }));
            }
            else
            {
                if (string.IsNullOrEmpty(settings.ApplicationIAMRole.RoleArn))
                {
                    throw new InvalidOrMissingConfigurationException("The provided Application IAM Role ARN is null or empty.");
                }

                AppIAMRole = Role.FromRoleArn(this, nameof(AppIAMRole), settings.ApplicationIAMRole.RoleArn);
            }

            Ec2InstanceProfile = new CfnInstanceProfile(this, nameof(Ec2InstanceProfile), InvokeCustomizeCDKPropsEvent(nameof(Ec2InstanceProfile), this, new CfnInstanceProfileProps
            {
                Roles = new[]
                {
                    AppIAMRole.RoleName
                }
            }));
        }
예제 #3
0
        internal BastionStack(Construct scope, string id, Vpc vpc, string keyPairName, IStackProps props = null) : base(scope, id, props)
        {
            Role = new Role(this, "ec2-bastion-role", new RoleProps {
                AssumedBy = new ServicePrincipal("ec2.amazonaws.com")
            });

            Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("SecretsManagerReadWrite"));

            Bastion = new Instance_(this, id, new InstanceProps
            {
                InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.MICRO),
                MachineImage = new WindowsImage(WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_FULL_BASE),
                Vpc          = vpc,
                UserData     = UserData.Custom(Utils.GetResource("bastion_user_data.ps1")),
                KeyName      = keyPairName,
                Role         = Role,
                VpcSubnets   = new SubnetSelection {
                    SubnetType = SubnetType.PUBLIC
                }
            });

            Bastion.Connections.AllowFromAnyIpv4(Port.Tcp(3389), "Internet access RDP");

            new CfnOutput(this, "Bastion Host", new CfnOutputProps {
                Value = Bastion.InstancePublicDnsName
            });
        }
예제 #4
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();
 }
        public async Task CreatePolicyAsyncTest()
        {
            // Create a policy with permissions to list Amazon S3 buckets
            var policy = await IAM_Basics.CreatePolicyAsync(Client, S3PolicyName, testPolicyDocument);

            Assert.Equal(policy.PolicyName, S3PolicyName);
            TestPolicy = policy;
        }
 public ECSInstanceRole(Construct scope)
     : base(scope, "ECSInstanceRole", new RoleProps()
 {
     RoleName        = "ecsInstanceRole",
     ManagedPolicies = new IManagedPolicy[] {
         ManagedPolicy.FromAwsManagedPolicyName("service-role/AmazonEC2ContainerServiceforEC2Role")
     },
     AssumedBy = new ServicePrincipal("ecs.amazonaws.com")
 })
 {
 }
예제 #7
0
        internal EksSimpleStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var clusterAdmin = new Role(this, Constants.ADMIN_ROLE, new RoleProps
            {
                AssumedBy = new AccountRootPrincipal()
            });

            IVpc vpc = new Vpc(this, Constants.VPC_ID, new VpcProps
            {
                Cidr = Constants.VPC_CIDR
            });
            var cluster = new Cluster(this, Constants.CLUSTER_ID, new ClusterProps
            {
                MastersRole     = clusterAdmin,
                Version         = KubernetesVersion.V1_16,
                KubectlEnabled  = true,
                DefaultCapacity = 0,
                Vpc             = vpc
            });

            var tags = new Dictionary <string, string>();

            tags.Add("name", Constants.CDK8s);

            var eksEC2sNodeGroup = cluster.AddNodegroup(Constants.CLUSTER_NODE_GRP_ID, new NodegroupOptions
            {
                InstanceType = new InstanceType(Constants.EC2_INSTANCE_TYPE),
                MinSize      = 2,
                Subnets      = new SubnetSelection {
                    Subnets = vpc.PrivateSubnets
                },
                Tags = tags
            });

            string[] ManagedPolicyArns = GetNodeRoleManagedPolicyARNs();
            foreach (string arn in ManagedPolicyArns)
            {
                eksEC2sNodeGroup.Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName(arn));
            }

            var eksSecGrp = ec2.SecurityGroup.FromSecurityGroupId(this, Constants.EKS_SECURITY_GRP, cluster.ClusterSecurityGroupId);

            secGrp.AddIngressRule(eksSecGrp, ec2.Port.Tcp(3306), description: Constants.EC2_INGRESS_DESCRIPTION);

            var privateSubnets = new List <string>();

            foreach (Subnet subnet in vpc.PrivateSubnets)
            {
                privateSubnets.Add(subnet.SubnetId);
            }
        public ManagedPolicy Policy(Construct scope, string id, string policyName, PolicyStatement[] statements)
        {
            if (policyName == null)
            {
                policyName = id;
            }

            var props = new ManagedPolicyProps
            {
                ManagedPolicyName = policyName,
                Statements        = statements
            };
            var policy = new ManagedPolicy(scope, id, props);

            return(policy);
        }
예제 #9
0
        private Role createLambdaRole()
        {
            Role role = new Role(this, "LambdaRole", new RoleProps
            {
                AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
            });

            role.AddManagedPolicy(
                ManagedPolicy.FromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole")
                );

            role.AddManagedPolicy(
                ManagedPolicy.FromAwsManagedPolicyName("service-role/AWSLambdaVPCAccessExecutionRole")
                );

            return(role);
        }
예제 #10
0
        internal EbDotnetLinuxStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var ebInstanceRole = new Role(this, "SampleApp-Role", new RoleProps
            {
                AssumedBy       = new ServicePrincipal("ec2.amazonaws.com"),
                ManagedPolicies = new[] { ManagedPolicy.FromAwsManagedPolicyName("AWSElasticBeanstalkWebTier") }
            });

            var instanceProfile = new CfnInstanceProfile(this, "SampleApp-InstanceProfile", new CfnInstanceProfileProps
            {
                InstanceProfileName = "SampleApp-InstanceProfile",
                Roles = new[] { ebInstanceRole.RoleName }
            });

            var optionSettingProperties = new CfnEnvironment.OptionSettingProperty[] {
                new CfnEnvironment.OptionSettingProperty {
                    Namespace  = "aws:autoscaling:launchconfiguration",
                    OptionName = "InstanceType",
                    Value      = "t3.small",
                },
                new CfnEnvironment.OptionSettingProperty {
                    Namespace  = "aws:autoscaling:launchconfiguration",
                    OptionName = "IamInstanceProfile",
                    Value      = instanceProfile.InstanceProfileName
                }
            };

            var app = new CfnApplication(this, "SampleApp-App", new CfnApplicationProps
            {
                ApplicationName = "SampleApp"
            });

            var env = new CfnEnvironment(this, "SampleApp-Env", new CfnEnvironmentProps
            {
                EnvironmentName = "SampleAppEnvironment",
                ApplicationName = app.ApplicationName,
                // please check the latest platform name at https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html
                SolutionStackName = "64bit Amazon Linux 2 v2.2.8 running .NET Core",
                OptionSettings    = optionSettingProperties
            });

            // to ensure the application is created before the environment
            env.AddDependsOn(app);
        }
예제 #11
0
        internal MailBotStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            //Secrets Manager
            //IAM
            //IAM - Role - mailbot
            //IAM - Role - StepFunctions
            //IAM - Role - StepFunctions - CloudWatchFullAccess
            //IAM - Role - StepFunctions - AWS Lambda Role
            //IAM - Role - StepFunctions - TAGS

            Role role = new Role(this, "StepFunctions", new RoleProps
            {
                AssumedBy   = new ServicePrincipal("ec2.amazonaws.com"),
                Description = "Role for Step Functions",
            });

            role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("CloudWatchFullAccess"));
            //role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AWSLambdaRole"));


            //User user = new User(this, "MyUser", new UserProps { Password = SecretValue.PlainText("1234") });
            //Group group = new Group(this, "MyGroup");

            //Policy policy = new Policy(this, "MyPolicy");
            //policy.AttachToUser(user);
            //group.AttachInlinePolicy(policy);


            ////Register domain
            ////Verify SES

            //Bucket emailsBucket = new Bucket(this, "emails", new BucketProps
            //{
            //});
            //Bucket updatesBucket = new Bucket(this, "updates", new BucketProps
            //{
            //});
            //Bucket attachmentsBucket = new Bucket(this, "attachments", new BucketProps
            //{
            //});
            //Bucket quarantineBucket = new Bucket(this, "quarantine", new BucketProps
            //{
            //});
        }
예제 #12
0
        private void ConfigureIAMRoles(Configuration settings)
        {
            if (settings.ServiceAccessIAMRole.CreateNew)
            {
                ServiceAccessRole = new Role(this, nameof(ServiceAccessRole), InvokeCustomizeCDKPropsEvent(nameof(ServiceAccessRole), this, new RoleProps
                {
                    AssumedBy = new ServicePrincipal("build.apprunner.amazonaws.com")
                }));

                ServiceAccessRole.AddManagedPolicy(ManagedPolicy.FromManagedPolicyArn(this, "ServiceAccessRoleManagedPolicy", "arn:aws:iam::aws:policy/service-role/AWSAppRunnerServicePolicyForECRAccess"));
            }
            else
            {
                if (string.IsNullOrEmpty(settings.ServiceAccessIAMRole.RoleArn))
                {
                    throw new InvalidOrMissingConfigurationException("The provided Application IAM Role ARN is null or empty.");
                }

                ServiceAccessRole = Role.FromRoleArn(this, nameof(ServiceAccessRole), settings.ServiceAccessIAMRole.RoleArn, new FromRoleArnOptions
                {
                    Mutable = false
                });
            }

            if (settings.ApplicationIAMRole.CreateNew)
            {
                TaskRole = new Role(this, nameof(TaskRole), InvokeCustomizeCDKPropsEvent(nameof(TaskRole), this, new RoleProps
                {
                    AssumedBy = new ServicePrincipal("tasks.apprunner.amazonaws.com")
                }));
            }
            else
            {
                if (string.IsNullOrEmpty(settings.ApplicationIAMRole.RoleArn))
                {
                    throw new InvalidOrMissingConfigurationException("The provided Application IAM Role ARN is null or empty.");
                }

                TaskRole = Role.FromRoleArn(this, nameof(TaskRole), settings.ApplicationIAMRole.RoleArn, new FromRoleArnOptions
                {
                    Mutable = false
                });
            }
        }
예제 #13
0
        internal MackerelAlertBridgeStack(Construct scope, string id, MackerelAlertBridgeProps props) : base(scope, id, props)
        {
            // Ref: https://mackerel.io/ja/docs/entry/integrations/aws
            var integrationRole = new Role(this, "IntegrationRole", new RoleProps()
            {
                AssumedBy   = new AccountPrincipal("217452466226"),
                ExternalIds = new string[] {
                    props.StsExternalId,
                },
                ManagedPolicies = new IManagedPolicy[]
                {
                    ManagedPolicy.FromAwsManagedPolicyName("AWSLambdaReadOnlyAccess"),
                },
            });

            new CfnOutput(this, "IntegrationRoleArn", new CfnOutputProps()
            {
                Value = integrationRole.RoleArn
            });
        }
예제 #14
0
        internal void GrantLambdaRolePermissions()
        {
            var lambdaRole = new Role(this, "lambdaEdgeRole", new RoleProps()
            {
                RoleName  = "LambdaEdgeRole",
                AssumedBy = new CompositePrincipal(
                    new ServicePrincipal("lambda.amazonaws.com"),
                    new ServicePrincipal("edgelambda.amazonaws.com")
                    ),
                ManagedPolicies = new IManagedPolicy[] {
                    ManagedPolicy.FromManagedPolicyArn(this, "AWSLambdaBasicExecutionRoleManagedPolicy", "service-role/AWSLambdaBasicExecutionRole")
                }
            });

            functionsStack.parseAuthHandler.GrantInvoke(lambdaRole);
            functionsStack.checkAuthHandler.GrantInvoke(lambdaRole);
            functionsStack.refreshAuthHandler.GrantInvoke(lambdaRole);
            functionsStack.signOutHandler.GrantInvoke(lambdaRole);
            functionsStack.httpHeadersHandler.GrantInvoke(lambdaRole);
        }
        public static Role GetRole(TodoInfraStack stack, string roleId,
                                   string[] ManagedPolicyArns,
                                   string[] PrincipalServices,
                                   string PolicyName, string[] Actions, string resources)
        {
            var roleProps = new RoleProps {
                Path      = "/",
                AssumedBy = new ServicePrincipal(PrincipalServices[0])
            };

            if (PrincipalServices.Length > 0)
            {
                List <PrincipalBase> principalBases = new List <PrincipalBase>();
                foreach (string service in PrincipalServices)
                {
                    PrincipalBase principalBase = new ServicePrincipal(service);
                    principalBases.Add(principalBase);
                }
                var compositePrincipal = new CompositePrincipal(principalBases.ToArray());
                roleProps = new RoleProps {
                    Path      = "/",
                    AssumedBy = compositePrincipal
                };
            }

            var iamRole = new Role(stack, roleId, roleProps);

            foreach (string arn in ManagedPolicyArns)
            {
                iamRole.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName(arn));
            }

            PolicyStatement policyStatement = new PolicyStatement(new PolicyStatementProps {
                Actions   = Actions,
                Resources = new string[] { resources },
                Effect    = Effect.ALLOW
            });

            iamRole.AddToPolicy(policyStatement);
            return(iamRole);
        }
예제 #16
0
        private static void CreateNodeGroup(string id, Cluster cluster, string nodeGroupName, string instanceType,
                                            ISubnet subnet, AZ az, int actualMinSize = 1, int actualMaxSize = 5)
        {
            var nodegroup = cluster.AddNodegroupCapacity($"{id}-{az}", new NodegroupProps()
            {
                NodegroupName = $"{cluster.ClusterName}-{nodeGroupName}-{az}",
                InstanceType  = new InstanceType(instanceType),
                MinSize       = actualMinSize,
                MaxSize       = actualMaxSize,
                Subnets       = new SubnetSelection {
                    Subnets = new[] { subnet }
                },
                Tags = new Dictionary <string, string>
                {
                    { "k8s.io/cluster-autoscaler/enabled", "" },
                    { "k8s.io/cluster-autoscaler/yoda", "" }
                }
            });

            nodegroup.Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("CloudWatchAgentServerPolicy"));
            nodegroup.Role.AddToPrincipalPolicy(autoScalePolicy);
        }
예제 #17
0
        public AppStack(Construct parent, string id, IStackProps props) : base(parent, id, props)
        {
            var cluster = new Cluster(this, "AppCluster", new ClusterProps
            {
                Vpc = Vpc.FromLookup(this, "DefaultVpc", new VpcLookupOptions()
                {
                    IsDefault = true
                }),
            });

            new ApplicationLoadBalancedFargateService(this, "AppService",
                                                      new ApplicationLoadBalancedFargateServiceProps
            {
                Cluster          = cluster,
                DesiredCount     = 1,
                TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions
                {
                    Image = ContainerImage.FromAsset(DockerFolderBuilder.GetBuildFolder(), new AssetImageProps()
                    {
                        File = Path.Combine("DockerProject1", "Dockerfile")
                    }),
                    TaskRole = new Role(this, "AppRole", new RoleProps()
                    {
                        RoleName        = "AppRole",
                        AssumedBy       = new ServicePrincipal("ecs-tasks.amazonaws.com"),
                        ManagedPolicies = new IManagedPolicy[]
                        {
                            ManagedPolicy.FromAwsManagedPolicyName("TranslateFullAccess"),
                            ManagedPolicy.FromAwsManagedPolicyName("AmazonS3FullAccess"),
                        }
                    })
                },
                MemoryLimitMiB     = 2048,      // Default is 256
                PublicLoadBalancer = true,      // Default is false
                AssignPublicIp     = true,
            }
                                                      );
        }
        internal TargetInstanceStack(Construct scope, string id, Vpc vpc, string keyPairName, IStackProps props = null) : base(scope, id, props)
        {
            SecurityGroup = new SecurityGroup(this, "TargetInstance-Security-Group", new SecurityGroupProps
            {
                Vpc = vpc,
                AllowAllOutbound  = true,
                Description       = "TargetInstance-Security-Group",
                SecurityGroupName = "secgroup-" + id
            });


            Role = new Role(this, "ec2-targetinstance-role", new RoleProps
            {
                AssumedBy = new ServicePrincipal("ec2.amazonaws.com")
            });

            Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("SecretsManagerReadWrite"));

            TargetInstance = new Instance_(this, id, new InstanceProps
            {
                InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.MICRO),
                MachineImage = new WindowsImage(WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_FULL_BASE),
                Vpc          = vpc,
                UserData     = UserData.Custom(Utils.GetResource("target_instance_user_data.ps1")),
                KeyName      = keyPairName,
                Role         = Role,
                VpcSubnets   = new SubnetSelection {
                    SubnetType = SubnetType.PRIVATE
                },
                SecurityGroup = SecurityGroup
            });

            SecurityGroup.AddIngressRule(Peer.AnyIpv4(), Port.AllTraffic(), "Allow all trafic in. In production - change this!");

            new CfnOutput(this, "target-instance", new CfnOutputProps {
                Value = TargetInstance.InstancePrivateIp
            });
        }
예제 #19
0
        public static async Task <Role> CreateRoleWithPoliciesAsync(
            this IAMHelper iam, string roleName,
            string[] policies,
            string roleDescription              = null,
            bool createInstanceProfile          = false,
            StringComparison stringComparison   = StringComparison.InvariantCultureIgnoreCase,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var policyDoc = $@"{{""Version"":""2012-10-17"",""Statement"":[{{""Effect"":""Allow"",""Principal"":{{""Service"":[""ec2.amazonaws.com"",""ecs-tasks.amazonaws.com""]}},""Action"":[""sts:AssumeRole""]}}]}}";

            var tR   = iam.CreateRoleAsync(roleName: roleName, description: roleDescription, path: null, maxSessionDuration: 12 * 3600, assumeRolePolicyDocument: policyDoc, cancellationToken: cancellationToken);
            var list = await iam.ListPoliciesAsync(cancellationToken : cancellationToken);

            var mp = new ManagedPolicy[policies.Length];

            for (int i = 0; i < policies.Length; i++)
            {
                var policy = policies[i];
                mp[i] = list.Single(x => x.PolicyName.Equals(policy, stringComparison) || x.PolicyName.Equals(policy, stringComparison));
            }

            var roleResponse = await tR;

            await mp.ForEachAsync(p => iam.AttachRolePolicyAsync(roleResponse.Role.RoleName, p.Arn, cancellationToken),
                                  iam._maxDegreeOfParalelism, cancellationToken : cancellationToken);

            //https://aws.amazon.com/premiumsupport/knowledge-center/iam-role-not-in-list/
            if (createInstanceProfile)
            {
                await iam.DeleteRoleInstanceProfiles(roleName : roleName, cancellationToken : cancellationToken);

                await iam.CreateInstanceProfileAsync(name : roleName, cancellationToken : cancellationToken);

                await iam.AddRoleToInstanceProfileAsync(profileName : roleName, roleName : roleName, cancellationToken : cancellationToken);
            }

            return(roleResponse.Role);
        }
예제 #20
0
        internal AutoScaledInstances(
            CdkStack stack,
            CfnParameter targetPlatform,
            Vpc vpc,
            bool publicAccess,
            SecurityGroup albSecurityGroup,
            SecurityGroup instanceSecurityGroup,
            Database database = null,
            Policy policy     = null,
            ApplicationLoadBalancer restApiLoadBalancer = null)
        {
            IMachineImage selectedImage;

            bool targetWindows = false;

            if (targetWindows)
            {
                var userData = UserData.ForWindows();
                userData.AddCommands(
                    "New-Item -Path c:\\temp -ItemType Directory -Force",
                    $"Read-S3Object -BucketName aws-codedeploy-{stack.Region}/latest -Key codedeploy-agent.msi -File c:\\temp\\codedeploy-agent.msi",
                    "Start-Process -Wait -FilePath c:\\temp\\codedeploy-agent.msi -WindowStyle Hidden"
                    );
                selectedImage = new WindowsImage(
                    WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_CORE_BASE,
                    new WindowsImageProps
                {
                    UserData = userData
                }
                    );
            }
            else
            {
                var userData = UserData.ForLinux(new LinuxUserDataOptions {
                    Shebang = "#!/bin/bash -xe"
                });
                userData.AddCommands(
                    "exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1",
                    "yum install -y aws-cli ruby jq",
                    "yum -y update",
                    "cd /tmp/",
                    $"curl -O https://aws-codedeploy-{stack.Region}.s3.amazonaws.com/latest/install",
                    "chmod +x ./install",
                    "if ./install auto; then",
                    "    echo \"CodeDeploy Agent installation completed successfully!\"",
                    "    exit 0",
                    "else",
                    "    echo \"CodeDeploy Agent installation failed, please investigate.\"",
                    "    rm -f /tmp/install",
                    "    exit 1",
                    "fi",
                    "rm -rf /tmp/*"
                    );
                selectedImage = new AmazonLinuxImage(new AmazonLinuxImageProps
                {
                    Edition        = AmazonLinuxEdition.STANDARD,
                    Virtualization = AmazonLinuxVirt.HVM,
                    Generation     = AmazonLinuxGeneration.AMAZON_LINUX_2,
                    Storage        = AmazonLinuxStorage.EBS,
                    UserData       = userData
                });
            };

            var alb = new ApplicationLoadBalancer(stack, $"ApplicationLoadBalancer-{(publicAccess ? "public" : "private")}", new ApplicationLoadBalancerProps
            {
                InternetFacing = publicAccess,
                Vpc            = vpc,
                VpcSubnets     = new SubnetSelection {
                    SubnetType = publicAccess ? SubnetType.PUBLIC : SubnetType.PRIVATE
                },
                SecurityGroup = albSecurityGroup,
                IpAddressType = IpAddressType.IPV4,
                Http2Enabled  = true
            });

            var albTargetGroup = new ApplicationTargetGroup(stack, $"ApplicationTargetGroup-{(publicAccess ? "public" : "private")}", new ApplicationTargetGroupProps
            {
                Vpc         = vpc,
                Port        = 80,
                Protocol    = ApplicationProtocol.HTTP,
                TargetType  = TargetType.INSTANCE,
                HealthCheck = new Amazon.CDK.AWS.ElasticLoadBalancingV2.HealthCheck
                {
                    Timeout  = Duration.Seconds(5),
                    Interval = Duration.Seconds(10),
                    HealthyThresholdCount = 2
                }
            });
            var albListener = new ApplicationListener(stack, $"ApplicationListener-{(publicAccess ? "public" : "private")}", new ApplicationListenerProps
            {
                Port          = 80,
                Protocol      = ApplicationProtocol.HTTP,
                DefaultAction = ListenerAction.Forward(new[] { albTargetGroup }),
                LoadBalancer  = alb
            });

            var asg = new AutoScalingGroup(stack, $"ASG-{(publicAccess ? "public" : "private")}", new AutoScalingGroupProps
            {
                Vpc          = vpc,
                MinCapacity  = 2,
                InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.MEDIUM),
                MachineImage = selectedImage,
                BlockDevices = new[] {
                    new Amazon.CDK.AWS.AutoScaling.BlockDevice()
                    {
                        DeviceName = "/dev/xvda",
                        Volume     = Amazon.CDK.AWS.AutoScaling.BlockDeviceVolume.Ebs(
                            targetWindows ? 30: 8,
                            new Amazon.CDK.AWS.AutoScaling.EbsDeviceOptions {
                            VolumeType          = Amazon.CDK.AWS.AutoScaling.EbsDeviceVolumeType.GP2,
                            DeleteOnTermination = true
                        }
                            )
                    }
                },
                AssociatePublicIpAddress = false,
                VpcSubnets = new SubnetSelection {
                    SubnetType = SubnetType.PRIVATE
                }
            });

            if (policy != null)
            {
                asg.Role.AttachInlinePolicy(policy);
            }
            asg.Role.AddToPrincipalPolicy(
                new PolicyStatement(new PolicyStatementProps
            {
                Effect    = Effect.ALLOW,
                Actions   = new[] { "ec2:DescribeTags" },
                Resources = new[] { "*" }
            })
                );
            asg.Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AmazonSSMManagedInstanceCore"));
            asg.Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AWSXRayDaemonWriteAccess"));
            asg.Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("CloudWatchAgentServerPolicy"));

            Tag.Add(asg, "Application", stack.StackName);
            if (publicAccess)
            {
                Tag.Add(asg, "ApplicationRole", "Front End");
                Tag.Add(asg, "RESTAPIAddress", restApiLoadBalancer.LoadBalancerDnsName);
            }
            else
            {
                Tag.Add(asg, "ApplicationRole", "REST API");
            }
            if (database != null)
            {
                asg.Node.AddDependency(database.DatabaseResource);
                Tag.Add(asg, "DBSecretArn", database.Password.SecretArn);
            }

            // Enable access from the ALB
            asg.AddSecurityGroup(instanceSecurityGroup);
            Result = new LoadBalancedInstancesResult
            {
                AutoScalingGroup = asg,
                TargetGroup      = albTargetGroup,
                LoadBalancer     = alb
            };
        }
예제 #21
0
        public AppsyncGraphqlDynamodbStack(Construct parent, string id, IStackProps props) : base(parent, id, props)
        {
            const string tableName = "items";

            var itemsGraphQLApi = new CfnGraphQLApi(this, "Items", new CfnGraphQLApiProps {
                Name = "items-api",
                AuthenticationType = "API_KEY"
            });

            new CfnApiKey(this, "ItemsApiKey", new CfnApiKeyProps {
                ApiId = itemsGraphQLApi.AttrApiId
            });

            var apiSchema = new CfnGraphQLSchema(this, "ItemsSchema", new CfnGraphQLSchemaProps {
                ApiId      = itemsGraphQLApi.AttrApiId,
                Definition = Definition(tableName)
            });

            var itemsTable = new Table(this, "ItemsTable", new TableProps {
                TableName    = tableName,
                PartitionKey = new Amazon.CDK.AWS.DynamoDB.Attribute {
                    Name = String.Format("{0}Id", tableName),
                    Type = AttributeType.STRING
                },
                BillingMode = BillingMode.PAY_PER_REQUEST,
                Stream      = StreamViewType.NEW_IMAGE,

                // The default removal policy is RETAIN, which means that cdk destroy will not attempt to delete
                // the new table, and it will remain in your account until manually deleted. By setting the policy to
                // DESTROY, cdk destroy will delete the table (even if it has data in it)
                RemovalPolicy = RemovalPolicy.DESTROY
            });

            var itemsTableRole = new Role(this, "ItemsDynamoDBRole", new RoleProps {
                AssumedBy = new ServicePrincipal("appsync.amazonaws.com")
            });

            itemsTableRole.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AmazonDynamoDBFullAccess"));

            var dataSource = new CfnDataSource(this, "ItemsDataSource", new CfnDataSourceProps {
                ApiId          = itemsGraphQLApi.AttrApiId,
                Name           = "ItemsDynamoDataSource",
                Type           = "AMAZON_DYNAMODB",
                DynamoDbConfig = new Dictionary <string, string>()
                {
                    { "tableName", itemsTable.TableName },
                    { "awsRegion", this.Region }
                },
                ServiceRoleArn = itemsTableRole.RoleArn
            });

            var getOneResolver = new CfnResolver(this, "GetOneQueryResolver", new CfnResolverProps {
                ApiId                   = itemsGraphQLApi.AttrApiId,
                TypeName                = "Query",
                FieldName               = "getOne",
                DataSourceName          = dataSource.Name,
                RequestMappingTemplate  = String.Format(@"{{
                    ""version"": ""2017-02-28"",
                    ""operation"": ""GetItem"",
                    ""key"": {{
                        ""{0}"": $util.dynamodb.toDynamoDBJson($ctx.args.{0}Id)
                    }}
                    }}", tableName),
                ResponseMappingTemplate = "$util.toJson($ctx.result)"
            });

            getOneResolver.AddDependsOn(apiSchema);

            var getAllResolver = new CfnResolver(this, "GetAllQueryResolver", new CfnResolverProps {
                ApiId                   = itemsGraphQLApi.AttrApiId,
                TypeName                = "Query",
                FieldName               = "all",
                DataSourceName          = dataSource.Name,
                RequestMappingTemplate  = String.Format(@"{{
                    ""version"": ""2017-02-28"",
                    ""operation"": ""Scan"",
                    ""limit"": $util.defaultIfNull($ctx.args.limit, 20),
                    ""nextToken"": $util.toJson($util.defaultIfNullOrEmpty($ctx.args.nextToken, null))
                    }}", tableName),
                ResponseMappingTemplate = "$util.toJson($ctx.result)"
            });

            getAllResolver.AddDependsOn(apiSchema);

            var saveResolver = new CfnResolver(this, "SaveMutationResolver", new CfnResolverProps {
                ApiId                   = itemsGraphQLApi.AttrApiId,
                TypeName                = "Mutation",
                FieldName               = "save",
                DataSourceName          = dataSource.Name,
                RequestMappingTemplate  = String.Format(@"{{
                    ""version"": ""2017-02-28"",
                    ""operation"": ""PutItem"",
                    ""key"": {{
                        ""{0}Id"": {{ ""S"": ""$util.autoId()"" }}
                    }},
                    ""attributeValues"": {{
                        ""name"": $util.dynamodb.toDynamoDBJson($ctx.args.name)
                    }}
                    }}", tableName),
                ResponseMappingTemplate = "$util.toJson($ctx.result)"
            });

            saveResolver.AddDependsOn(apiSchema);

            var deleteResolver = new CfnResolver(this, "DeleteMutationResolver", new CfnResolverProps {
                ApiId                   = itemsGraphQLApi.AttrApiId,
                TypeName                = "Mutation",
                FieldName               = "delete",
                DataSourceName          = dataSource.Name,
                RequestMappingTemplate  = String.Format(@"{{
                    ""version"": ""2017-02-28"",
                    ""operation"": ""Scan"",
                    ""key"": {{
                        ""{0}Id"": $util.dynamodb.toDynamoDBJson($ctx.args.{0}Id)
                    }}
                    }}", tableName),
                ResponseMappingTemplate = "$util.toJson($ctx.result)"
            });

            deleteResolver.AddDependsOn(apiSchema);
        }
        internal DeploymentStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            // role
            var role = new Role(this, "fixsecuritygroupslambdarole", new RoleProps
            {
                Description = "fix security groups lambda role",
                AssumedBy   = new ServicePrincipal("lambda.amazonaws.com")
            });

            role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AmazonEC2FullAccess"));
            role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AWSLambdaExecute"));
            role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("CloudWatchEventsFullAccess"));

            // lambda
            var code   = @"
import json
import boto3

def lambda_handler(event, context):
    print(event)
    if event['detail']['eventSource'] == 'ec2.amazonaws.com' and event['detail']['eventName'] == 'CreateSecurityGroup':
        sgid = event['detail']['responseElements']['groupId']
    elif event['detail']['eventSource'] == 'ec2.amazonaws.com' and event['detail']['eventName'] == 'DeleteTags':
        sgid = event['detail']['requestParameters']['resourcesSet']['items'][0]['resourceId']
    ec2 = boto3.resource('ec2')
    sg = ec2.SecurityGroup(sgid)
    sg.create_tags(Tags=[{'Key': 'Name', 'Value': ""TAGGED!!!""}])
    return {
        'statusCode': 200,
        'body': json.dumps(event)
    }
";
            var lambda = new Function(this, "fixsecuritygroupslambda", new FunctionProps
            {
                Runtime = Runtime.PYTHON_3_6,
                Code    = Code.FromInline(code),
                Handler = "index.lambda_handler",
                Role    = role
            });

            // cloudwatch event
            //       @"{
            //          ""source"": [
            //            ""aws.ec2""
            //          ],
            //          ""detail-type"": [
            //            ""AWS API Call via CloudTrail""
            //          ],
            //          ""detail"": {
            //            ""eventSource"": [
            //              ""ec2.amazonaws.com""
            //            ],
            //            ""eventName"": [
            //              ""CreateSecurityGroup"",
            //              ""DeleteTags""
            //            ]
            //          }
            //        }";
            var ed = new Dictionary <string, object>();

            ed.Add("eventSource", new string[1] {
                "ec2.amazonaws.com"
            });
            ed.Add("eventName", new string[2] {
                "CreateSecurityGroup", "DeleteTags"
            });
            var rule = new Rule(this, "cloudwatchevent", new RuleProps
            {
                Enabled      = true,
                EventPattern = new EventPattern()
                {
                    Detail = ed,
                    Source = new string[1] {
                        "aws.ec2"
                    },
                    DetailType = new string[1] {
                        "AWS API Call via CloudTrail"
                    }
                },
            });

            rule.AddTarget(new LambdaFunction(lambda));
        }
예제 #23
0
        public PipelineStack(Construct parent, string id, IPipelineStackProps props) : base(parent, id, props)
        {
            EcrRepository = new Repository(
                this,
                "EcrRepository",
                new RepositoryProps
            {
                RepositoryName = "cdk-dotnet-example",
                RemovalPolicy  = RemovalPolicy.DESTROY,
            });

            var cdkBuild = new PipelineProject(
                this,
                "CdkBuild",
                new PipelineProjectProps
            {
                BuildSpec   = BuildSpec.FromSourceFilename("Infrastructure/Resources/cdk_buildspec.yml"),
                Environment = new BuildEnvironment
                {
                    BuildImage = LinuxBuildImage.AMAZON_LINUX_2,
                },
            });

            var apiBuildTaskRole = new Role(
                this,
                "ApiBuildRole",
                new RoleProps
            {
                ManagedPolicies = new[]
                {
                    ManagedPolicy.FromAwsManagedPolicyName("AmazonEC2ContainerRegistryPowerUser"),
                },
                AssumedBy = new ServicePrincipal("codebuild.amazonaws.com")
            });

            var apiBuild = new PipelineProject(
                this,
                "ApiBuild",
                new PipelineProjectProps
            {
                BuildSpec   = BuildSpec.FromSourceFilename("Infrastructure/Resources/api_buildspec.yml"),
                Role        = apiBuildTaskRole,
                Environment = new BuildEnvironment
                {
                    BuildImage           = LinuxBuildImage.AMAZON_LINUX_2,
                    Privileged           = true,
                    EnvironmentVariables = new Dictionary <string, IBuildEnvironmentVariable>
                    {
                        ["AWS_ACCOUNT_ID"]     = CdkUtil.PlainTextBuildEnvironmentVariable(Of(this).Account),
                        ["AWS_DEFAULT_REGION"] = CdkUtil.PlainTextBuildEnvironmentVariable(Of(this).Region),
                    },
                },
            });

            var apiTest = new PipelineProject(
                this,
                "ApiTest",
                new PipelineProjectProps
            {
                BuildSpec   = BuildSpec.FromSourceFilename("Infrastructure/Resources/ci_buildspec.yml"),
                Environment = new BuildEnvironment
                {
                    BuildImage = LinuxBuildImage.AMAZON_LINUX_2,
                    Privileged = true,
                },
            });

            var sourceOutput   = new Artifact_();
            var cdkBuildOutput = new Artifact_("CdkBuildOutput");
            var apiBuildOutput = new Artifact_("ApiBuildOutput");

            new Pipeline(
                this,
                "Api",
                new PipelineProps
            {
                Stages = new IStageProps[]
                {
                    new StageProps
                    {
                        StageName = "Source",
                        Actions   = new IAction[]
                        {
                            new GitHubSourceAction(new GitHubSourceActionProps
                            {
                                ActionName = "GitHub",
                                OauthToken = SecretValue.SecretsManager(props.GitHubSecretName),
                                Repo       = props.GitHubRepo,
                                Owner      = props.GitHubOwner,
                                Output     = sourceOutput,
                                Trigger    = GitHubTrigger.WEBHOOK,
                            }),
                        },
                    },
                    new StageProps
                    {
                        StageName = "Build",
                        Actions   = new IAction[]
                        {
                            new CodeBuildAction(new CodeBuildActionProps
                            {
                                ActionName = "ApiTest",
                                Project    = apiTest,
                                Input      = sourceOutput,
                                RunOrder   = 1,
                            }),
                            new CodeBuildAction(new CodeBuildActionProps
                            {
                                ActionName = "ApiBuild",
                                Project    = apiBuild,
                                Input      = sourceOutput,
                                Outputs    = new[] { apiBuildOutput },
                                RunOrder   = 2,
                            }),
                            new CodeBuildAction(new CodeBuildActionProps
                            {
                                ActionName = "CdkBuild",
                                Project    = cdkBuild,
                                Input      = sourceOutput,
                                Outputs    = new[] { cdkBuildOutput },
                                RunOrder   = 3,
                            }),
                        },
                    },
                    new StageProps
                    {
                        StageName = "Deploy",
                        Actions   = new IAction[]
                        {
                            new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps
                            {
                                ActionName         = "ApiStack",
                                TemplatePath       = cdkBuildOutput.AtPath($"{props.ApiStackName}.template.json"),
                                StackName          = "Api",
                                AdminPermissions   = true,
                                ParameterOverrides = new Dictionary <string, object>
                                {
                                    [props.ApiImageTag] = apiBuildOutput.GetParam("metadata.json", "imageTag"),
                                },
                                ExtraInputs = new[]
                                {
                                    apiBuildOutput,
                                },
                            }),
                        },
                    },
                },
            });
        }
예제 #24
0
        internal AppStack(Construct scope, RecipeConfiguration <Configuration> recipeConfiguration, IStackProps props = null)
            : base(scope, recipeConfiguration.StackName, props)
        {
            var settings = recipeConfiguration.Settings;

            var asset = new Asset(this, "Asset", new AssetProps
            {
                Path = recipeConfiguration.DotnetPublishZipPath
            });

            CfnApplication application = null;

            // Create an app version from the S3 asset defined above
            // The S3 "putObject" will occur first before CF generates the template
            var applicationVersion = new CfnApplicationVersion(this, "ApplicationVersion", new CfnApplicationVersionProps
            {
                ApplicationName = settings.BeanstalkApplication.ApplicationName,
                SourceBundle    = new CfnApplicationVersion.SourceBundleProperty
                {
                    S3Bucket = asset.S3BucketName,
                    S3Key    = asset.S3ObjectKey
                }
            });

            if (settings.BeanstalkApplication.CreateNew)
            {
                application = new CfnApplication(this, "Application", new CfnApplicationProps
                {
                    ApplicationName = settings.BeanstalkApplication.ApplicationName
                });

                applicationVersion.AddDependsOn(application);
            }

            IRole role;

            if (settings.ApplicationIAMRole.CreateNew)
            {
                role = new Role(this, "Role", new RoleProps
                {
                    AssumedBy = new ServicePrincipal("ec2.amazonaws.com"),

                    // https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-instanceprofile.html
                    ManagedPolicies = new[]
                    {
                        ManagedPolicy.FromAwsManagedPolicyName("AWSElasticBeanstalkWebTier"),
                        ManagedPolicy.FromAwsManagedPolicyName("AWSElasticBeanstalkWorkerTier")
                    }
                });
            }
            else
            {
                role = Role.FromRoleArn(this, "Role", settings.ApplicationIAMRole.RoleArn);
            }

            var instanceProfile = new CfnInstanceProfile(this, "InstanceProfile", new CfnInstanceProfileProps
            {
                Roles = new[]
                {
                    role.RoleName
                }
            });

            var optionSettingProperties = new List <CfnEnvironment.OptionSettingProperty> {
                new CfnEnvironment.OptionSettingProperty {
                    Namespace  = "aws:autoscaling:launchconfiguration",
                    OptionName = "IamInstanceProfile",
                    Value      = instanceProfile.AttrArn
                },
                new CfnEnvironment.OptionSettingProperty {
                    Namespace  = "aws:elasticbeanstalk:environment",
                    OptionName = "EnvironmentType",
                    Value      = settings.EnvironmentType
                }
            };

            if (!string.IsNullOrEmpty(settings.InstanceType))
            {
                optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty
                {
                    Namespace  = "aws:autoscaling:launchconfiguration",
                    OptionName = "InstanceType",
                    Value      = settings.InstanceType
                });
            }

            if (settings.EnvironmentType.Equals(ENVIRONMENTTYPE_LOADBALANCED))
            {
                optionSettingProperties.Add(
                    new CfnEnvironment.OptionSettingProperty
                {
                    Namespace  = "aws:elasticbeanstalk:environment",
                    OptionName = "LoadBalancerType",
                    Value      = settings.LoadBalancerType
                }
                    );
            }

            if (!string.IsNullOrEmpty(settings.EC2KeyPair))
            {
                optionSettingProperties.Add(
                    new CfnEnvironment.OptionSettingProperty
                {
                    Namespace  = "aws:autoscaling:launchconfiguration",
                    OptionName = "EC2KeyName",
                    Value      = settings.EC2KeyPair
                }
                    );
            }

            var environment = new CfnEnvironment(this, "Environment", new CfnEnvironmentProps
            {
                EnvironmentName = settings.EnvironmentName,
                ApplicationName = settings.BeanstalkApplication.ApplicationName,
                PlatformArn     = settings.ElasticBeanstalkPlatformArn,
                OptionSettings  = optionSettingProperties.ToArray(),
                // This line is critical - reference the label created in this same stack
                VersionLabel = applicationVersion.Ref,
            });

            var output = new CfnOutput(this, "EndpointURL", new CfnOutputProps
            {
                Value = $"http://{environment.AttrEndpointUrl}/"
            });
        }
예제 #25
0
        internal LambdaNetPipelineStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var codeBuildRole = new Role(this, "CodeBuildRole", new RoleProps
            {
                ManagedPolicies = new IManagedPolicy[] { ManagedPolicy.FromAwsManagedPolicyName("PowerUserAccess") },
                AssumedBy       = new ServicePrincipal("codebuild.amazonaws.com")
            });

            var cloudFormationRole = new Role(this, "CloudFormationRole", new RoleProps
            {
                ManagedPolicies = new IManagedPolicy[] { ManagedPolicy.FromAwsManagedPolicyName("AdministratorAccess") },
                AssumedBy       = new ServicePrincipal("cloudformation.amazonaws.com")
            });

            var artifactStore = new Bucket(this, "ArtifactStore");


            var build = new PipelineProject(this, id, new PipelineProjectProps
            {
                Role        = codeBuildRole,
                Environment = new BuildEnvironment
                {
                    BuildImage           = LinuxBuildImage.AMAZON_LINUX_2_3,
                    EnvironmentVariables = new Dictionary <string, IBuildEnvironmentVariable>
                    {
                        { "S3_BUCKET", new BuildEnvironmentVariable {
                              Type = BuildEnvironmentVariableType.PLAINTEXT, Value = artifactStore.BucketName
                          } }
                    }
                }
            });


            var githubOwner = this.Node.TryGetContext("github-owner")?.ToString();

            if (string.IsNullOrEmpty(githubOwner))
            {
                throw new Exception("Context variable \"github-owner\" required to be set.");
            }

            var githubRepository = this.Node.TryGetContext("github-repo")?.ToString();

            if (string.IsNullOrEmpty(githubRepository))
            {
                throw new Exception("Context variable \"github-repo\" required to be set.");
            }

            var githubOauthToken = this.Node.TryGetContext("github-oauth-token")?.ToString();

            if (string.IsNullOrEmpty(githubOauthToken))
            {
                Console.WriteLine($"Looking for GitHub oauth token in SSM Parameter Store using key: {DEFAULT_OAUTH_PARAMETER_STORE_KEY}");
                githubOauthToken = FetchGitHubPersonalAuthToken();
            }

            Console.WriteLine($"Defining pipelines for {githubOwner}/{githubRepository}");


            CreatePipeline(cloudFormationRole, build, githubOwner, githubRepository, githubOauthToken, "dev");
            CreatePipeline(cloudFormationRole, build, githubOwner, githubRepository, githubOauthToken, "master");
        }
예제 #26
0
 public IManagedPolicy LocateManagedPolicyByName(string policyName)
 {
     return(ManagedPolicy.FromManagedPolicyName(Scope, policyName, policyName));
 }
예제 #27
0
 public IManagedPolicy LocateAwsManagedPolicyByName(string policyName)
 {
     return(ManagedPolicy.FromAwsManagedPolicyName(policyName));
 }
예제 #28
0
        internal AwsServerlessStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            // Create IAM Admin Role
            var iamRole = new Role(this, "Role", new RoleProps {
                RoleName        = "LambdaAdminRole",
                AssumedBy       = new ServicePrincipal("lambda.amazonaws.com"),
                ManagedPolicies = new [] { ManagedPolicy.FromManagedPolicyArn(this, "RolePolicy", "arn:aws:iam::aws:policy/AdministratorAccess") }
            });

            // Create A S3 Bucket
            var s3Bucket = new Bucket(this, "demoS3", new BucketProps {
                BucketName       = "des-inv-app-s3-bckt",
                RemovalPolicy    = RemovalPolicy.DESTROY,
                PublicReadAccess = true,
            });

            // Create A DynamoDB
            var dynamoDBTable = new Table(this, "demoDynamoDB", new TableProps {
                TableName    = "serverless-inventory-app-dynamodb-table",
                PartitionKey = new Attribute {
                    Name = "Store", Type = AttributeType.STRING
                },
                SortKey = new Attribute {
                    Name = "Item", Type = AttributeType.STRING
                },
                BillingMode   = BillingMode.PAY_PER_REQUEST,
                Stream        = StreamViewType.NEW_AND_OLD_IMAGES,
                RemovalPolicy = RemovalPolicy.DESTROY
            });

            // Create Lambda Function for DynamoDB
            var func_DynamoDB = new Function(this, "demoFuncDynamoDB", new FunctionProps {
                Runtime      = Runtime.DOTNET_CORE_3_1,
                FunctionName = "serverless-inventory-app-func-dynamodb",
                Code         = Code.FromAsset("publish_lambda/func_DynamoDB"),
                Handler      = "func_DynamoDB::func_DynamoDB.Function::FunctionHandler",
                Timeout      = Amazon.CDK.Duration.Minutes(3),
                Role         = iamRole,
                //Role = Role.FromRoleArn (this, "fullAccessLambda_DynamoDB", "arn:aws:iam::138340313734:role/Lambda_AdminRole", new FromRoleArnOptions { })
            });

            // Create Lambda Function for SNS
            var func_SNS = new Function(this, "demoFuncSNS", new FunctionProps {
                Runtime      = Runtime.DOTNET_CORE_3_1,
                FunctionName = "serverless-inventory-app-func-sns",
                Code         = Code.FromAsset("publish_lambda/func_SNS"),
                Handler      = "func_SNS::func_SNS.Function::FunctionHandler",
                Timeout      = Amazon.CDK.Duration.Minutes(3),
                Role         = iamRole,
                //Role = Role.FromRoleArn (this, "fullAccessLambda_SNS", "arn:aws:iam::138340313734:role/Lambda_AdminRole", new FromRoleArnOptions { })
            });

            // Create Lambda Function for RestAPI
            var func_GetItems = new Function(this, "demoFuncGetItems", new FunctionProps {
                Runtime      = Runtime.DOTNET_CORE_3_1,
                FunctionName = "serverless-inventory-app-func-getitems",
                Code         = Code.FromAsset("publish_lambda/func_GetItems"),
                Handler      = "func_GetItems::func_GetItems.Function::FunctionHandler",
                Timeout      = Amazon.CDK.Duration.Minutes(3),
                Role         = iamRole,
                //Role = Role.FromRoleArn (this, "fullAccessLambda_GetItems", "arn:aws:iam::138340313734:role/Lambda_AdminRole", new FromRoleArnOptions { })
            });

            // Create API Gateway for Applications
            var apiGateway = new LambdaRestApi(this, "demoAPIGateway", new LambdaRestApiProps {
                Handler     = func_GetItems,
                RestApiName = "serverless-inventory-app-api-inventory",
                Proxy       = false,
            });
            var items = apiGateway.Root.AddResource("api");

            items.AddMethod("GET");

            // Create Lambda Event for Upload Image S3
            func_DynamoDB.AddEventSource(new S3EventSource(s3Bucket, new S3EventSourceProps {
                Events = new [] { EventType.OBJECT_CREATED }
            }));

            // Create Lambda Event for Insert DynamoDB
            func_SNS.AddEventSource(new DynamoEventSource(dynamoDBTable, new DynamoEventSourceProps {
                StartingPosition = StartingPosition.LATEST,
            }));

            // Create A SNS
            var snsTopic = new Topic(this, "demoSNS", new TopicProps {
                TopicName   = "NoStock",
                DisplayName = "Out of Stock Topic",
            });

            snsTopic.AddSubscription(new EmailSubscription("*****@*****.**", new EmailSubscriptionProps {
            }));
        }
예제 #29
0
        internal GrpcBenchmarkStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var vpc = new Vpc(this, "vpc", new VpcProps
            {
                MaxAzs              = 1,
                NatGateways         = 0,
                SubnetConfiguration = new[] { new SubnetConfiguration {
                                                  Name = "public", SubnetType = SubnetType.PUBLIC
                                              } },
            });
            var subnets = new SubnetSelection {
                Subnets = vpc.PublicSubnets
            };
            var sg = new SecurityGroup(this, "MasterSg", new SecurityGroupProps
            {
                AllowAllOutbound = true,
                Vpc = vpc,
            });
            var role = new Role(this, "MasterRole", new RoleProps
            {
                AssumedBy = new ServicePrincipal("ec2.amazonaws.com"),
            });

            role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AmazonSSMManagedInstanceCore"));

            var spot = new AutoScalingGroup(this, "instances", new AutoScalingGroupProps
            {
                // Monitoring is default DETAILED.
                SpotPrice                = "1.0", // 0.0096 for spot price average for m3.medium
                Vpc                      = vpc,
                SecurityGroup            = sg,
                VpcSubnets               = subnets,
                InstanceType             = InstanceType.Of(InstanceClass.COMPUTE5_AMD, InstanceSize.XLARGE4),
                DesiredCapacity          = 1,
                MaxCapacity              = 1,
                MinCapacity              = 0,
                AssociatePublicIpAddress = true,
                MachineImage             = new AmazonLinuxImage(new AmazonLinuxImageProps
                {
                    CpuType        = AmazonLinuxCpuType.X86_64,
                    Generation     = AmazonLinuxGeneration.AMAZON_LINUX_2,
                    Storage        = AmazonLinuxStorage.GENERAL_PURPOSE,
                    Virtualization = AmazonLinuxVirt.HVM,
                }),
                AllowAllOutbound = true,
                GroupMetrics     = new[] { GroupMetrics.All() },
                Role             = role,
                UpdatePolicy     = UpdatePolicy.ReplacingUpdate(),
            });

            // https://gist.github.com/npearce/6f3c7826c7499587f00957fee62f8ee9
            spot.AddUserData(new[]
            {
                "amazon-linux-extras install docker -y",
                "service docker start",
                "chkconfig docker on",
                "usermod -a -G docker ec2-user",
                "curl -L https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose",
                "chmod +x /usr/local/bin/docker-compose",
                "yum install -y git",
                "reboot",
            });
        }
예제 #30
0
        private void ConfigureBeanstalkEnvironment(Configuration settings)
        {
            if (Ec2InstanceProfile == null)
            {
                throw new InvalidOperationException($"{nameof(Ec2InstanceProfile)} has not been set. The {nameof(ConfigureIAM)} method should be called before {nameof(ConfigureBeanstalkEnvironment)}");
            }
            if (ApplicationVersion == null)
            {
                throw new InvalidOperationException($"{nameof(ApplicationVersion)} has not been set. The {nameof(ConfigureApplication)} method should be called before {nameof(ConfigureBeanstalkEnvironment)}");
            }

            var optionSettingProperties = new List <CfnEnvironment.OptionSettingProperty> {
                new CfnEnvironment.OptionSettingProperty {
                    Namespace  = "aws:autoscaling:launchconfiguration",
                    OptionName = "IamInstanceProfile",
                    Value      = Ec2InstanceProfile.AttrArn
                },
                new CfnEnvironment.OptionSettingProperty {
                    Namespace  = "aws:elasticbeanstalk:environment",
                    OptionName = "EnvironmentType",
                    Value      = settings.EnvironmentType
                },
                new CfnEnvironment.OptionSettingProperty
                {
                    Namespace  = "aws:elasticbeanstalk:managedactions",
                    OptionName = "ManagedActionsEnabled",
                    Value      = settings.ElasticBeanstalkManagedPlatformUpdates.ManagedActionsEnabled.ToString().ToLower()
                }
            };

            if (!string.IsNullOrEmpty(settings.InstanceType))
            {
                optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty
                {
                    Namespace  = "aws:autoscaling:launchconfiguration",
                    OptionName = "InstanceType",
                    Value      = settings.InstanceType
                });
            }

            if (settings.EnvironmentType.Equals(ENVIRONMENTTYPE_LOADBALANCED))
            {
                optionSettingProperties.Add(
                    new CfnEnvironment.OptionSettingProperty
                {
                    Namespace  = "aws:elasticbeanstalk:environment",
                    OptionName = "LoadBalancerType",
                    Value      = settings.LoadBalancerType
                }
                    );
            }

            if (!string.IsNullOrEmpty(settings.EC2KeyPair))
            {
                optionSettingProperties.Add(
                    new CfnEnvironment.OptionSettingProperty
                {
                    Namespace  = "aws:autoscaling:launchconfiguration",
                    OptionName = "EC2KeyName",
                    Value      = settings.EC2KeyPair
                }
                    );
            }

            if (settings.ElasticBeanstalkManagedPlatformUpdates.ManagedActionsEnabled)
            {
                BeanstalkServiceRole = new Role(this, nameof(BeanstalkServiceRole), InvokeCustomizeCDKPropsEvent(nameof(BeanstalkServiceRole), this, new RoleProps
                {
                    AssumedBy       = new ServicePrincipal("elasticbeanstalk.amazonaws.com"),
                    ManagedPolicies = new[]
                    {
                        ManagedPolicy.FromAwsManagedPolicyName("AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy")
                    }
                }));

                optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty
                {
                    Namespace  = "aws:elasticbeanstalk:environment",
                    OptionName = "ServiceRole",
                    Value      = BeanstalkServiceRole.RoleArn
                });

                optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty
                {
                    Namespace  = "aws:elasticbeanstalk:managedactions",
                    OptionName = "PreferredStartTime",
                    Value      = settings.ElasticBeanstalkManagedPlatformUpdates.PreferredStartTime
                });

                optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty
                {
                    Namespace  = "aws:elasticbeanstalk:managedactions:platformupdate",
                    OptionName = "UpdateLevel",
                    Value      = settings.ElasticBeanstalkManagedPlatformUpdates.UpdateLevel
                });
            }

            BeanstalkEnvironment = new CfnEnvironment(this, nameof(BeanstalkEnvironment), InvokeCustomizeCDKPropsEvent(nameof(BeanstalkEnvironment), this, new CfnEnvironmentProps
            {
                EnvironmentName = settings.EnvironmentName,
                ApplicationName = settings.BeanstalkApplication.ApplicationName,
                PlatformArn     = settings.ElasticBeanstalkPlatformArn,
                OptionSettings  = optionSettingProperties.ToArray(),
                // This line is critical - reference the label created in this same stack
                VersionLabel = ApplicationVersion.Ref,
            }));
        }