Esempio n. 1
0
        private void CreatePipeline(IRole cloudFormationRole, PipelineProject build, string githubOwner, string githubRepository, string githubOauthToken, string gitBranch)
        {
            Console.WriteLine($"... defining {gitBranch} pipeline");

            var buildOutput = new Artifact_("BuildOutput");


            new Pipeline(this, "Pipeline-" + gitBranch, new PipelineProps
            {
                Stages = new StageProps[]
                {
                    new StageProps
                    {
                        StageName = "Source",
                        Actions   = new IAction[]
                        {
                            new GitHubSourceAction(new GitHubSourceActionProps
                            {
                                ActionName = "GitHubSource",
                                Branch     = gitBranch,
                                Repo       = githubRepository,
                                Owner      = githubOwner,
                                OauthToken = SecretValue.PlainText(githubOauthToken),
                                Output     = SourceOutput
                            })
                        }
                    },
                    new StageProps
                    {
                        StageName = "Build",
                        Actions   = new IAction[]
                        {
                            new CodeBuildAction(new CodeBuildActionProps
                            {
                                ActionName = $"Build-{gitBranch}",
                                Project    = build,
                                Input      = SourceOutput,
                                Outputs    = new Artifact_[] { buildOutput }
                            })
                        }
                    },
                    new StageProps
                    {
                        StageName = "Deploy",
                        Actions   = new IAction[]
                        {
                            new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps
                            {
                                ActionName       = "DeployServerlessTemplate",
                                Capabilities     = new CloudFormationCapabilities[] { CloudFormationCapabilities.ANONYMOUS_IAM, CloudFormationCapabilities.AUTO_EXPAND },
                                TemplatePath     = ArtifactPath_.ArtifactPath(buildOutput.ArtifactName, "updated.template"),
                                StackName        = $"{githubRepository}-{gitBranch}-{DateTime.Now.Ticks}",
                                AdminPermissions = true
                            })
                        }
                    }
                }
            });
        }
        internal DotnetPipelineStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            string REPO_NAME  = "dotnet-pipeline";
            string STACK_NAME = "DotnetFunctionalStack";

            var code = Repository.FromRepositoryName(this, "ImportedRepo", REPO_NAME);

            var sourceOutput = new Artifact_();

            var cdkDeploy = new PipelineProject(this, "CDKDeploy", new PipelineProjectProps
            {
                BuildSpec = BuildSpec.FromObject(new Dictionary <string, object> {
                    ["version"] = "0.2",
                    ["phases"]  = new Dictionary <string, object>
                    {
                        ["install"] = new Dictionary <string, string>
                        {
                            ["commands"] = "npm install -g aws-cdk"
                        },
                        ["build"] = new Dictionary <string, object>
                        {
                            ["commands"] = new [] { "src/scripts/build.sh", "cdk deploy " + STACK_NAME }
                        }
                    }
                }),
                Environment = new BuildEnvironment {
                    BuildImage = LinuxBuildImage.AMAZON_LINUX_2_3
                }
            });

            var statement = new Amazon.CDK.AWS.IAM.PolicyStatement();

            statement.Effect = Effect.ALLOW;
            statement.AddActions(new [] { "*" });
            statement.AddAllResources();
            cdkDeploy.Role.AddToPolicy(statement);

            var pipeline = new Amazon.CDK.AWS.CodePipeline.Pipeline(this, "Pipeline", new PipelineProps {
                Stages = new [] {
                    new StageProps
                    {
                        StageName = "Source",
                        Actions   = new []
                        {
                            new CodeCommitSourceAction(new CodeCommitSourceActionProps
                            {
                                ActionName = "Source",
                                Repository = code,
                                Output     = sourceOutput
                            })
                        }
                    },
                    new StageProps
                    {
                        StageName = "Deploy",
                        Actions   = new []
                        {
                            new CodeBuildAction(new CodeBuildActionProps
                            {
                                ActionName = "CDK_Deploy",
                                Project    = cdkDeploy,
                                Input      = sourceOutput
                            })
                        }
                    }
                }
            });
        }
