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); }
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(); }
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 }); }
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 } })); }
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") }) { }
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); }
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); }
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 //{ //}); }
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); }
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 }); }
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); }
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); }
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 }); }
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 }; }
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); }
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, }, }), }, }, }, }); }
internal CensusEtlStack(Construct scope, string id, CensusEtlStackProps props) : base(scope, id, props) { var securityGroup = SecurityGroup.FromSecurityGroupId(this, "aurora-sg", props.AuroraSeucrityGroupId); var censusBucket = Bucket.FromBucketName(this, "lambdaBucket", props.CensusArtifactBucket); var awsManagedLambdaPolicy = ManagedPolicy.FromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole"); var queue = new Queue(this, "queue", new QueueProps { QueueName = props.CensusEtlQueue }); new CfnOutput(this, "sqs-queue", new CfnOutputProps { ExportName = "enqueueSQS", Value = queue.QueueUrl }); var enqueueRole = new Role(this, "enqueue-role", new RoleProps { AssumedBy = new ServicePrincipal("lambda.amazonaws.com") }); enqueueRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { censusBucket.BucketArn }, Actions = new string[] { "s3:ListBucket" } })); enqueueRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { queue.QueueArn }, Actions = new string[] { "sqs:SendMessage" } })); enqueueRole.AddManagedPolicy(awsManagedLambdaPolicy); new Function(this, "census-etl", new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, Handler = "EtlEnqueue::EtlEnqueue.Function::FunctionHandler", Code = Code.FromAsset("EtlEnqueue/bin/Debug/netcoreapp3.1/publish"), SecurityGroups = new ISecurityGroup[] { securityGroup }, Role = enqueueRole }); var workerRole = new Role(this, "worker-role", new RoleProps { AssumedBy = new ServicePrincipal("lambda.amazonaws.com") }); workerRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { censusBucket.BucketArn }, Actions = new string[] { "s3:GetObject" } })); workerRole.AddManagedPolicy(awsManagedLambdaPolicy); workerRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { queue.QueueArn }, Actions = new string[] { "sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes", "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" } })); var workerFunction = new Function(this, "worker-function", new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, Handler = "something", Code = Code.FromAsset("EtlEnqueue/bin/Debug/netcoreapp3.1/publish"), SecurityGroups = new ISecurityGroup[] { securityGroup }, ReservedConcurrentExecutions = 2, Role = workerRole }); workerFunction.AddEventSource(new SqsEventSource(queue)); }
public IManagedPolicy LocateAwsManagedPolicyByName(string policyName) { return(ManagedPolicy.FromAwsManagedPolicyName(policyName)); }
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}/" }); }
public static IManagedPolicy[] FromAwsManagedPolicies(params string[] awsPolicyNames) => awsPolicyNames .Where(policy => !string.IsNullOrWhiteSpace(policy)) .Select(policy => ManagedPolicy.FromAwsManagedPolicyName(policy)) .ToArray() ;
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", }); }
internal EksCdkStack(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 repository = new ecr.Repository(this, Constants.ECR_REPOSITORY_ID, new ecr.RepositoryProps { RepositoryName = Constants.ECR_REPOSITORY_NAME }); #region Aurora Database var secGrp = new SecurityGroup(this, Constants.DATABASE_SECURITY_GRP, new SecurityGroupProps { Vpc = vpc }); 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); } var dbsubnetGroup = new rds.CfnDBSubnetGroup(this, Constants.AURORA_DB_SUBNET_ID, new rds.CfnDBSubnetGroupProps { DbSubnetGroupDescription = Constants.AURORA_DB_SUBNET_DESCRIPTION, DbSubnetGroupName = Constants.AURORA_DB_SUBNET_GROUP_NAME, SubnetIds = privateSubnets.ToArray() }); List <CfnTag> cfnDbSecurityGroupTag = new List <CfnTag>(); CfnTag tagName = new CfnTag() { Key = "Name", Value = Constants.APP_NAME }; cfnDbSecurityGroupTag.Add(tagName); var dbSecurityGroup = new CfnSecurityGroup(this, Constants.AURORA_CFN_SG_ID, new CfnSecurityGroupProps { VpcId = vpc.VpcId, GroupName = Constants.AURORA_GROUP_NAME, GroupDescription = "Access to the RDS", Tags = cfnDbSecurityGroupTag.ToArray() } ); var cfnSecurityGroupIngress = new ec2.CfnSecurityGroupIngress( this, Constants.AURORA_SG_INGRESS, new ec2.CfnSecurityGroupIngressProps { Description = Constants.AURORA_SG_INGRESS_DESCRIPTION, FromPort = Constants.AURORA_PORT, ToPort = Constants.AURORA_PORT, IpProtocol = Constants.CONTAINER_PROTOCOL, SourceSecurityGroupId = eksSecGrp.SecurityGroupId, GroupId = dbSecurityGroup.AttrGroupId }); var dbcluster = new rds.CfnDBCluster(this, Constants.AURORA_TODO_DATABASE, new rds.CfnDBClusterProps { Engine = Constants.AURORA_DB_ENGINE, EngineMode = Constants.AURORA_ENGINE_MODE, Port = Constants.AURORA_PORT, MasterUsername = Constants.DB_USER_VALUE, MasterUserPassword = Constants.DB_PASSWORD_VALUE, DbSubnetGroupName = Constants.AURORA_DB_SUBNET_GROUP_NAME, DatabaseName = Constants.DB_NAME_VALUE, VpcSecurityGroupIds = new string[] { dbSecurityGroup.AttrGroupId } }); dbcluster.DbClusterIdentifier = Constants.AURORA_TODO_DATABASE; dbcluster.AddDependsOn(dbsubnetGroup); dbcluster.CfnOptions.DeletionPolicy = CfnDeletionPolicy.DELETE; #endregion #region SSM StringBuilder connString = new StringBuilder(); connString.AppendFormat("server={0}", dbcluster.AttrEndpointAddress); connString.AppendFormat(";port={0}", Constants.AURORA_PORT); connString.AppendFormat(";database={0}", Constants.DB_NAME_VALUE); connString.AppendFormat(";user={0}", Constants.DB_USER_VALUE); connString.AppendFormat(";password={0}", Constants.DB_PASSWORD_VALUE); new ssm.StringParameter(this, "Parameter", new ssm.StringParameterProps { Description = "Maintains the Aurora Database Connection String", ParameterName = Constants.SSM_DB_CONN_STRING, StringValue = connString.ToString(), Tier = ssm.ParameterTier.ADVANCED }); #endregion }
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, })); }
internal AutoDemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { // account and role info var automationAccountId = "123456789"; var automationWorkerRoleName = $"AWS-SystemsManager-AutomationExecutionRole-{Aws.REGION}"; var automationAdminRoleName = $"AWS-SystemsManager-AutomationAdministrationRole-{Aws.REGION}"; //Goes into Automation account Role automationAdminRole = new Role(this, "autoAdminRole", new RoleProps { AssumedBy = new CompositePrincipal( new ServicePrincipal("ssm.amazonaws.com") ), RoleName = automationAdminRoleName, InlinePolicies = new Dictionary <string, PolicyDocument> { ["ExecutionPolicy"] = new PolicyDocument(new PolicyDocumentProps { Statements = new PolicyStatement[] { new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new [] { $"arn:aws:iam::*:role/{automationWorkerRoleName}" },//construct this Actions = new [] { "sts:AssumeRole" } }), new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new [] { "*" }, Actions = new [] { "organizations:ListAccountsForParent" } }) } }) } }); var listResourceGroups = new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new[] { "*" }, Actions = new[] { "resource-groups:ListGroupResources", "tag:GetResources" } }); var passRole = new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new[] { Arn.Format(new ArnComponents { Account = automationAccountId, Region = "", Resource = "role", ResourceName = automationWorkerRoleName, Service = "iam" }, this) }, Actions = new[] { "iam:PassRole" } }); var managedPolicyTest = new ManagedPolicy(this, "test-managed-policy", new ManagedPolicyProps { Statements = new PolicyStatement[] { listResourceGroups, passRole } }); //Goes into all accounts Role automationWorkerRole = new Role(this, "automasterrole", new RoleProps { AssumedBy = new CompositePrincipal( new AccountPrincipal(automationAccountId), new ServicePrincipal("ssm.amazonaws.com") ), RoleName = automationWorkerRoleName, ManagedPolicies = new IManagedPolicy[] { ManagedPolicy.FromAwsManagedPolicyName("service-role/AmazonSSMAutomationRole"), managedPolicyTest }, Path = "/", InlinePolicies = new Dictionary <string, PolicyDocument> { ["ExecutionPolicy"] = new PolicyDocument(new PolicyDocumentProps { Statements = new PolicyStatement[] { new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new [] { "*" }, Actions = new [] { "resource-groups:ListGroupResources", "tag:GetResources" } }), new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new[] { Arn.Format(new ArnComponents { Account = automationAccountId, Region = "", Resource = "role", ResourceName = automationWorkerRoleName, Service = "iam" }, this) }, Actions = new [] { "iam:PassRole" } }) } }) } }); User automationUser = new User(this, "automation-user", new UserProps { UserName = "******" }); Role myLimitedAssumeRole = new Role(this, "roleToAssume", new RoleProps { AssumedBy = new ArnPrincipal(Arn.Format(new ArnComponents { Account = automationAccountId, Region = "", Resource = "user", ResourceName = automationUser.UserName, Service = "iam" }, this)), RoleName = $"Automation-Restricted-{Aws.REGION}", InlinePolicies = new Dictionary <string, PolicyDocument> { ["limited-actions"] = new PolicyDocument(new PolicyDocumentProps { Statements = new PolicyStatement[] { new PolicyStatement(new PolicyStatementProps { Resources = new string[] { "*" }, Actions = new string[] { "ssm:DescribeAutomationExecutions", "ssm:DescribeAutomationStepExecutions", "ssm:DescribeDocument", "ssm:GetAutomationExecution", "ssm:GetDocument", "ssm:ListDocuments", "ssm:ListDocumentVersions", "ssm:StartAutomationExecution" } }), new PolicyStatement(new PolicyStatementProps { Resources = new string[] { Arn.Format(new ArnComponents { Account = automationAccountId, Region = "", Resource = "role", ResourceName = automationAdminRoleName, Service = "iam" }, this) }, Actions = new string[] { "iam:PassRole" }, Effect = Effect.ALLOW }) } }) } }); //Automation document for updating AMI's var amiUpdateDoc = new CfnDocument(this, "ami-update-document", new CfnDocumentProps { // Name = "ami-update", DocumentType = "Automation", Content = new Dictionary <string, object> { ["schemaVersion"] = "0.3", ["description"] = "Updates Parameter store with the latest AMI for specific images", ["assumeRole"] = "{{ AutomationAssumeRole }}", ["parameters"] = new Dictionary <string, object> { ["AutomationAssumeRole"] = new Dictionary <string, string> { ["type"] = "String", ["description"] = "(Optional) The ARN of the role that allows Automation to perform the actions on your behalf" }, ["AmiID"] = new Dictionary <string, string> { ["type"] = "String", ["description"] = "(Required) The image ID for the new AMI" }, ["ImageName"] = new Dictionary <string, string> { ["type"] = "String", ["description"] = "(Required) The name of the image which shoud have the AMI ID updated." } }, ["mainSteps"] = new Dictionary <string, object>[] { new Dictionary <string, object> { ["action"] = "aws:executeAwsApi", ["name"] = "getCurrentValue", ["inputs"] = new Dictionary <string, object> { ["Api"] = "GetParameter", ["Name"] = "/amis/{{ ImageName }}/id", ["Service"] = "ssm" }, ["outputs"] = new Dictionary <string, object>[] { new Dictionary <string, object> { ["Name"] = "value", ["Selector"] = "$.Parameter.Value", ["Type"] = "String" } } }, /*new Dictionary<string,object> { * ["action"] = "aws:branch", * ["name"] = "confirmChange", * ["isEnd"] = true, * ["inputs"] = new Dictionary<string,object> { * ["Choices"] = new Dictionary<string,object>[] { * new Dictionary<string,object> { * ["NextStep"] = "getDeployRole", * ["Not"] = new Dictionary<string,object> { * ["StringEquals"] = "{{ Version }}", * ["Variable"] = "{{ getCurrentValue.value }}" * } * } * } * } * },*/ new Dictionary <string, object> { ["action"] = "aws:executeAwsApi", ["name"] = "putNewVersion", ["inputs"] = new Dictionary <string, object> { ["Api"] = "PutParameter", ["Name"] = "/amis/{{ ImageName }}/id-new", ["Overwrite"] = true, ["Service"] = "ssm", ["Value"] = "{{ AmiID }}", ["Type"] = "String " } } } } }); //create the SSM parameters var param = "/aws/service/ami-windows-latest/Windows_Server-2019-English-Full-ECS_Optimized/image_id"; var lookupParam = StringParameter.ValueForTypedStringParameter(this, param); var lookupParamTest = StringParameter.ValueForTypedStringParameter(this, param); // ami-082a23ee4379053a2 - default Console.WriteLine(lookupParam); new StringParameter(this, $"ami-windows-parameter", new StringParameterProps { Description = $"The AMI ID for the Windows image", ParameterName = $"/amis/windows/id", //Type = ParameterType.AWS_EC2_IMAGE_ID, StringValue = lookupParam, Tier = ParameterTier.STANDARD }); new Amazon.CDK.AWS.SSM.CfnParameter(this, "ami-testing", new Amazon.CDK.AWS.SSM.CfnParameterProps { DataType = "aws:ec2:image", Description = "Testing ami data type", Name = "/amis/windows-test/id", Type = "String", Value = lookupParamTest }); new StringParameter(this, "ami-deploy-document-parameter", new StringParameterProps { Description = "The name of the SSM document for rolling out new AMI's", ParameterName = $"/ci-deploy/ci-deploy-document", StringValue = amiUpdateDoc.Ref, Tier = ParameterTier.STANDARD }); }
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)); }
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"); }