请求协助编写集成CodePipeline等服务的AWS CI/CD CloudFormation脚本
Hey Dave, glad to walk you through building a full AWS CI/CD pipeline with CloudFormation! I’ve put together a complete template that ties together CodeCommit, CodeBuild, CodeDeploy, and CodePipeline, with clear explanations so you can follow along and tweak it to your needs.
AWSTemplateFormatVersion: '2010-09-09' Description: AWS CI/CD Pipeline with CodeCommit, CodeBuild, CodeDeploy, CodePipeline # IAM Roles - Critical for service permissions Resources: # Role for CodePipeline to interact with other AWS services CodePipelineServiceRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: codepipeline.amazonaws.com Action: sts:AssumeRole Path: / Policies: - PolicyName: CodePipelinePermissions PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - codecommit:GetBranch - codecommit:GetCommit - codecommit:UploadArchive - codecommit:GetUploadArchiveStatus - codecommit:CancelUploadArchive - codebuild:StartBuild - codebuild:BatchGetBuilds - codedeploy:CreateDeployment - codedeploy:GetDeployment - codedeploy:GetDeploymentConfig - codedeploy:RegisterApplicationRevision - s3:GetObject - s3:GetObjectVersion - s3:GetBucketVersioning Resource: "*" # Role for CodeBuild to access resources and run builds CodeBuildServiceRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: codebuild.amazonaws.com Action: sts:AssumeRole Path: / Policies: - PolicyName: CodeBuildPermissions PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - codecommit:GitPull - s3:GetObject - s3:PutObject - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: "*" # Role for CodeDeploy to manage deployments to EC2 instances CodeDeployServiceRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: codedeploy.amazonaws.com Action: sts:AssumeRole Path: / Policies: - PolicyName: CodeDeployPermissions PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - ec2:DescribeInstances - ec2:DescribeInstanceStatus - ec2:TerminateInstances - autoscaling:DescribeAutoScalingGroups - autoscaling:DescribeAutoScalingInstances - autoscaling:UpdateAutoScalingGroup - autoscaling:PutLifecycleHook Resource: "*" # CodeCommit Repository - Stores your source code MyCodeCommitRepo: Type: AWS::CodeCommit::Repository Properties: RepositoryName: MyAppRepo RepositoryDescription: Source code repository for my application # CodeBuild Project - Builds your application code MyCodeBuildProject: Type: AWS::CodeBuild::Project Properties: Name: MyAppBuild Description: Build project for my application ServiceRole: !GetAtt CodeBuildServiceRole.Arn Source: Type: CODECOMMIT Location: !Sub https://git-codecommit.${AWS::Region}.amazonaws.com/v1/repos/${MyCodeCommitRepo} Environment: Type: LINUX_CONTAINER ComputeType: BUILD_GENERAL1_SMALL Image: aws/codebuild/amazonlinux2-x86_64-standard:3.0 EnvironmentVariables: - Name: S3_BUCKET Value: !Ref BuildArtifactsBucket Artifacts: Type: S3 Location: !Ref BuildArtifactsBucket Name: build-output.zip # S3 Bucket to store build artifacts and pipeline artifacts BuildArtifactsBucket: Type: AWS::S3::Bucket Properties: VersioningConfiguration: Status: Enabled # CodeDeploy Application - Defines the application to deploy MyCodeDeployApp: Type: AWS::CodeDeploy::Application Properties: ApplicationName: MyAppDeploy ComputePlatform: Server # CodeDeploy Deployment Group - Targets EC2 instances for deployment MyCodeDeployDeploymentGroup: Type: AWS::CodeDeploy::DeploymentGroup Properties: ApplicationName: !Ref MyCodeDeployApp DeploymentGroupName: MyAppDeploymentGroup ServiceRoleArn: !GetAtt CodeDeployServiceRole.Arn DeploymentConfigName: CodeDeployDefault.AllAtOnce Ec2TagFilters: - Key: Environment Value: Production Type: KEY_AND_VALUE # Note: Ensure your EC2 instances have the CodeDeploy agent installed and the above tag # CodePipeline Pipeline - Orchestrates the CI/CD workflow MyCodePipeline: Type: AWS::CodePipeline::Pipeline Properties: Name: MyAppPipeline RoleArn: !GetAtt CodePipelineServiceRole.Arn ArtifactStore: Type: S3 Location: !Ref BuildArtifactsBucket Stages: # Source Stage: Pull code from CodeCommit - Name: Source Actions: - Name: CodeCommitSource ActionTypeId: Category: Source Owner: AWS Provider: CodeCommit Version: '1' Configuration: RepositoryName: !Ref MyCodeCommitRepo BranchName: main OutputArtifacts: - Name: SourceCode RunOrder: 1 # Build Stage: Run CodeBuild to build the application - Name: Build Actions: - Name: CodeBuildAction ActionTypeId: Category: Build Owner: AWS Provider: CodeBuild Version: '1' Configuration: ProjectName: !Ref MyCodeBuildProject InputArtifacts: - Name: SourceCode OutputArtifacts: - Name: BuildArtifacts RunOrder: 1 # Deploy Stage: Deploy to EC2 via CodeDeploy - Name: Deploy Actions: - Name: CodeDeployAction ActionTypeId: Category: Deploy Owner: AWS Provider: CodeDeploy Version: '1' Configuration: ApplicationName: !Ref MyCodeDeployApp DeploymentGroupName: !Ref MyCodeDeployDeploymentGroup InputArtifacts: - Name: BuildArtifacts RunOrder: 1
IAM Roles
Each AWS CI/CD service needs a dedicated IAM role with permissions to interact with other services:
- CodePipelineServiceRole: Lets CodePipeline trigger CodeBuild builds, send artifacts to S3, and initiate CodeDeploy deployments.
- CodeBuildServiceRole: Grants CodeBuild access to pull code from CodeCommit, store build outputs in S3, and log build details to CloudWatch.
- CodeDeployServiceRole: Allows CodeDeploy to manage EC2 instances, check their status, and perform deployments.
CodeCommit Repository
This is your private Git repository in AWS where you’ll store your application source code. The template creates a repo named MyAppRepo—feel free to rename this to match your project.
CodeBuild Project
The build stage uses this project to compile, test, and package your code. It uses the standard Amazon Linux 2 build image, and outputs the build artifact to the S3 bucket. You’ll need to add a buildspec.yml file to your CodeCommit repo to define build steps (e.g., install dependencies, run tests).
S3 Bucket
This bucket stores both the build artifacts from CodeBuild and the intermediate artifacts used by CodePipeline. Versioning is enabled to keep track of artifact versions.
CodeDeploy Application & Deployment Group
- CodeDeploy Application: A logical container for your deployment targets.
- Deployment Group: Defines which EC2 instances to deploy to (using the
Environment: Productiontag). Make sure your EC2 instances have the CodeDeploy agent installed and the correct tag before running the deployment.
CodePipeline Pipeline
This is the orchestrator that ties everything together:
- Source Stage: Pulls the latest code from the CodeCommit
mainbranch. - Build Stage: Runs the CodeBuild project to process the source code.
- Deploy Stage: Uses CodeDeploy to push the build artifact to your EC2 instances.
- Add a buildspec.yml: Create this file in your CodeCommit repo root to define your build steps (example below):
version: 0.2 phases: install: commands: - echo Installing dependencies... - npm install build: commands: - echo Building application... - npm run build post_build: commands: - echo Packaging build output... - zip -r build-output.zip ./dist artifacts: files: - build-output.zip - Prepare EC2 Instances: Install the CodeDeploy agent on your EC2 instances and tag them with
Environment: Production. - Deploy the Template: Use the AWS CLI (
aws cloudformation deploy --template-file ci-cd-pipeline.yml --stack-name MyCICDPipeline) or AWS Console to launch the stack.
内容的提问来源于stack exchange,提问作者Dave