Esempio n. 3
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,
                                },
                            }),
                        },
                    },
                },
            });
        }
Esempio n. 4
0
        public static void Load(PipelineProject project)
        {
            Unload();

            var assemblyPaths = new List <string>();

            var projectRoot = project.Location;

            foreach (var i in project.References)
            {
                var path = Path.Combine(projectRoot, i);

                if (string.IsNullOrEmpty(path))
                {
                    throw new ArgumentException("assemblyFilePath cannot be null!");
                }
                if (!Path.IsPathRooted(path))
                {
                    throw new ArgumentException("assemblyFilePath must be absolute!");
                }

                // Make sure we're not adding the same assembly twice.
                path = PathHelper.Normalize(path);
                if (!assemblyPaths.Contains(path))
                {
                    assemblyPaths.Add(path);
                }
            }

            ResolveAssemblies(assemblyPaths);

            var importerDescriptions = new ImporterTypeDescription[_importers.Count];
            var cur = 0;

            foreach (var item in _importers)
            {
                // Find the abstract base class ContentImporter<T>.
                var baseType = item.Type.BaseType;
                while (!baseType.IsAbstract)
                {
                    baseType = baseType.BaseType;
                }

                var outputType = baseType.GetGenericArguments()[0];
                var name       = item.Attribute.DisplayName;
                if (string.IsNullOrEmpty(name))
                {
                    name = item.GetType().Name;
                }
                var desc = new ImporterTypeDescription()
                {
                    TypeName         = item.Type.Name,
                    DisplayName      = name,
                    DefaultProcessor = item.Attribute.DefaultProcessor,
                    FileExtensions   = item.Attribute.FileExtensions,
                    OutputType       = outputType,
                };
                importerDescriptions[cur] = desc;
                cur++;
            }

            Importers = importerDescriptions;
            ImportersStandardValuesCollection = new TypeConverter.StandardValuesCollection(Importers);

            var processorDescriptions = new ProcessorTypeDescription[_processors.Count];

            const BindingFlags bindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;

            cur = 0;
            foreach (var item in _processors)
            {
                var obj            = Activator.CreateInstance(item.Type);
                var typeProperties = item.Type.GetProperties(bindings);
                var properties     = new List <ProcessorTypeDescription.Property>();
                foreach (var i in typeProperties)
                {
                    var attrs     = i.GetCustomAttributes(true);
                    var name      = i.Name;
                    var browsable = true;
                    var defvalue  = i.GetValue(obj, null);

                    foreach (var a in attrs)
                    {
                        if (a is BrowsableAttribute)
                        {
                            browsable = (a as BrowsableAttribute).Browsable;
                        }
                        else if (a is DisplayNameAttribute)
                        {
                            name = (a as DisplayNameAttribute).DisplayName;
                        }
                    }

                    var p = new ProcessorTypeDescription.Property()
                    {
                        Name         = i.Name,
                        DisplayName  = name,
                        Type         = i.PropertyType,
                        DefaultValue = defvalue,
                        Browsable    = browsable
                    };
                    properties.Add(p);
                }

                var inputType = (obj as IContentProcessor).InputType;
                var desc      = new ProcessorTypeDescription()
                {
                    TypeName    = item.Type.Name,
                    DisplayName = item.Attribute.DisplayName,
                    Properties  = new ProcessorTypeDescription.ProcessorPropertyCollection(properties),
                    InputType   = inputType,
                };
                if (string.IsNullOrEmpty(desc.DisplayName))
                {
                    desc.DisplayName = desc.TypeName;
                }

                processorDescriptions[cur] = desc;
                cur++;
            }

            Processors = processorDescriptions;
            ProcessorsStandardValuesCollection = new TypeConverter.StandardValuesCollection(Processors);
        }
