Lessons in this course (9)

8. Infrastructure as code and CI/CD — CloudFormation, CDK, CodePipeline, GitHub Actions

Intermediate★ Must knowLesson 8 of 9
csharp
// AWS CDK in C# — a Fargate service behind a load balancer in ~10 lines
public class ShopStack : Stack
{
    public ShopStack(Construct scope, string id) : base(scope, id)
    {
        var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 2 });
        var cluster = new Cluster(this, "Cluster", new ClusterProps { Vpc = vpc });
        new ApplicationLoadBalancedFargateService(this, "Api", new ApplicationLoadBalancedFargateServiceProps
        {
            Cluster = cluster, DesiredCount = 2, Cpu = 512, MemoryLimitMiB = 1024,
            TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions { Image = ContainerImage.FromAsset("../src/Shop.Api"), ContainerPort = 8080 }
        });
    }
}
// cdk deploy
yaml
# GitHub Actions — build and deploy to ECS using OIDC (no stored AWS keys)
permissions: { id-token: write, contents: read }
steps:
  - uses: actions/checkout@v4
  - uses: aws-actions/configure-aws-credentials@v4
    with: { role-to-assume: arn:aws:iam::123456789012:role/github-deploy, aws-region: ap-south-1 }
  - uses: aws-actions/amazon-ecr-login@v2
  - run: docker build -t $ECR_REPO:${{ github.sha }} . && docker push $ECR_REPO:${{ github.sha }}
  - uses: aws-actions/amazon-ecs-deploy-task-definition@v2
    with: { task-definition: taskdef.json, service: shop-api, cluster: shop, wait-for-service-stability: true }

AWS-native alternative: CodePipeline (orchestration) + CodeBuild (build/test) + CodeDeploy (blue/green for EC2/ECS/Lambda).