AWS DevOps Tools: CodePipeline, CodeBuild, and ECS
· Pavan Y N · aws, devops, cicd, containers, cloud
AWS offers a set of developer tools that cover a container delivery pipeline end to end: AWS CodePipeline orchestrates stages, AWS CodeBuild builds and tests, Amazon ECR stores images, and Amazon ECS on AWS Fargate runs them. EduGeek explains how to wire these together with infrastructure as code, and which parts of older examples have changed: GitHub integration now goes through a connection instead of an OAuth token, pipelines have a V2 type, CodeBuild images have moved to Amazon Linux 2023 and Ubuntu 24.04, and ECS gained built-in blue/green, linear, and canary deployments. The CloudFormation templates were linted with cfn-lint, the Terraform was validated against the AWS provider 6.x schema, and the task definition was registered against a local AWS API emulator; nothing was deployed to a real account.
AWS CodeCommit, the managed Git service, stopped accepting new customers for a period and then reopened. On November 24, 2025 AWS announced that CodeCommit is open to new customers again and published a roadmap that included Git LFS support and additional Regions. This guide uses GitHub as the source, but CodeCommit is a valid option again.
# AWS CodePipeline
## What is CodePipeline?
AWS CodePipeline is a managed continuous delivery service. A pipeline is a sequence of stages (source, build, test, deploy), each made of actions, with artifacts passed between them through an S3 artifact bucket.
## Pipeline types: V1 and V2
CodePipeline has two pipeline types that differ in features and price. V2 adds capabilities that V1 lacks:
| Capability | V1 | V2 |
|---|---|---|
| Pipeline-level variables | Not supported | Supported |
| Triggers filtered by Git tags, branches, pull requests, or file paths | Not supported | Supported |
QUEUED and PARALLEL execution modes | Not supported | Supported |
| Stage rollback, stage conditions, automatic stage retry | Not supported | Supported |
| Source revision overrides and the Commands action | Not supported | Supported |
The type is set by PipelineType (CloudFormation) or pipeline_type (Terraform, which documents V1 as its default). Adding V2-only settings such as Git tag triggers to a pipeline definition makes it a V2 pipeline with the associated pricing, so set the type explicitly and check the CodePipeline pricing page first.
## The pipeline in CloudFormation
The template below creates the artifact bucket, the GitHub connection, an ECR repository, the pipeline with its least-privilege role, and the CodeBuild project with its role.
pipeline.yml:
AWSTemplateFormatVersion: '2010-09-09'
Description: CI/CD pipeline for a containerized application on Amazon ECS
Parameters:
FullRepositoryId:
Type: String
Description: GitHub repository in owner/name form
BranchName:
Type: String
Default: main
ClusterName:
Type: String
ServiceName:
Type: String
ContainerName:
Type: String
Default: myapp
EcsTaskRoleArns:
Type: CommaDelimitedList
Description: ARNs of the task and task execution roles the ECS service uses
DockerHubSecretArn:
Type: String
Description: Secrets Manager secret with username and token keys for Docker Hub
Resources:
ArtifactBucket:
Type: AWS::S3::Bucket
Properties:
VersioningConfiguration:
Status: Enabled
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
LifecycleConfiguration:
Rules:
- Id: DeleteOldArtifacts
Status: Enabled
ExpirationInDays: 30
# A connection is created in the PENDING state; complete the GitHub
# authorization once in the Developer Tools console before the first run.
GitHubConnection:
Type: AWS::CodeStarConnections::Connection
Properties:
ConnectionName: !Sub '${AWS::StackName}-github'
ProviderType: GitHub
ImageRepository:
Type: AWS::ECR::Repository
Properties:
ImageTagMutability: IMMUTABLE
ImageScanningConfiguration:
ScanOnPush: true
BuildLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/codebuild/${AWS::StackName}'
RetentionInDays: 30
Pipeline:
Type: AWS::CodePipeline::Pipeline
Properties:
Name: !Sub '${AWS::StackName}-pipeline'
PipelineType: V2
RoleArn: !GetAtt PipelineRole.Arn
ArtifactStore:
Type: S3
Location: !Ref ArtifactBucket
Stages:
- Name: Source
Actions:
- Name: SourceAction
ActionTypeId:
Category: Source
Owner: AWS
Provider: CodeStarSourceConnection
Version: '1'
Configuration:
ConnectionArn: !Ref GitHubConnection
FullRepositoryId: !Ref FullRepositoryId
BranchName: !Ref BranchName
OutputArtifactFormat: CODE_ZIP
OutputArtifacts:
- Name: SourceOutput
- Name: Build
Actions:
- Name: BuildAction
ActionTypeId:
Category: Build
Owner: AWS
Provider: CodeBuild
Version: '1'
Configuration:
ProjectName: !Ref BuildProject
InputArtifacts:
- Name: SourceOutput
OutputArtifacts:
- Name: BuildOutput
- Name: Deploy
Actions:
- Name: DeployAction
ActionTypeId:
Category: Deploy
Owner: AWS
Provider: ECS
Version: '1'
Configuration:
ClusterName: !Ref ClusterName
ServiceName: !Ref ServiceName
FileName: imagedefinitions.json
InputArtifacts:
- Name: BuildOutput
PipelineRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: codepipeline.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: PipelinePolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: ArtifactStore
Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectVersion
- s3:PutObject
- s3:GetBucketVersioning
Resource:
- !GetAtt ArtifactBucket.Arn
- !Sub '${ArtifactBucket.Arn}/*'
- Sid: UseGitHubConnection
Effect: Allow
Action:
- codeconnections:UseConnection
- codestar-connections:UseConnection
Resource: !Ref GitHubConnection
- Sid: RunBuild
Effect: Allow
Action:
- codebuild:BatchGetBuilds
- codebuild:StartBuild
Resource: !GetAtt BuildProject.Arn
- Sid: DeployToEcs
Effect: Allow
Action:
- ecs:DescribeTaskDefinition
- ecs:RegisterTaskDefinition
Resource: '*'
- Sid: UpdateEcsService
Effect: Allow
Action:
- ecs:DescribeServices
- ecs:UpdateService
Resource: !Sub 'arn:${AWS::Partition}:ecs:${AWS::Region}:${AWS::AccountId}:service/${ClusterName}/${ServiceName}'
- Sid: PassTaskRoles
Effect: Allow
Action: iam:PassRole
Resource: !Ref EcsTaskRoleArns
Condition:
StringEquals:
iam:PassedToService:
- ecs.amazonaws.com
- ecs-tasks.amazonaws.com
BuildProject:
Type: AWS::CodeBuild::Project
Properties:
Name: !Sub '${AWS::StackName}-build'
ServiceRole: !GetAtt BuildRole.Arn
Artifacts:
Type: CODEPIPELINE
Environment:
Type: LINUX_CONTAINER
ComputeType: BUILD_GENERAL1_MEDIUM
Image: aws/codebuild/amazonlinux-x86_64-standard:6.0
PrivilegedMode: true # required to run docker build
EnvironmentVariables:
- Name: REGISTRY
Value: !Sub '${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com'
- Name: IMAGE_REPO_NAME
Value: !Ref ImageRepository
- Name: CONTAINER_NAME
Value: !Ref ContainerName
Source:
Type: CODEPIPELINE
BuildSpec: buildspec.yml
Cache:
Type: S3
Location: !Sub '${ArtifactBucket}/build-cache'
LogsConfig:
CloudWatchLogs:
Status: ENABLED
GroupName: !Ref BuildLogGroup
BuildRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: codebuild.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: BuildPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: WriteLogs
Effect: Allow
Action:
- logs:CreateLogStream
- logs:PutLogEvents
Resource: !Sub '${BuildLogGroup.Arn}:*'
- Sid: ArtifactsAndCache
Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectVersion
- s3:PutObject
Resource: !Sub '${ArtifactBucket.Arn}/*'
- Sid: EcrLogin
Effect: Allow
Action: ecr:GetAuthorizationToken
Resource: '*'
- Sid: EcrPush
Effect: Allow
Action:
- ecr:BatchCheckLayerAvailability
- ecr:InitiateLayerUpload
- ecr:UploadLayerPart
- ecr:CompleteLayerUpload
- ecr:PutImage
Resource: !GetAtt ImageRepository.Arn
- Sid: ReadDockerHubSecret
Effect: Allow
Action: secretsmanager:GetSecretValue
Resource: !Ref DockerHubSecretArn
Outputs:
RepositoryUri:
Value: !GetAtt ImageRepository.RepositoryUri
ConnectionArn:
Value: !Ref GitHubConnection
What changed from older versions of this template:
- →GitHub source. The earlier template used the GitHub version 1 action with an
OAuthToken. AWS now describes that action as "not recommended" and recommends the GitHub (via GitHub App) action, backed by a connection and theCodeStarSourceConnectionprovider. A connection created from CloudFormation or the CLI starts inPENDINGstatus, so authorize it once in the console. The pipeline role needsUseConnectionpermission on both thecodeconnectionsandcodestar-connectionsprefixes, because AWS states that both are required. - →Pipeline role. The earlier role attached the managed
AWSCodePipelineFullAccesspolicy and addeds3:*,codebuild:*, andecs:*on every resource. The role above grants only the actions the ECS standard deploy action needs, a pass-role permission restricted to the ECS service principals, and access to the artifact bucket. - →Artifact bucket. It blocks public access, encrypts with SSE-S3, keeps versions, and expires artifacts after 30 days. A fixed
BucketNameis omitted so stack names do not collide in the global bucket namespace. - →Immutable image tags. The ECR repository rejects overwriting a tag, so every deployment must use a unique tag, which the buildspec derives from the commit.
# AWS CodeBuild
## BuildSpec configuration
buildspec.yml:
version: 0.2
env:
variables:
NODE_ENV: production
secrets-manager:
DOCKERHUB_USER: dockerhub:username
DOCKERHUB_TOKEN: dockerhub:token
phases:
install:
runtime-versions:
nodejs: 24
commands:
- npm ci
pre_build:
commands:
- npm run lint
- npm audit --audit-level=high
- echo "$DOCKERHUB_TOKEN" | docker login --username "$DOCKERHUB_USER" --password-stdin
- aws ecr get-login-password --region "$AWS_DEFAULT_REGION" | docker login --username AWS --password-stdin "$REGISTRY"
- IMAGE_TAG=$(echo "$CODEBUILD_RESOLVED_SOURCE_VERSION" | cut -c1-12)
build:
on-failure: ABORT
commands:
# Tests run before anything is built or pushed
- npm test
# The Dockerfile builds the application in a multi-stage build
- docker build -t "$REGISTRY/$IMAGE_REPO_NAME:$IMAGE_TAG" .
- docker push "$REGISTRY/$IMAGE_REPO_NAME:$IMAGE_TAG"
post_build:
commands:
- printf '[{"name":"%s","imageUri":"%s"}]' "$CONTAINER_NAME" "$REGISTRY/$IMAGE_REPO_NAME:$IMAGE_TAG" > imagedefinitions.json
artifacts:
files:
- imagedefinitions.json
cache:
paths:
- 'node_modules/**/*'
- '.npm/**/*'
reports:
test-results:
files:
- 'test-results/**/*'
file-format: JUNITXML
coverage-report:
files:
- 'coverage/cobertura-coverage.xml'
file-format: COBERTURAXML
Points worth knowing:
- →Shared shell. In buildspec version 0.2, CodeBuild runs all commands in the same shell instance, which is why
IMAGE_TAG, set inpre_build, is visible inbuildandpost_build. - →Phase failure handling. The documentation guarantees only that the
UPLOAD_ARTIFACTSphase is always attempted even ifBUILDfails, and it does not state thatpost_buildis skipped after a failed build. The earlier buildspec ran tests inpost_build, after the image was already pushed. The version above runs tests first, pushes only after they pass, and setson-failure: ABORTon thebuildphase so a failure stops the build. - →Immutable tags. The tag is the first 12 characters of
CODEBUILD_RESOLVED_SOURCE_VERSION, which is the commit ID for GitHub sources, so each image is traceable to a commit. - →Secrets. AWS recommends the
secrets-managerandparameter-storemappings for sensitive values because plain environment variables can be displayed in the console and CLI. Thesecrets-managervalue has the formsecret-id:json-key:version-stage:version-id. The earlier example loaded database credentials into a build; build-time access to production secrets is rarely necessary, so this version fetches only Docker Hub credentials, which avoid anonymous pull rate limits for base images. - →Report formats.
file-formatvalues are not case sensitive, andJUNITXMLis the default.
## Build images and runtimes
The CodeBuild project above uses aws/codebuild/amazonlinux-x86_64-standard:6.0 (Amazon Linux 2023). The current Ubuntu image is aws/codebuild/standard:8.0 (Ubuntu 24.04); standard:7.0, used in earlier versions of this guide, is Ubuntu 22.04 and still listed. Runtime names depend on the image: nodejs: 24 is available on both the Amazon Linux 2023 6.0 image and the Ubuntu 8.0 image. Always specify a runtime version, because the default changes when a version reaches end of life.
PrivilegedMode: true is required to run the Docker daemon for docker build.
# Amazon ECS (Elastic Container Service)
## Task definition
{
"family": "myapp-task",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "512",
"memory": "1024",
"runtimePlatform": {
"operatingSystemFamily": "LINUX",
"cpuArchitecture": "X86_64"
},
"executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
"taskRoleArn": "arn:aws:iam::123456789012:role/ecsTaskRole",
"containerDefinitions": [
{
"name": "myapp",
"image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/myapp:3f2a9c1d7b4e",
"essential": true,
"portMappings": [
{ "containerPort": 3000, "protocol": "tcp" }
],
"environment": [
{ "name": "NODE_ENV", "value": "production" },
{ "name": "PORT", "value": "3000" }
],
"secrets": [
{
"name": "DATABASE_URL",
"valueFrom": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/database-url-AbCdEf"
}
],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/myapp",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "ecs"
}
},
"healthCheck": {
"command": ["CMD-SHELL", "curl -f http://localhost:3000/health || exit 1"],
"interval": 30,
"timeout": 5,
"retries": 3,
"startPeriod": 60
}
}
]
}
cpu: 512 with memory: 1024 is a valid Fargate combination. Secrets are referenced by ARN and injected by ECS at launch through the task execution role, which therefore needs secretsmanager:GetSecretValue for that secret. The container health check runs inside the container, so the image must include curl (or use a different command). The runtimePlatform block selects the CPU architecture; ARM64 runs on Graviton, can be priced differently, and needs an Arm image.
The CodePipeline ECS deploy action registers its own revision of the task definition based on the revision the service currently runs, replacing the container image with the one from imagedefinitions.json. Revisions registered elsewhere are ignored by the action unless the service is updated to use them.
## The ECS service in CloudFormation
service.yml:
AWSTemplateFormatVersion: '2010-09-09'
Description: ECS Fargate service behind an existing Application Load Balancer target group
Parameters:
VpcId:
Type: AWS::EC2::VPC::Id
PrivateSubnetIds:
Type: List<AWS::EC2::Subnet::Id>
LoadBalancerSecurityGroupId:
Type: AWS::EC2::SecurityGroup::Id
TargetGroupArn:
Type: String
InitialImage:
Type: String
Description: Image to start with; the pipeline replaces it on the first deployment
DatabaseUrlSecretArn:
Type: String
Description: Secrets Manager secret holding the database URL
Resources:
Cluster:
Type: AWS::ECS::Cluster
Properties:
ClusterName: !Sub '${AWS::StackName}-cluster'
ClusterSettings:
- Name: containerInsights
Value: enhanced
CapacityProviders:
- FARGATE
- FARGATE_SPOT
LogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: /ecs/myapp
RetentionInDays: 30
ExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: ecs-tasks.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
Policies:
- PolicyName: ReadSecrets
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: secretsmanager:GetSecretValue
Resource: !Ref DatabaseUrlSecretArn
TaskRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: ecs-tasks.amazonaws.com
Action: sts:AssumeRole
TaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: myapp-task
NetworkMode: awsvpc
RequiresCompatibilities:
- FARGATE
Cpu: '512'
Memory: '1024'
ExecutionRoleArn: !GetAtt ExecutionRole.Arn
TaskRoleArn: !GetAtt TaskRole.Arn
RuntimePlatform:
OperatingSystemFamily: LINUX
CpuArchitecture: X86_64
ContainerDefinitions:
- Name: myapp
Image: !Ref InitialImage
Essential: true
PortMappings:
- ContainerPort: 3000
Protocol: tcp
Environment:
- Name: NODE_ENV
Value: production
- Name: PORT
Value: '3000'
Secrets:
- Name: DATABASE_URL
ValueFrom: !Ref DatabaseUrlSecretArn
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-group: !Ref LogGroup
awslogs-region: !Ref AWS::Region
awslogs-stream-prefix: ecs
HealthCheck:
Command:
- CMD-SHELL
- curl -f http://localhost:3000/health || exit 1
Interval: 30
Timeout: 5
Retries: 3
StartPeriod: 60
ServiceSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Allow the load balancer to reach the tasks
VpcId: !Ref VpcId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 3000
ToPort: 3000
SourceSecurityGroupId: !Ref LoadBalancerSecurityGroupId
Service:
Type: AWS::ECS::Service
Properties:
ServiceName: !Sub '${AWS::StackName}-service'
Cluster: !Ref Cluster
TaskDefinition: !Ref TaskDefinition
DesiredCount: 3
# A capacity provider strategy replaces LaunchType: two tasks always run
# on regular Fargate and the remainder prefer Fargate Spot.
CapacityProviderStrategy:
- CapacityProvider: FARGATE
Base: 2
Weight: 1
- CapacityProvider: FARGATE_SPOT
Weight: 3
NetworkConfiguration:
AwsvpcConfiguration:
AssignPublicIp: DISABLED
SecurityGroups:
- !Ref ServiceSecurityGroup
Subnets: !Ref PrivateSubnetIds
LoadBalancers:
- ContainerName: myapp
ContainerPort: 3000
TargetGroupArn: !Ref TargetGroupArn
HealthCheckGracePeriodSeconds: 60
DeploymentConfiguration:
MaximumPercent: 200
MinimumHealthyPercent: 100
DeploymentCircuitBreaker:
Enable: true
Rollback: true
ScalableTarget:
Type: AWS::ApplicationAutoScaling::ScalableTarget
Properties:
MinCapacity: 2
MaxCapacity: 10
ResourceId: !Sub 'service/${Cluster}/${Service.Name}'
ScalableDimension: ecs:service:DesiredCount
ServiceNamespace: ecs
ScalingPolicy:
Type: AWS::ApplicationAutoScaling::ScalingPolicy
Properties:
PolicyName: !Sub '${AWS::StackName}-cpu-target-tracking'
PolicyType: TargetTrackingScaling
ScalingTargetId: !Ref ScalableTarget
TargetTrackingScalingPolicyConfiguration:
PredefinedMetricSpecification:
PredefinedMetricType: ECSServiceAverageCPUUtilization
TargetValue: 70.0
ScaleInCooldown: 300
ScaleOutCooldown: 60
Notes on this template:
- →Capacity providers instead of
LaunchType. A service that setsLaunchType: FARGATEignores the cluster's default capacity provider strategy, so the earlier template never used Fargate Spot. SettingCapacityProviderStrategyon the service is explicit: two tasks always run on regular Fargate and the rest prefer Spot, which AWS can interrupt with a two-minute warning. Avoid Spot for the baseline of a production service. - →Container Insights. The cluster setting
enhancedenables Container Insights with enhanced observability, which AWS recommends over the standardenabledmode for ECS on EC2 and Fargate. - →Private networking. Tasks with
AssignPublicIp: DISABLEDstill need a route to Amazon ECR, CloudWatch Logs, and Secrets Manager: a NAT gateway or VPC interface endpoints, plus an S3 gateway endpoint for image layers. - →Deployment safety. The deployment circuit breaker fails a rolling deployment whose tasks cannot start and rolls back to the last completed deployment.
- →Auto scaling. The scalable target omits
RoleARN, so Application Auto Scaling uses its service-linked role.
## Deployment strategies
The default is the rolling update (ECS deployment controller). ECS now also supports blue/green, linear, and canary strategies natively, with bake time and Lambda or pause lifecycle hooks; they need a load balancer, Service Connect, or VPC Lattice to shift traffic, and during the shift they run both service revisions, which can double resource use. CodePipeline's separate ECS-to-CodeDeploy blue/green action remains available for existing setups.
# The same pipeline in Terraform
The Terraform below defines the ECR repository, connection, CodeBuild project, pipeline, and ECS service. It omits the IAM roles, artifact bucket, load balancer, and network, which follow the same patterns as the templates above and the VPC code in AWS Cloud Fundamentals for DevOps Engineers.
pipeline.tf:
variable "app_name" {
type = string
default = "myapp"
}
variable "github_repository" {
description = "GitHub repository in owner/name form"
type = string
}
variable "github_branch" {
type = string
default = "main"
}
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
locals {
registry = "${data.aws_caller_identity.current.account_id}.dkr.ecr.${data.aws_region.current.region}.amazonaws.com"
}
resource "aws_ecr_repository" "app" {
name = var.app_name
image_tag_mutability = "IMMUTABLE"
image_scanning_configuration {
scan_on_push = true
}
encryption_configuration {
encryption_type = "AES256"
}
}
# Authorize this connection once in the Developer Tools console after the first apply
resource "aws_codeconnections_connection" "github" {
name = "${var.app_name}-github"
provider_type = "GitHub"
}
resource "aws_codebuild_project" "app" {
name = "${var.app_name}-build"
service_role = aws_iam_role.codebuild.arn
build_timeout = 30
artifacts {
type = "CODEPIPELINE"
}
environment {
compute_type = "BUILD_GENERAL1_MEDIUM"
image = "aws/codebuild/amazonlinux-x86_64-standard:6.0"
type = "LINUX_CONTAINER"
privileged_mode = true # required to run docker build
image_pull_credentials_type = "CODEBUILD"
environment_variable {
name = "REGISTRY"
value = local.registry
}
environment_variable {
name = "IMAGE_REPO_NAME"
value = aws_ecr_repository.app.name
}
environment_variable {
name = "CONTAINER_NAME"
value = var.app_name
}
}
source {
type = "CODEPIPELINE"
buildspec = "buildspec.yml"
}
cache {
type = "S3"
location = "${aws_s3_bucket.artifacts.bucket}/build-cache"
}
logs_config {
cloudwatch_logs {
group_name = "/aws/codebuild/${var.app_name}"
}
}
}
resource "aws_codepipeline" "app" {
name = "${var.app_name}-pipeline"
role_arn = aws_iam_role.codepipeline.arn
pipeline_type = "V2"
artifact_store {
location = aws_s3_bucket.artifacts.bucket
type = "S3"
}
stage {
name = "Source"
action {
name = "Source"
category = "Source"
owner = "AWS"
provider = "CodeStarSourceConnection"
version = "1"
output_artifacts = ["source_output"]
configuration = {
ConnectionArn = aws_codeconnections_connection.github.arn
FullRepositoryId = var.github_repository
BranchName = var.github_branch
}
}
}
stage {
name = "Build"
action {
name = "Build"
category = "Build"
owner = "AWS"
provider = "CodeBuild"
version = "1"
input_artifacts = ["source_output"]
output_artifacts = ["build_output"]
configuration = {
ProjectName = aws_codebuild_project.app.name
}
}
}
stage {
name = "Deploy"
action {
name = "Deploy"
category = "Deploy"
owner = "AWS"
provider = "ECS"
version = "1"
input_artifacts = ["build_output"]
configuration = {
ClusterName = aws_ecs_cluster.main.name
ServiceName = aws_ecs_service.app.name
FileName = "imagedefinitions.json"
}
}
}
}
ecs.tf (the service; the cluster and task definition follow the CloudFormation versions above):
resource "aws_ecs_service" "app" {
name = "${var.app_name}-service"
cluster = aws_ecs_cluster.main.id
task_definition = aws_ecs_task_definition.app.arn
desired_count = 3
capacity_provider_strategy {
capacity_provider = "FARGATE"
base = 2
weight = 1
}
capacity_provider_strategy {
capacity_provider = "FARGATE_SPOT"
weight = 3
}
network_configuration {
security_groups = [aws_security_group.ecs_tasks.id]
subnets = aws_subnet.private[*].id
assign_public_ip = false
}
load_balancer {
target_group_arn = aws_lb_target_group.app.arn
container_name = var.app_name
container_port = 3000
}
health_check_grace_period_seconds = 60
deployment_maximum_percent = 200
deployment_minimum_healthy_percent = 100
deployment_circuit_breaker {
enable = true
rollback = true
}
# The pipeline registers new task definition revisions; do not fight it
lifecycle {
ignore_changes = [task_definition]
}
depends_on = [aws_lb_listener.app]
}
Two details differ from many older examples. First, aws_ecs_service takes deployment_maximum_percent, deployment_minimum_healthy_percent, and a top-level deployment_circuit_breaker block; the deployment_configuration block that older snippets used for those settings now holds only the newer strategy settings (strategy, bake_time_in_minutes, and blue/green, linear, or canary options), so the old form fails validation. Second, ignore_changes = [task_definition] stops Terraform from reverting the revisions the pipeline registers; manage the image tag in the pipeline and everything else in Terraform. For the workflow around this code, see Terraform Infrastructure as Code: Complete Guide.
# Operating the pipeline
A migration from a self-managed CI server to this setup is mostly a sequence of small, measurable steps. Record your own baseline (deployment duration, failure rate, time to restore) before you start, because published improvement figures depend on the starting point.
- •Foundation. Create the network, an ECS cluster, a load balancer, and the service with a placeholder image, so the first pipeline run has something to update.
- •Pipeline. Connect the source repository, build and test in CodeBuild, push to ECR, and deploy with the ECS action. Add a manual approval action before production in a V2 or V1 pipeline.
- •Security. Keep secrets in Secrets Manager, give each role only the actions it needs, scan images on push, and use VPC endpoints for private traffic.
- •Observability. Enable Container Insights, alarm on service and pipeline failures, and keep build logs with a retention period.
- •Cost. Use Fargate Spot for fault-tolerant capacity, add lifecycle rules to expire old images, and right-size task CPU and memory.
If you already run Jenkins, Jenkins CI/CD Mastery covers the self-managed alternative, and Docker Fundamentals covers the image build that this pipeline automates.
# Best practices
- →Pipeline design: use separate pipelines or stages per environment with an approval before production, set
PipelineTypeexplicitly, and keep pipeline, build, and service definitions in version control. - →Security: use a connection for GitHub, scope every IAM role to specific actions and resources, read secrets through Secrets Manager or Parameter Store mappings, scan images on push, and keep image tags immutable.
- →Performance: cache dependencies, match the CodeBuild compute type to the workload, keep images small, and run independent actions in parallel within a stage.
- →Monitoring: enable Container Insights with enhanced observability, alarm on service health and pipeline failures, and propagate trace IDs through the load balancer and service logs.
- →Cost: combine regular Fargate with Fargate Spot, add ECR lifecycle policies, and review task sizes against observed CPU and memory use.
# Key takeaways
- →Use a CodeConnections GitHub App connection with the
CodeStarSourceConnectionprovider; the OAuth-token GitHub version 1 action is no longer recommended. - →Set
PipelineTypeexplicitly, since V1 and V2 differ in features and price and V2-only settings make a pipeline V2. - →Run tests and the image push in the CodeBuild
buildphase withon-failure: ABORT, tag images with the commit, and keep ECR tags immutable. - →Use current CodeBuild images (
amazonlinux-x86_64-standard:6.0orstandard:8.0) and name a runtime version in the buildspec. - →Prefer a capacity provider strategy over
LaunchTypeif you want Fargate Spot, and keep a regular Fargate base for production. - →In Terraform,
aws_ecs_serviceusesdeployment_maximum_percent,deployment_minimum_healthy_percent, anddeployment_circuit_breaker; the olderdeployment_configurationsnippet no longer validates. - →ECS has native blue/green, linear, and canary deployments in addition to rolling updates and the CodeDeploy integration.
# Further reading
Test yourself: AWS DevOps Tools assessment