Esempio n. 5
0
        internal CICD(
            CdkStack stack,
            CfnParameter targetPlatform,
            LoadBalancedInstancesResult frontEndInstanceInfo,
            LoadBalancedInstancesResult restAPIInstanceInfo)
        {
            var artifactBucket = new Bucket(stack, "ArtifactBucket");
            var repo           = new Repository(stack, "ApplicationRepository", new RepositoryProps
            {
                RepositoryName = stack.StackName,
                Description    = $"Contains the code for the {stack.StackName} application."
            });
            var cfnRepo = repo.Node.DefaultChild as Amazon.CDK.AWS.CodeCommit.CfnRepository;

            cfnRepo.Code = new CfnRepository.CodeProperty
            {
                S3 = new CfnRepository.S3Property
                {
                    Bucket = SourceBucketName,
                    Key    = SourceBucketKey
                }
            };

            var build = new PipelineProject(stack, "ApplicationBuild", new PipelineProjectProps
            {
                Environment = new BuildEnvironment
                {
                    BuildImage           = LinuxBuildImage.AMAZON_LINUX_2_3,
                    EnvironmentVariables = new Dictionary <string, IBuildEnvironmentVariable> {
                        {
                            "TARGET_OS",
                            new BuildEnvironmentVariable {
                                Type  = BuildEnvironmentVariableType.PLAINTEXT,
                                Value = targetPlatform.Value
                            }
                        }
                    }
                }
            });
            var frontEndApplication = new ServerApplication(stack, "FrontEnd", new ServerApplicationProps
            {
                ApplicationName = $"{stack.StackName}-FrontEnd"
            });
            var frontEndDeploymentGroup = new ServerDeploymentGroup(stack, "FrontEndDeploymentGroup", new ServerDeploymentGroupProps
            {
                Application         = frontEndApplication,
                DeploymentGroupName = $"{stack.StackName.ToLower()}-frontend-deployment-group",
                //Role = new Role(stack, "DeploymentServiceRole", new RoleProps
                //{
                //    AssumedBy = new ServicePrincipal("codedeploy.amazonaws.com"),
                //    Description = "Allows Application Deployment.",
                //    ManagedPolicies = new[] { ManagedPolicy.FromAwsManagedPolicyName("service-role/AWSCodeDeployRole") }
                //}),
                //AutoRollback = new AutoRollbackConfig { FailedDeployment = true },
                //DeploymentConfig = ServerDeploymentConfig.HALF_AT_A_TIME,
                LoadBalancer      = LoadBalancer.Application(frontEndInstanceInfo.TargetGroup),
                AutoScalingGroups = new[] { frontEndInstanceInfo.AutoScalingGroup }
            });
            var restApiApplication = new ServerApplication(stack, "RestAPI", new ServerApplicationProps
            {
                ApplicationName = $"{stack.StackName}-RESTAPI"
            });
            var restApiDeploymentGroup = new ServerDeploymentGroup(stack, "RestAPIDeploymentGroup", new ServerDeploymentGroupProps
            {
                Application         = restApiApplication,
                DeploymentGroupName = $"{stack.StackName.ToLower()}-restapi-deployment-group",
                //AutoRollback = new AutoRollbackConfig { FailedDeployment = true },
                //DeploymentConfig = ServerDeploymentConfig.HALF_AT_A_TIME,
                LoadBalancer      = LoadBalancer.Application(restAPIInstanceInfo.TargetGroup),
                AutoScalingGroups = new[] { restAPIInstanceInfo.AutoScalingGroup }
            });
            var sourceOutput      = new Artifact_();
            var frontEndArtifacts = new Artifact_("FrontEndOutput");
            var restAPIArtifacts  = new Artifact_("RESTAPIOutput");
            var pipeline          = new Pipeline(stack, "ApplicationPipeline", new PipelineProps
            {
                ArtifactBucket = artifactBucket,
                PipelineName   = $"{stack.StackName}-Pipeline",
                Stages         = new[]
                {
                    new Amazon.CDK.AWS.CodePipeline.StageProps
                    {
                        StageName = "Source",
                        Actions   = new []
                        {
                            new CodeCommitSourceAction(new CodeCommitSourceActionProps
                            {
                                ActionName = "Source",
                                Repository = repo,
                                Output     = sourceOutput
                            })
                        }
                    },
                    new Amazon.CDK.AWS.CodePipeline.StageProps
                    {
                        StageName = "Build",
                        Actions   = new []
                        {
                            new CodeBuildAction(new CodeBuildActionProps
                            {
                                ActionName = "CodeBuild",
                                Project    = build,
                                Input      = sourceOutput,
                                Outputs    = new [] { frontEndArtifacts, restAPIArtifacts }
                            })
                        }
                    },
                    new Amazon.CDK.AWS.CodePipeline.StageProps
                    {
                        StageName = "Deploy",
                        Actions   = new []
                        {
                            new CodeDeployServerDeployAction(new CodeDeployServerDeployActionProps {
                                ActionName      = "DeployFrontEnd",
                                DeploymentGroup = frontEndDeploymentGroup,
                                Input           = frontEndArtifacts
                            }),
                            new CodeDeployServerDeployAction(new CodeDeployServerDeployActionProps {
                                ActionName      = "DeployRESTAPI",
                                DeploymentGroup = restApiDeploymentGroup,
                                Input           = restAPIArtifacts
                            })
                        }
                    }
                }
            });
        }
        public CodeCoveragePipelineStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var buildProjectName = Constants.Project + Constants.BuildProject;
            var buildProject     = new PipelineProject(this, buildProjectName, new PipelineProjectProps
            {
                ProjectName = buildProjectName,
                BuildSpec   = BuildSpec.FromObject(new Dictionary <string, object>
                {
                    ["version"] = "0.2",
                    ["phases"]  = new Dictionary <string, object>
                    {
                        ["install"] = new Dictionary <string, object>
                        {
                            ["runtime-versions"] = new Dictionary <string, object>
                            {
                                ["dotnet"] = "latest"
                            },
                            ["commands"] = new string[]
                            {
                                "dotnet tool install -g dotnet-reportgenerator-globaltool",
                                "export PATH=\"$PATH:/root/.dotnet/tools\""
                            }
                        },
                        ["build"] = new Dictionary <string, object>
                        {
                            ["commands"] = new string[]
                            {
                                "dotnet build",
                                "dotnet test --collect:\"XPlat Code Coverage\" --logger trx",
                                "xmlPath=$(find $CODEBUILD_SRC_DIR/Calculator.Tests/TestResults -name \"*.xml\")",
                                "reportgenerator -reports:$xmlPath -targetdir:$CODEBUILD_SRC_DIR/Calculator.Tests/TestResults/"
                            }
                        }
                    },
                    ["reports"] = new Dictionary <string, object>
                    {
                        [Constants.TestReportGroup] = new Dictionary <string, object>
                        {
                            ["files"] = new string[]
                            {
                                "**/*.trx"
                            },
                            ["base-directory"] = "$CODEBUILD_SRC_DIR/Calculator.Tests/TestResults",
                            ["file-format"]    = "VisualStudioTrx"
                        },
                        [Constants.CodeCoverageReportGroup] = new Dictionary <string, object>
                        {
                            ["files"] = new string[]
                            {
                                "**/*.xml"
                            },
                            ["base-directory"] = "$CODEBUILD_SRC_DIR/Calculator.Tests/TestResults",
                            ["file-format"]    = "CoberturaXml"
                        }
                    },
                    ["artifacts"] = new Dictionary <string, object>
                    {
                        ["files"] = new string[]
                        {
                            "**/*"
                        },
                        ["name"]           = "coverlet-$(date +%Y-%m-%d)",
                        ["base-directory"] = "$CODEBUILD_SRC_DIR/Calculator.Tests/TestResults/"
                    }
                }),
                Environment = new BuildEnvironment
                {
                    BuildImage = LinuxBuildImage.AMAZON_LINUX_2_3
                }
            });

            var bucketName          = "codepipeline-ap-southeast-2-822565979272";
            var testReportGroupName = buildProjectName + "-" + Constants.TestReportGroup;
            var testReportGroup     = new CfnReportGroup(this, "TestReportGroup", new CfnReportGroupProps
            {
                Name         = testReportGroupName,
                Type         = "TEST",
                ExportConfig = new CfnReportGroup.ReportExportConfigProperty {
                    ExportConfigType = "S3",
                    S3Destination    = new CfnReportGroup.S3ReportExportConfigProperty {
                        Bucket    = bucketName,
                        Packaging = "NONE",
                        Path      = "TestReports"
                    }
                }
            });

            var codeCoverageReportGroupName = buildProjectName + "-" + Constants.CodeCoverageReportGroup;
            var CodeCoverageReportGroup     = new CfnReportGroup(this, "CodeCoverageReportGroup", new CfnReportGroupProps
            {
                Name         = codeCoverageReportGroupName,
                Type         = "CODE_COVERAGE",
                ExportConfig = new CfnReportGroup.ReportExportConfigProperty {
                    ExportConfigType = "S3",
                    S3Destination    = new CfnReportGroup.S3ReportExportConfigProperty {
                        Bucket    = bucketName,
                        Packaging = "NONE",
                        Path      = "CodeCoverageReports"
                    }
                }
            });

            buildProject.AddToRolePolicy(
                new PolicyStatement(new PolicyStatementProps
            {
                Effect  = Effect.ALLOW,
                Actions = new []
                {
                    "codebuild:BatchPutCodeCoverages"
                },
                Resources = new []
                {
                    Fn.Join("", new string[]
                    {
                        "arn:",
                        Fn.Ref("AWS::Partition"),
                        ":codebuild:",
                        Fn.Ref("AWS::Region"),
                        ":",
                        Fn.Ref("AWS::AccountId"),
                        ":report-group/",
                        buildProject.ProjectName,
                        "-*"
                    })
                }
            })
                );

            var code            = Repository.FromRepositoryName(this, "TestCoverageRepo", "TestCoverageRepo");
            var artifactsBucket = Bucket.FromBucketName(this, "BucketByName", bucketName);
            var sourceOutput    = new Artifact_("sourceArtifact");
            var buildOutput     = new Artifact_("buildArtifact");
            var pipelineName    = Constants.Project + "Pipeline";

            new Pipeline(this, pipelineName, new PipelineProps
            {
                PipelineName   = pipelineName,
                ArtifactBucket = artifactsBucket,
                Stages         = new[]
                {
                    new StageProps
                    {
                        StageName = "Source",
                        Actions   = new []
                        {
                            new CodeCommitSourceAction(new CodeCommitSourceActionProps
                            {
                                ActionName = "SourceAction",
                                Repository = code,
                                Output     = sourceOutput
                            })
                        }
                    },
                    new StageProps
                    {
                        StageName = "Build",
                        Actions   = new []
                        {
                            new CodeBuildAction(new CodeBuildActionProps
                            {
                                ActionName = "BuildAction",
                                Project    = buildProject,
                                Input      = sourceOutput,
                                Outputs    = new [] { buildOutput }
                            })
                        }
                    },
                }
            });
        }
