Lesson 03 — CI/CD Pipeline Security
Learning Path
☁️ Phase 02 – AWS Cloud Security
📘 Module 11 – DevSecOps & Infrastructure as Code (IaC) Security
🎯 Lesson Objective
Section titled “🎯 Lesson Objective”By the end of this lesson, you will be able to:
- Explain Continuous Integration and Continuous Delivery.
- Identify threats affecting CI/CD pipelines.
- Design a secure enterprise CI/CD architecture.
- Apply least-privilege permissions to pipeline services.
- Secure source code, build environments and deployment artefacts.
- Configure security gates and manual approvals.
- Protect production environments from unauthorised deployments.
- Monitor pipeline activity using AWS logging and security services.
- Respond to pipeline failures and suspected compromise.
📚 Lesson Information
Estimated Time: 4–5 Hours
Difficulty: Advanced
Prerequisites: Lesson 02 – Secure Infrastructure as Code (IaC)
Hands-on Labs: Yes
💼 Business Scenario
Section titled “💼 Business Scenario”CloudNova Technologies releases application updates several times each day.
Its development environment includes:
- Hundreds of Git repositories
- GitHub-based source control
- AWS CodeBuild projects
- AWS CodePipeline pipelines
- Terraform and CloudFormation templates
- Amazon ECR container repositories
- Development, testing, staging and production AWS accounts
- Multiple application teams
A recent internal assessment identifies serious weaknesses:
- Developers can deploy directly to production.
- Build roles have excessive IAM permissions.
- Long-term AWS access keys are stored in repository secrets.
- Pipeline artefacts are not encrypted with customer-managed keys.
- Security testing can be skipped.
- Production deployment does not require approval.
- Build logs contain sensitive information.
- Third-party pipeline actions are not reviewed.
- Old credentials remain active.
- Pipeline failures are not centrally monitored.
The CTO asks:
“How can we protect our software supply chain without slowing down application delivery?”
As the Cloud Security Engineer, you must redesign CloudNova’s CI/CD environment so that every code change is authenticated, reviewed, tested, approved, traceable and securely deployed.
What Is a CI/CD Pipeline?
Section titled “What Is a CI/CD Pipeline?”A CI/CD pipeline automates the process of converting source code into a tested and deployable application.
CI/CD commonly includes:
- Source control
- Code review
- Build automation
- Automated testing
- Security scanning
- Artefact creation
- Deployment approval
- Application deployment
- Operational monitoring
Developer
↓
Source Repository
↓
Continuous Integration
↓
Security Validation
↓
Artefact Repository
↓
Continuous Delivery
↓
Application EnvironmentContinuous Integration
Section titled “Continuous Integration”Continuous Integration, or CI, automatically validates code whenever developers submit changes.
A typical CI process performs:
- Source code checkout
- Dependency installation
- Code compilation
- Unit testing
- Static application security testing
- Secret scanning
- Dependency scanning
- IaC validation
- Container image scanning
- Artefact packaging
Git Commit
↓
Pull Request
↓
Automated Build
↓
Automated Tests
↓
Security Scans
↓
Build ResultThe goal is to provide developers with fast feedback before insecure or defective code is merged.
Continuous Delivery and Continuous Deployment
Section titled “Continuous Delivery and Continuous Deployment”These terms are related but have an important difference.
| Practice | Meaning |
|---|---|
| Continuous Delivery | Code remains ready for release, but production deployment may require approval |
| Continuous Deployment | Every validated change is automatically deployed to production |
For sensitive enterprise workloads, CloudNova uses Continuous Delivery with controlled production approvals.
Why Pipeline Security Matters
Section titled “Why Pipeline Security Matters”A CI/CD pipeline often has permission to:
- Access source code
- Retrieve application secrets
- Create cloud infrastructure
- Build container images
- Push artefacts
- Assume deployment roles
- Modify production systems
A compromised pipeline can become a direct path into production.
Compromised Developer Account
↓
Malicious Code Commit
↓
Pipeline Execution
↓
Privileged Build Role
↓
Production CompromiseCI/CD security is therefore a critical part of software supply chain security.
CI/CD Attack Surface
Section titled “CI/CD Attack Surface”An enterprise pipeline includes multiple attack surfaces.
| Pipeline Component | Example Risk |
|---|---|
| Developer Workstation | Credential theft |
| Source Repository | Malicious code or unauthorised changes |
| Pull Request | Approval bypass |
| Build Environment | Command injection |
| Dependencies | Compromised package |
| Pipeline Configuration | Security stages removed |
| IAM Role | Excessive permissions |
| Artefact Store | Artefact replacement |
| Deployment Stage | Unauthorised production release |
| Logs | Secret exposure |
| Third-Party Action | Supply chain compromise |
Every component requires security controls.
Enterprise CI/CD Security Principles
Section titled “Enterprise CI/CD Security Principles”CloudNova adopts the following principles:
- Verify every identity.
- Review every change.
- Use temporary credentials.
- Apply least privilege.
- Protect branches.
- Scan every build.
- Encrypt every artefact.
- Separate environments.
- Require production approval.
- Log every pipeline action.
- Fail securely.
- Never allow security checks to be silently bypassed.
Secure CI/CD Architecture
Section titled “Secure CI/CD Architecture” Developer │ Feature Branch │ Pull Request │ ┌──────────────────┴──────────────────┐ │ │ Peer Review Automated Checks │ ┌────────────┼────────────┐ │ │ │ Secret Scan SAST Scan IaC Scan │ │ │ └────────────┼────────────┘ │ Protected Merge │ AWS CodePipeline │ AWS CodeBuild │ Unit and Integration Tests │ Container/Dependency Scan │ Signed Build Artefact │ Encrypted S3 or Amazon ECR │ Staging Deployment │ Manual Approval Gate │ Production Deployment │ CloudTrail • CloudWatch • Security HubPipeline Security Layers
Section titled “Pipeline Security Layers”A secure pipeline uses multiple defensive layers.
Identity Security
↓
Repository Security
↓
Build Security
↓
Artefact Security
↓
Deployment Security
↓
Monitoring and ResponseNo single security control is sufficient.
Source Repository Security
Section titled “Source Repository Security”The source repository is the starting point of the pipeline.
CloudNova protects repositories using:
- Multi-factor authentication
- Single sign-on
- Protected branches
- Required Pull Requests
- Required code-owner reviews
- Required status checks
- Commit history
- Secret scanning
- Signed commits where appropriate
- Restrictions on force pushes
- Restrictions on branch deletion
Branch Protection
Section titled “Branch Protection”Branch protection prevents developers from directly changing critical branches.
Recommended production branch controls:
- Block direct commits.
- Require Pull Requests.
- Require at least two reviewers for critical repositories.
- Require successful CI checks.
- Require security scan completion.
- Require code-owner approval.
- Prevent approval by the author.
- Dismiss approvals when new changes are added.
- Block force pushes.
- Restrict branch deletion.
Feature Branch
↓
Pull Request
↓
Peer Review
↓
Security Checks
↓
Protected Main BranchCode Review Security
Section titled “Code Review Security”Code review helps detect:
- Insecure functions
- Hardcoded credentials
- Unnecessary permissions
- Unsafe network exposure
- Missing encryption
- Unapproved dependencies
- Changes to security controls
- Malicious or unexpected logic
High-risk changes should receive specialist review.
Examples include:
- IAM policies
- Network rules
- Authentication logic
- Cryptographic configuration
- Pipeline definitions
- Terraform modules
- CloudFormation templates
Pipeline as Code
Section titled “Pipeline as Code”Pipeline configurations should also be treated as code.
Examples include:
buildspec.yml- GitHub Actions workflow files
- AWS CodePipeline definitions
- Terraform pipeline modules
- CloudFormation pipeline templates
Pipeline configuration files must receive the same protection as application code.
Pipeline Definition
↓
Version Control
↓
Pull Request
↓
Security Review
↓
Controlled DeploymentAWS CodePipeline
Section titled “AWS CodePipeline”AWS CodePipeline orchestrates the software delivery process.
A pipeline can contain stages such as:
Source
↓
Build
↓
Test
↓
Security Scan
↓
Approval
↓
DeployEach stage should use a dedicated IAM role or controlled service role.
AWS CodeBuild
Section titled “AWS CodeBuild”AWS CodeBuild provides managed build environments.
A CodeBuild project can:
- Download source code
- Install dependencies
- Run tests
- Scan code
- Build containers
- Package applications
- Upload artefacts
Because CodeBuild runs commands from the repository, its IAM role must be tightly restricted.
Buildspec File
Section titled “Buildspec File”AWS CodeBuild commonly uses a buildspec.yml file.
Example:
version: 0.2
phases: install: commands: - echo "Installing dependencies" - npm ci
pre_build: commands: - echo "Running security validation" - npm audit --audit-level=high - terraform fmt -check - terraform validate
build: commands: - echo "Running application tests" - npm test
post_build: commands: - echo "Build completed successfully"
artifacts: files: - "**/*"Security checks should fail the build when unacceptable findings are detected.
Fail Securely
Section titled “Fail Securely”A pipeline must not continue when a required security control fails.
Security Test Passed?
├── Yes → Continue Pipeline│└── No → Stop Build and Notify TeamExamples of conditions that should stop deployment:
- Exposed credentials
- Critical dependency vulnerability
- Failed unit tests
- Publicly exposed infrastructure
- Unencrypted data resource
- Excessive IAM permissions
- Unsigned or untrusted artefact
- Failed approval requirement
Pipeline Identity and Access Management
Section titled “Pipeline Identity and Access Management”Each pipeline component should use a dedicated role.
Example roles:
| Role | Purpose |
|---|---|
| Pipeline Service Role | Coordinates pipeline stages |
| Build Role | Runs build and scan commands |
| Artefact Role | Reads and writes approved artefacts |
| Staging Deployment Role | Deploys to staging |
| Production Deployment Role | Deploys only approved releases |
| Security Scan Role | Reads required resources for validation |
Avoid using one highly privileged role for the entire pipeline.
Least-Privilege Build Role
Section titled “Least-Privilege Build Role”A build role should only receive permissions needed for the current build.
For example, a build that uploads an artefact to one S3 bucket should not receive access to all S3 buckets.
Example restricted policy:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "UploadBuildArtifacts", "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject" ], "Resource": [ "arn:aws:s3:::cloudnova-pipeline-artifacts/*" ] } ]}Temporary Credentials
Section titled “Temporary Credentials”Long-term AWS access keys should not be stored in:
- Git repositories
- Pipeline variables
- Build scripts
- Container images
- Configuration files
AWS services should use IAM roles and temporary credentials.
For external CI/CD platforms such as GitHub Actions, use identity federation where supported rather than static AWS keys.
External CI Platform
↓
Federated Identity
↓
AWS STS
↓
Temporary Credentials
↓
Restricted Deployment RoleSecure GitHub-to-AWS Authentication
Section titled “Secure GitHub-to-AWS Authentication”A secure GitHub Actions integration can use OpenID Connect.
GitHub Actions Workflow
↓
OIDC Identity Token
↓
AWS IAM Identity Provider
↓
AssumeRoleWithWebIdentity
↓
Temporary AWS CredentialsThe role trust policy should restrict:
- GitHub organisation
- Repository
- Branch or environment
- Audience
- Approved workflow conditions
Example trust policy structure:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com" }, "Action": "sts:AssumeRoleWithWebIdentity", "Condition": { "StringEquals": { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" }, "StringLike": { "token.actions.githubusercontent.com:sub": "repo:cloudnova/secure-app:ref:refs/heads/main" } } } ]}Replace the example account, organisation, repository and branch with your authorised values.
Secrets Management
Section titled “Secrets Management”Application and pipeline secrets should be stored in:
- AWS Secrets Manager
- AWS Systems Manager Parameter Store
Examples of secrets include:
- Database passwords
- API credentials
- Signing keys
- Third-party tokens
The pipeline should retrieve secrets only when required.
Build Job
↓
Authorised IAM Role
↓
Secrets Manager
↓
Temporary Secret RetrievalSecrets must never be printed in build logs.
Environment Variables
Section titled “Environment Variables”Environment variables may be used for non-sensitive values such as:
- AWS Region
- Application environment
- Artefact bucket name
- Deployment stage
Sensitive values should reference a secrets service rather than appear as plaintext environment variables.
Build Environment Security
Section titled “Build Environment Security”Secure build environments should:
- Use trusted base images.
- Use current runtime versions.
- Minimise installed tools.
- Run builds in isolated environments.
- Restrict outbound network access where feasible.
- Avoid privileged mode unless required.
- Delete temporary files.
- Avoid reusing compromised build caches.
- Record build logs.
- Patch build images regularly.
Privileged Mode Risk
Section titled “Privileged Mode Risk”CodeBuild privileged mode is often enabled when building Docker images.
Privileged mode provides elevated access inside the build environment and should only be enabled when necessary.
When enabled:
- Restrict the project’s IAM role.
- Use trusted source repositories.
- Scan the resulting image.
- Limit network access.
- Monitor build activity.
- Prevent untrusted Pull Requests from triggering privileged builds.
Dependency Security
Section titled “Dependency Security”Modern applications depend on external packages.
Risks include:
- Vulnerable libraries
- Malicious packages
- Dependency confusion
- Typosquatting
- Unmaintained components
- Compromised registries
Recommended controls:
- Use lock files.
- Pin dependency versions.
- Use approved package registries.
- Scan dependencies.
- Remove unused packages.
- Review critical updates.
- Generate a Software Bill of Materials where required.
Artefact Security
Section titled “Artefact Security”Build artefacts may include:
- Application packages
- Lambda deployment archives
- Container images
- CloudFormation templates
- Terraform plans
- Configuration bundles
Artefacts must be protected against unauthorised modification.
Secure Artefact Storage
Section titled “Secure Artefact Storage”CloudNova stores artefacts using:
- Amazon S3 for application packages
- Amazon ECR for container images
- AWS KMS for encryption
- Versioning for change history
- Restricted bucket and repository policies
- Lifecycle rules for retention
- Access logging and CloudTrail events
CodeBuild
↓
Build Artefact
↓
Integrity Validation
↓
KMS Encryption
↓
Controlled Artefact Repository
↓
Approved DeploymentExample Secure Artefact Bucket Controls
Section titled “Example Secure Artefact Bucket Controls”The artefact bucket should:
- Block all public access.
- Require TLS.
- Enable versioning.
- Encrypt objects.
- Restrict access to approved pipeline roles.
- Deny unencrypted uploads where required.
- Record access activity.
- Apply retention and lifecycle policies.
Artefact Integrity
Section titled “Artefact Integrity”A secure deployment should use the exact artefact created and tested by the pipeline.
Do not rebuild the application separately for production after staging tests.
Build Once
↓
Test Same Artefact
↓
Approve Same Artefact
↓
Deploy Same ArtefactThis reduces the chance of differences between tested and deployed code.
Container Pipeline Security
Section titled “Container Pipeline Security”A container pipeline commonly follows this workflow:
Source Code
↓
Docker Build
↓
Image Scan
↓
Approved Image
↓
Amazon ECR
↓
Deployment to ECS or EKSRecommended controls include:
- Use minimal trusted base images.
- Pin image versions or digests.
- Avoid running as root.
- Remove unnecessary packages.
- Scan images before deployment.
- Encrypt ECR repositories.
- Restrict image push permissions.
- Enable image tag immutability where appropriate.
- Deploy only approved image digests.
Environment Separation
Section titled “Environment Separation”Development, testing, staging and production environments should be separated.
A mature enterprise model uses separate AWS accounts.
Development Account
↓
Testing Account
↓
Staging Account
↓
Production AccountBenefits include:
- Reduced blast radius
- Stronger access control
- Cleaner cost allocation
- Independent security controls
- Safer testing
- Easier audit evidence
Cross-Account Deployment
Section titled “Cross-Account Deployment”CloudNova uses a central pipeline account and dedicated workload accounts.
CI/CD Tooling Account │ ┌──────────────┼──────────────┐ │ │ │ Development Staging Production Account Account Account │ │ │ Dev Deploy Role Stage Deploy Role Prod Deploy RoleThe pipeline assumes a separate deployment role in each target account.
The production role has the strictest controls.
Production Deployment Controls
Section titled “Production Deployment Controls”Production deployment should require:
- Successful automated tests
- Successful security scans
- Approved artefact
- Change record
- Manual approval
- Restricted production role
- Maintenance window where applicable
- Rollback plan
- Deployment monitoring
Manual Approval Gate
Section titled “Manual Approval Gate”AWS CodePipeline supports manual approval actions.
Staging Deployment
↓
Integration Testing
↓
Security Validation
↓
Manual Approval
↓
Production DeploymentApproval requests may include:
- Release number
- Change summary
- Test results
- Security findings
- Rollback procedure
- Approval deadline
Separation of Duties
Section titled “Separation of Duties”The person who writes code should not have unrestricted authority to approve and deploy the same change to production.
Example:
| Activity | Role |
|---|---|
| Write Code | Developer |
| Review Code | Peer Developer |
| Validate Security | Security Automation |
| Approve Release | Application Owner or Change Manager |
| Deploy | Pipeline Service Role |
| Monitor | Operations and Security Teams |
This reduces fraud, mistakes and unauthorised changes.
Deployment Strategies
Section titled “Deployment Strategies”CloudNova selects deployment strategies based on risk.
| Strategy | Description |
|---|---|
| In-Place | Existing application is updated directly |
| Rolling | Instances are updated in controlled batches |
| Blue/Green | New environment is created before traffic is switched |
| Canary | Small percentage of traffic is sent to the new version |
| Immutable | New infrastructure replaces the old environment |
Blue/green and canary deployments support safer validation and rollback.
Rollback Planning
Section titled “Rollback Planning”Every production deployment requires a rollback plan.
The plan should define:
- Rollback trigger
- Responsible owner
- Previous artefact version
- Database compatibility
- Infrastructure rollback method
- Customer communication
- Validation steps
Deployment
↓
Health Check
├── Healthy → Continue│└── Unhealthy → Roll BackPipeline Logging and Monitoring
Section titled “Pipeline Logging and Monitoring”CloudNova monitors pipeline activity using:
- AWS CloudTrail
- Amazon CloudWatch Logs
- Amazon EventBridge
- Amazon SNS
- AWS Config
- AWS Security Hub
- Amazon GuardDuty
Important events include:
- Pipeline configuration changes
- IAM role changes
- Failed builds
- Repeated approval failures
- Unauthorised deployment attempts
- Artefact bucket policy changes
- KMS key policy changes
- Disabled security stages
Pipeline Alerting Architecture
Section titled “Pipeline Alerting Architecture”CodePipeline / CodeBuild Event
↓
Amazon EventBridge
↓
Amazon SNS
↓
DevOps and Security TeamsCritical failures can also be forwarded to incident management systems.
CloudTrail Monitoring
Section titled “CloudTrail Monitoring”CloudTrail helps answer:
- Who changed the pipeline?
- Who started the deployment?
- Which role was assumed?
- Who approved production?
- Who changed the artefact bucket?
- Who modified the build project?
- Which API action failed?
Pipeline and IAM events should be centrally logged in a protected logging account.
Security Metrics
Section titled “Security Metrics”CloudNova tracks the following metrics:
| Metric | Purpose |
|---|---|
| Build Success Rate | Measures pipeline reliability |
| Security Gate Failure Rate | Identifies frequent security issues |
| Mean Time to Remediate | Measures remediation speed |
| Vulnerabilities per Build | Tracks code and dependency risk |
| Unauthorised Deployment Attempts | Detects policy violations |
| Approval Duration | Identifies release bottlenecks |
| Rollback Rate | Measures release quality |
| Secret Detection Events | Measures credential exposure |
Pipeline Incident Response
Section titled “Pipeline Incident Response”A suspected pipeline compromise should be handled as a security incident.
Recommended response workflow:
Suspicious Activity Detected
↓
Stop Pipeline
↓
Disable Compromised Credentials
↓
Restrict Deployment Roles
↓
Preserve Logs and Artefacts
↓
Investigate Source and Build History
↓
Identify Affected Releases
↓
Rollback or Rebuild
↓
Restore Trusted Pipeline
↓
Document Lessons LearnedEnterprise Pipeline Security Checklist
Section titled “Enterprise Pipeline Security Checklist”Before approving a production pipeline, verify:
- Repository MFA is enforced.
- Production branches are protected.
- Pull Requests are required.
- Code-owner reviews are configured.
- Security checks cannot be skipped.
- Build roles follow least privilege.
- Static access keys are not used.
- Secrets are stored in an approved service.
- Artefacts are encrypted.
- Artefact repositories block public access.
- Production requires approval.
- Environments are separated.
- Logs are centrally collected.
- Pipeline failures generate alerts.
- A rollback procedure is documented.
🛠 Lab 01 — Map an Enterprise CI/CD Pipeline
Section titled “🛠 Lab 01 — Map an Enterprise CI/CD Pipeline”Objective
Section titled “Objective”Identify the security controls required throughout a CI/CD pipeline.
Scenario
Section titled “Scenario”CloudNova is deploying a customer portal through GitHub and AWS CodePipeline.
Create a pipeline diagram containing:
- Developer workstation
- GitHub repository
- Pull Request
- Code review
- AWS CodePipeline
- AWS CodeBuild
- Security scanning
- Artefact storage
- Staging deployment
- Manual approval
- Production deployment
- Monitoring
For every stage, document:
- Main risk
- Preventive control
- Detective control
- Responsible team
Deliverable
Section titled “Deliverable”Create a table similar to the following:
| Stage | Risk | Preventive Control | Detective Control | Owner |
|---|---|---|---|---|
| Source Repository | Unauthorised commit | Branch protection | Repository audit logs | Development |
| Build | Malicious command | Restricted build role | CodeBuild logs | DevOps |
| Production | Unapproved release | Manual approval | CloudTrail | Operations |
🛠 Lab 02 — Create a Secure Artefact Bucket
Section titled “🛠 Lab 02 — Create a Secure Artefact Bucket”Objective
Section titled “Objective”Create an encrypted S3 bucket for CI/CD artefacts.
Step 1 — Define Variables
Section titled “Step 1 — Define Variables”Run in PowerShell or Git Bash after configuring the AWS CLI.
AWS_REGION="ap-south-1"ARTIFACT_BUCKET="cloudnova-pipeline-artifacts-REPLACE-WITH-UNIQUE-ID"PowerShell users can use:
$AWS_REGION = "ap-south-1"$ARTIFACT_BUCKET = "cloudnova-pipeline-artifacts-REPLACE-WITH-UNIQUE-ID"Step 2 — Create the Bucket
Section titled “Step 2 — Create the Bucket”For ap-south-1:
aws s3api create-bucket \ --bucket "$ARTIFACT_BUCKET" \ --region "$AWS_REGION" \ --create-bucket-configuration LocationConstraint="$AWS_REGION"PowerShell:
aws s3api create-bucket ` --bucket $ARTIFACT_BUCKET ` --region $AWS_REGION ` --create-bucket-configuration LocationConstraint=$AWS_REGIONStep 3 — Block Public Access
Section titled “Step 3 — Block Public Access”aws s3api put-public-access-block \ --bucket "$ARTIFACT_BUCKET" \ --public-access-block-configuration \BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=trueStep 4 — Enable Versioning
Section titled “Step 4 — Enable Versioning”aws s3api put-bucket-versioning \ --bucket "$ARTIFACT_BUCKET" \ --versioning-configuration Status=EnabledStep 5 — Enable Default Encryption
Section titled “Step 5 — Enable Default Encryption”aws s3api put-bucket-encryption \ --bucket "$ARTIFACT_BUCKET" \ --server-side-encryption-configuration \'{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"},"BucketKeyEnabled":true}]}'Step 6 — Verify Controls
Section titled “Step 6 — Verify Controls”aws s3api get-public-access-block \ --bucket "$ARTIFACT_BUCKET"aws s3api get-bucket-versioning \ --bucket "$ARTIFACT_BUCKET"aws s3api get-bucket-encryption \ --bucket "$ARTIFACT_BUCKET"Expected Result
Section titled “Expected Result”The bucket should:
- Block all public access.
- Have versioning enabled.
- Encrypt new objects automatically.
🛠 Lab 03 — Create a CodeBuild Project
Section titled “🛠 Lab 03 — Create a CodeBuild Project”Objective
Section titled “Objective”Create a basic CodeBuild project with a restricted service role.
Step 1 — Create a Trust Policy
Section titled “Step 1 — Create a Trust Policy”Create a file named codebuild-trust-policy.json.
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "codebuild.amazonaws.com" }, "Action": "sts:AssumeRole" } ]}Step 2 — Create the IAM Role
Section titled “Step 2 — Create the IAM Role”aws iam create-role \ --role-name CloudNovaCodeBuildRole \ --assume-role-policy-document file://codebuild-trust-policy.jsonStep 3 — Create a Restricted Permissions Policy
Section titled “Step 3 — Create a Restricted Permissions Policy”Create codebuild-permissions.json.
Replace the example bucket name.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "ReadWritePipelineArtifacts", "Effect": "Allow", "Action": [ "s3:GetObject", "s3:GetObjectVersion", "s3:PutObject" ], "Resource": "arn:aws:s3:::cloudnova-pipeline-artifacts-REPLACE-WITH-UNIQUE-ID/*" }, { "Sid": "WriteBuildLogs", "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "*" } ]}Step 4 — Attach the Policy
Section titled “Step 4 — Attach the Policy”aws iam put-role-policy \ --role-name CloudNovaCodeBuildRole \ --policy-name CloudNovaCodeBuildPolicy \ --policy-document file://codebuild-permissions.jsonStep 5 — Retrieve the Role ARN
Section titled “Step 5 — Retrieve the Role ARN”aws iam get-role \ --role-name CloudNovaCodeBuildRole \ --query "Role.Arn" \ --output textRecord the ARN for the project configuration.
Security Note
Section titled “Security Note”For a production implementation:
- Restrict CloudWatch Logs resources.
- Use a customer-managed KMS key.
- Restrict the source repository.
- Add only permissions required by the build.
- Use permissions boundaries where appropriate.
🛠 Lab 04 — Build a Security-Gated buildspec.yml
Section titled “🛠 Lab 04 — Build a Security-Gated buildspec.yml”Objective
Section titled “Objective”Create a build specification that stops deployment when tests fail.
Create buildspec.yml.
version: 0.2
phases: install: runtime-versions: nodejs: 20 commands: - echo "Installing dependencies" - npm ci
pre_build: commands: - echo "Checking for vulnerable dependencies" - npm audit --audit-level=high - echo "Validating Terraform formatting" - terraform fmt -check -recursive - echo "Validating Terraform configuration" - terraform init -backend=false - terraform validate
build: commands: - echo "Running unit tests" - npm test
post_build: commands: - echo "All required checks completed"
artifacts: files: - "**/*" discard-paths: noStudent Activity
Section titled “Student Activity”Introduce one controlled failure, such as:
- Invalid Terraform syntax
- A failed unit test
- A vulnerable test dependency
Run the build and confirm that the pipeline stops.
Evidence
Section titled “Evidence”Capture:
- Failed command
- Build status
- Relevant log entry
- Remediation performed
- Successful rerun
🛠 Lab 05 — Design Production Approval Controls
Section titled “🛠 Lab 05 — Design Production Approval Controls”Objective
Section titled “Objective”Design an approval gate between staging and production.
Your approval process must include:
- Application owner approval
- Security scan results
- Change request reference
- Tested artefact version
- Rollback procedure
- Deployment window
- Business impact summary
Approval Record Template
Section titled “Approval Record Template”Application:Release Version:Artefact Identifier:Change Request:Staging Test Result:Security Scan Result:Known Risks:Rollback Version:Rollback Owner:Requested By:Approved By:Approval Time:Deliverable
Section titled “Deliverable”Create a pipeline diagram showing:
Build
↓
Security Validation
↓
Staging
↓
Manual Approval
↓
Production🛠 Lab 06 — Create Pipeline Failure Notifications
Section titled “🛠 Lab 06 — Create Pipeline Failure Notifications”Objective
Section titled “Objective”Use Amazon EventBridge and Amazon SNS to notify the team when a pipeline fails.
Step 1 — Create an SNS Topic
Section titled “Step 1 — Create an SNS Topic”aws sns create-topic \ --name CloudNovaPipelineAlertsRecord the returned topic ARN.
Step 2 — Create an Event Pattern
Section titled “Step 2 — Create an Event Pattern”Create pipeline-failure-event-pattern.json.
{ "source": [ "aws.codepipeline" ], "detail-type": [ "CodePipeline Pipeline Execution State Change" ], "detail": { "state": [ "FAILED" ] }}Step 3 — Create the EventBridge Rule
Section titled “Step 3 — Create the EventBridge Rule”aws events put-rule \ --name CloudNovaPipelineFailureRule \ --event-pattern file://pipeline-failure-event-pattern.json \ --state ENABLEDStep 4 — Add the SNS Target
Section titled “Step 4 — Add the SNS Target”Replace the example SNS topic ARN.
aws events put-targets \ --rule CloudNovaPipelineFailureRule \ --targets \'Id=PipelineFailureSNS,Arn=arn:aws:sns:ap-south-1:123456789012:CloudNovaPipelineAlerts'Step 5 — Allow EventBridge to Publish to SNS
Section titled “Step 5 — Allow EventBridge to Publish to SNS”Create an SNS topic policy allowing the EventBridge rule to publish.
In an enterprise environment, restrict the policy using the rule ARN and aws:SourceArn.
Verification
Section titled “Verification”Run:
aws events describe-rule \ --name CloudNovaPipelineFailureRuleaws events list-targets-by-rule \ --rule CloudNovaPipelineFailureRule💻 AWS CLI Reference
Section titled “💻 AWS CLI Reference”List CodePipeline Pipelines
Section titled “List CodePipeline Pipelines”aws codepipeline list-pipelinesView Pipeline Details
Section titled “View Pipeline Details”aws codepipeline get-pipeline \ --name CloudNovaApplicationPipelineView Pipeline State
Section titled “View Pipeline State”aws codepipeline get-pipeline-state \ --name CloudNovaApplicationPipelineView Pipeline Executions
Section titled “View Pipeline Executions”aws codepipeline list-pipeline-executions \ --pipeline-name CloudNovaApplicationPipelineStart a Pipeline
Section titled “Start a Pipeline”aws codepipeline start-pipeline-execution \ --name CloudNovaApplicationPipelineStop a Pipeline Execution
Section titled “Stop a Pipeline Execution”Replace the execution ID.
aws codepipeline stop-pipeline-execution \ --pipeline-name CloudNovaApplicationPipeline \ --pipeline-execution-id PIPELINE_EXECUTION_ID \ --reason "Security validation failed" \ --abandonList CodeBuild Projects
Section titled “List CodeBuild Projects”aws codebuild list-projectsView a CodeBuild Project
Section titled “View a CodeBuild Project”aws codebuild batch-get-projects \ --names CloudNovaSecureBuildView Recent Builds
Section titled “View Recent Builds”aws codebuild list-builds-for-project \ --project-name CloudNovaSecureBuildView Build Details
Section titled “View Build Details”aws codebuild batch-get-builds \ --ids BUILD_ID✅ Verification Checklist
Section titled “✅ Verification Checklist”Verify that you can:
- Explain CI and CD.
- Identify CI/CD pipeline attack surfaces.
- Apply repository and branch protection controls.
- Explain Pipeline as Code.
- Design least-privilege pipeline roles.
- Replace long-term keys with temporary credentials.
- Protect application secrets.
- Secure build environments.
- Encrypt and control artefacts.
- Separate development and production deployments.
- Configure production approval gates.
- Monitor pipeline events.
- Respond to suspected pipeline compromise.
🔍 Troubleshooting
Section titled “🔍 Troubleshooting”Problem — Pipeline Cannot Access the Artefact Bucket
Section titled “Problem — Pipeline Cannot Access the Artefact Bucket”Verify:
- Pipeline service role permissions
- CodeBuild role permissions
- S3 bucket policy
- KMS key policy
- Correct bucket ARN
- Correct AWS Region
Use:
aws sts get-caller-identityaws s3api head-bucket \ --bucket YOUR_ARTIFACT_BUCKETProblem — CodeBuild Cannot Write Logs
Section titled “Problem — CodeBuild Cannot Write Logs”Verify that the build role permits:
logs:CreateLogGrouplogs:CreateLogStreamlogs:PutLogEventsAlso verify:
- CloudWatch Logs Region
- Log group resource ARN
- Permissions boundary
- Service Control Policies
Problem — Production Deployment Role Cannot Be Assumed
Section titled “Problem — Production Deployment Role Cannot Be Assumed”Review:
- Role trust policy
- Pipeline role permissions
- External ID or OIDC conditions
- Target account ID
- Branch or repository condition
- Service Control Policies
- AWS Organizations restrictions
Problem — Security Test Fails Unexpectedly
Section titled “Problem — Security Test Fails Unexpectedly”Review:
- Scanner configuration
- Severity threshold
- Suppression rules
- Dependency lock file
- False-positive process
- Tool version
- Network access to required package registries
Do not bypass the check without documented risk acceptance.
Problem — Pipeline Works in Development but Fails in Production
Section titled “Problem — Pipeline Works in Development but Fails in Production”Compare:
- IAM role permissions
- Environment variables
- KMS key policies
- Network controls
- Service quotas
- Resource names
- Account-level policies
- Production approval conditions
🏢 Enterprise Best Practices
Section titled “🏢 Enterprise Best Practices”CloudNova standards include:
- Use protected branches for every production repository.
- Require Pull Requests and independent approvals.
- Use dedicated IAM roles for each pipeline function.
- Use temporary credentials instead of long-term access keys.
- Store secrets in approved secrets-management services.
- Scan code, dependencies, IaC and container images.
- Stop pipelines when mandatory security controls fail.
- Encrypt artefacts at rest and in transit.
- Build once and deploy the same approved artefact.
- Separate development, staging and production accounts.
- Require approval before production deployment.
- Protect and review pipeline configuration files.
- Log all pipeline and deployment activity.
- Alert security teams about critical failures.
- Test rollback procedures before production releases.
- Review third-party pipeline actions and dependencies.
🚫 Common Mistakes
Section titled “🚫 Common Mistakes”❌ Giving the build role AdministratorAccess.
❌ Storing AWS access keys in repository secrets when federation is available.
❌ Allowing direct commits to the production branch.
❌ Running untrusted code in a privileged build environment.
❌ Printing passwords or tokens in build logs.
❌ Rebuilding a different artefact for production.
❌ Allowing security scans to be skipped.
❌ Using the same deployment role across every environment.
❌ Keeping pipeline artefacts in a public or unencrypted bucket.
❌ Deploying automatically to production without appropriate approval.
❌ Ignoring dependency and third-party action risks.
❌ Failing to monitor changes to pipeline definitions.
🧪 DIY Enterprise Challenge
Section titled “🧪 DIY Enterprise Challenge”CloudNova is building a new financial services platform.
Design a secure CI/CD pipeline that supports:
- GitHub source control.
- Protected production branches.
- Pull Request reviews.
- GitHub OIDC authentication to AWS.
- AWS CodeBuild.
- Static code analysis.
- Secret scanning.
- Dependency scanning.
- Terraform security validation.
- Container image scanning.
- Encrypted artefact storage.
- Staging deployment.
- Manual production approval.
- Cross-account production deployment.
- CloudTrail and CloudWatch monitoring.
- Pipeline failure notifications.
- Rollback procedures.
Prepare the following deliverables:
- CI/CD Architecture Diagram
- Pipeline Stage Matrix
- IAM Role Design
- GitHub OIDC Trust Policy
- Secure
buildspec.yml - Artefact Protection Standard
- Production Approval Procedure
- Monitoring and Alerting Design
- Pipeline Incident Response Runbook
- Executive Security Summary
📊 Knowledge Check
Section titled “📊 Knowledge Check”- What is the difference between Continuous Delivery and Continuous Deployment?
- Why is a CI/CD pipeline a high-value target?
- What security controls should protect production branches?
- Why should pipeline definitions be stored in version control?
- Why should build roles follow least privilege?
- Why are temporary credentials safer than static access keys?
- How does GitHub OIDC authenticate to AWS?
- Why should builds fail when mandatory security scans fail?
- How should application secrets be provided to a build?
- Why should pipeline artefacts be encrypted and versioned?
- What does “build once, deploy the same artefact” mean?
- Why should production use a separate deployment role?
- What is the purpose of a manual approval gate?
- Which AWS services can monitor pipeline activity?
- What should happen when a pipeline compromise is suspected?
💡 Key Takeaways
Section titled “💡 Key Takeaways”After completing this lesson, you should understand:
- A CI/CD pipeline is part of the organisation’s software supply chain and must be treated as critical production infrastructure.
- Secure repositories, protected branches and independent code reviews prevent unauthorised changes from entering the delivery process.
- Pipeline services should use dedicated least-privilege IAM roles and temporary credentials rather than shared identities or static access keys.
- Security gates should automatically scan source code, dependencies, infrastructure templates, secrets and container images.
- Build artefacts must be encrypted, access-controlled and protected from modification.
- Environment and account separation reduces the blast radius of pipeline compromise.
- Production releases should use approved artefacts, controlled deployment roles and clearly documented rollback procedures.
- CloudTrail, CloudWatch, EventBridge and security services provide the visibility needed to detect and investigate pipeline activity.
- When a required security control fails, the secure response is to stop the pipeline, investigate the cause and remediate the issue.
🚀 Next Lesson
Section titled “🚀 Next Lesson”➡️ Lesson 04 — Security Testing & Secret Management