Esempio n. 7
0
        private Amazon.CDK.AWS.CodePipeline.IStageOptions GetPipelineStage(
            DeploymentEnvironment deployEnv,
            string apiName,
            Artifact_ cdkBuildOutput,
            IRole crossAccountRole,
            IRole deploymentRole,
            IRole pipelineRole,
            Artifact_ sourceOutputArtifact,
            PipelineProject containerBuildProject)
        {
            var ecrStackName   = $"{apiName}api-{deployEnv.EnvironmentName}-ecrrepo";
            var ecrRepoName    = $"{apiName}api-{deployEnv.EnvironmentName}-repo";
            var ecrRegistry    = $"{deployEnv.AccountId}.dkr.ecr.us-east-1.amazonaws.com";
            var ecrImageId     = $"{ecrRegistry}/{ecrRepoName}";
            var infraStackName = $"{apiName}api-{deployEnv.EnvironmentName}-infra";

            return(new Amazon.CDK.AWS.CodePipeline.StageOptions
            {
                StageName = $"Deploy_{deployEnv.EnvironmentName}",
                Actions = new Amazon.CDK.AWS.CodePipeline.Action[]
                {
                    new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps {
                        ActionName = "Create_ECR",
                        TemplatePath = cdkBuildOutput.AtPath($"{ecrStackName}.template.json"),
                        StackName = ecrStackName,
                        AdminPermissions = true,
                        Role = crossAccountRole,
                        DeploymentRole = deploymentRole,
                        CfnCapabilities = new[] { CfnCapabilities.ANONYMOUS_IAM },
                        RunOrder = 1
                    }),
                    new CodeBuildAction(new CodeBuildActionProps {
                        ActionName = "Lambda_Image_Build",
                        Project = containerBuildProject,
                        Input = sourceOutputArtifact,
                        Role = pipelineRole,
                        EnvironmentVariables = new Dictionary <string, IBuildEnvironmentVariable> {
                            {
                                "ECR_REGISTRY", new BuildEnvironmentVariable {
                                    Type = BuildEnvironmentVariableType.PLAINTEXT,
                                    Value = ecrRegistry
                                }
                            }, {
                                "ECR_IMAGE", new BuildEnvironmentVariable {
                                    Type = BuildEnvironmentVariableType.PLAINTEXT,
                                    Value = ecrImageId
                                }
                            }
                        },
                        RunOrder = 2
                    }),
                    new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps {
                        ActionName = "Deploy",
                        TemplatePath = cdkBuildOutput.AtPath($"{infraStackName}.template.json"),
                        StackName = infraStackName,
                        AdminPermissions = true,
                        Role = crossAccountRole,
                        DeploymentRole = deploymentRole,
                        CfnCapabilities = new[] { CfnCapabilities.ANONYMOUS_IAM },
                        ParameterOverrides = new Dictionary <string, object> {
                            { "ImageTag", "#{SourceVariables.CommitId}" }
                        },
                        RunOrder = 3
                    })
                }
            });
        }
        internal AppdeploymentStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            #region Application hosting resources

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

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

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

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

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

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

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

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

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

            #endregion

            #region CI/CD resources

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

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

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

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

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

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

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

            #endregion
        }
Esempio n. 9
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");
        }
Esempio n. 10
0
        public CiCdStack(Construct parent, string id, CiCdStackProps props) : base(parent, id, props)
        {
            var apiRepository =
                Amazon.CDK.AWS.CodeCommit.Repository.FromRepositoryArn(this, "Repository", props.apiRepositoryArn);
            var environmentVariables = new Dictionary <string, IBuildEnvironmentVariable>();

            environmentVariables.Add("AWS_ACCOUNT_ID", new BuildEnvironmentVariable()
            {
                Type  = BuildEnvironmentVariableType.PLAINTEXT,
                Value = Aws.ACCOUNT_ID
            });
            environmentVariables.Add("AWS_DEFAULT_REGION", new BuildEnvironmentVariable()
            {
                Type  = BuildEnvironmentVariableType.PLAINTEXT,
                Value = Aws.REGION
            });
            var codebuildProject = new PipelineProject(this, "BuildProject", new PipelineProjectProps
            {
                Environment = new BuildEnvironment
                {
                    ComputeType          = ComputeType.SMALL,
                    BuildImage           = LinuxBuildImage.UBUNTU_14_04_PYTHON_3_5_2,
                    Privileged           = true,
                    EnvironmentVariables = environmentVariables
                }
            });
            var codeBuildPolicy = new PolicyStatement();

            codeBuildPolicy.AddResources(apiRepository.RepositoryArn);
            codeBuildPolicy.AddActions(
                "codecommit:ListBranches",
                "codecommit:ListRepositories",
                "codecommit:BatchGetRepositories",
                "codecommit:GitPull"
                );
            codebuildProject.AddToRolePolicy(
                codeBuildPolicy
                );
            props.ecrRepository.GrantPullPush(codebuildProject.GrantPrincipal);

            var sourceOutput = new Artifact_();
            var sourceAction = new Amazon.CDK.AWS.CodePipeline.Actions.CodeCommitSourceAction(
                new Amazon.CDK.AWS.CodePipeline.Actions.CodeCommitSourceActionProps
            {
                ActionName = "CodeCommit-Source",
                Branch     = "master",
                Trigger    = CodeCommitTrigger.POLL,
                Repository = apiRepository,
                Output     = sourceOutput
            });

            var buildOutput = new Artifact_();
            var buildAction = new CodeBuildAction(new CodeBuildActionProps
            {
                ActionName = "Build",
                Input      = sourceOutput,
                Outputs    = new Artifact_[]
                {
                    buildOutput
                },
                Project = codebuildProject
            });

            var deployAction = new EcsDeployAction(new EcsDeployActionProps
            {
                ActionName = "DeployAction",
                Input      = buildOutput,
                Service    = props.ecsService,
            });

            var pipeline = new Pipeline(this, "Pipeline");

            pipeline.AddStage(new StageOptions
            {
                StageName = "Source",
                Actions   = new Action[] { sourceAction }
            });
            pipeline.AddStage(new StageOptions
            {
                StageName = "Build",
                Actions   = new Action[] { buildAction }
            });
            pipeline.AddStage(new StageOptions
            {
                StageName = "Deploy",
                Actions   = new Action[] { deployAction }
            });
        }
        public ServerlessTodoListPipelineCdkStack(Construct parent, string id, IStackProps props) : base(parent, id, props)
        {
            var frontendBuild = new PipelineProject(this, "CodeBuild", new PipelineProjectProps
            {
                BuildSpec   = BuildSpec.FromSourceFilename("./Application/Final/ServerlessTODOList.Frontend/buildspec.yml"),
                Environment = new BuildEnvironment
                {
                    BuildImage = LinuxBuildImage.STANDARD_2_0
                }
            });

            var s3PolicyStatement = new PolicyStatement();

            s3PolicyStatement.Effect = Effect.ALLOW;
            s3PolicyStatement.AddActions("s3:*");
            s3PolicyStatement.AddResources("arn:aws:s3:::normj-east1/", "arn:aws:s3:::normj-east1/*");
            frontendBuild.Role.AddToPolicy(s3PolicyStatement);

            var sourceOutput = new Artifact_();
            var buildOutput  = new Artifact_("BuildOutput");

            var pipeline = new Pipeline(this, "Pipeline", new PipelineProps
            {
                Stages = new StageProps[]
                {
                    new StageProps
                    {
                        StageName = "Source",
                        Actions   = new IAction[]
                        {
                            new GitHubSourceAction(new GitHubSourceActionProps
                            {
                                ActionName = "GitHubSource",
                                Branch     = "master",
                                Repo       = "ServerlessTODOListTutorial",
                                Owner      = "normj",
                                OauthToken = SecretValue.PlainText(FetchGitHubPersonalAuthToken()),
                                Output     = sourceOutput
                            })
                        }
                    },
                    new StageProps
                    {
                        StageName = "Build",
                        Actions   = new IAction[]
                        {
                            new CodeBuildAction(new CodeBuildActionProps
                            {
                                ActionName = "BuildServerlessTODOListFrontend",
                                Project    = frontendBuild,
                                Input      = sourceOutput,
                                Outputs    = new Artifact_[] { buildOutput }
                            })
                        }
                    },
                    new StageProps
                    {
                        StageName = "Deploy",
                        Actions   = new IAction[]
                        {
                            new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps
                            {
                                ActionName       = "DeployFrontend",
                                Capabilities     = new CloudFormationCapabilities[] { CloudFormationCapabilities.ANONYMOUS_IAM, CloudFormationCapabilities.AUTO_EXPAND },
                                TemplatePath     = ArtifactPath_.ArtifactPath("BuildOutput", "updated.template"),
                                StackName        = "ServerlessFrontendCdk",
                                AdminPermissions = true
                            })
                        }
                    }
                }
            });
        }