Skip to main content

CodeDeploy Auto Deploy And Monitoring Should Be Enabled

More Info:

Ensure Code build code deploy has auto rollback and monitoring enabled

Risk Level

Medium

Address

Operational Excellence, Performance Efficiency, Reliability, Security

Compliance Standards

  • APRA CPS 234 (Australia)
  • BSI C5 (Germany)
  • Brazil LGPD
  • CCPA / CPRA (California)
  • CIS Critical Security Controls v8
  • CMMC 2.0
  • CSA Cloud Controls Matrix v4
  • DPDPA
  • Digital Operational Resilience Act (EU)
  • Essential 8
  • HITRUST CSF
  • ISO/IEC 27017
  • ISO/IEC 27018
  • ISO/IEC 27701
  • KSA PDPL
  • MAS Technology Risk Management (Singapore)
  • MITRE ATT&CK (Cloud)
  • NIS2 Directive
  • NIST SP 800-171
  • NYDFS 23 NYCRR 500
  • SOC2
  • SWIFT Customer Security Controls Framework
  • Sarbanes-Oxley IT General Controls
  • UK NCSC Cyber Assessment Framework

Triage and Remediation

Remediation

Using Console

Below are the console steps to enable Auto Deploy and Monitoring for an existing AWS CodeDeploy deployment group (which your CodeBuild pipeline likely deploys to).


1. Enable Auto Deploy (Automatically deploy new revisions)

  1. Sign in to the AWS Management Console.

  2. In the top bar, choose the correct Region where your CodeDeploy resources exist.

  3. Open CodeDeploy:

    • Services → search for CodeDeploy → select it.
  4. In the left pane, choose Applications.

  5. Click the CodeDeploy application that your CodeBuild project/pipeline uses.

  6. Go to the Deployment groups tab.

  7. Click the Deployment group you want to fix.

  8. In the top-right, choose Edit.

  9. Scroll to the Deployment settings / Triggers / Auto deploy section:

    • Locate Auto deploy or Trigger deployments on new application revisions.
    • Check/enable:
      • Automatically deploy new revisions (or similar wording like “Trigger deployments when a new revision is pushed to the deployment group’s target repository/bucket”).
    • If using:
      • S3: select the bucket and prefix that contains your AppSpec and bundle.
      • GitHub/CodeCommit: ensure the “Revision change” trigger is tied to the correct repository/branch.
  10. (Recommended) In the same edit screen, enable Automatic rollback:

    • Find Automatic rollback.
    • Select:
      • Rollback when a deployment fails.
      • Optionally Rollback when alarm thresholds are met (we’ll set alarms next).
  11. At the bottom of the page, click Save changes.


2. Enable Monitoring with CloudWatch Alarms

You generally do this per deployment group by associating CloudWatch alarms that track instance/application health.

2.1 Create or verify CloudWatch alarms

If you already have alarms that detect unhealthy deployments/instances, skip to 2.2.

  1. Open CloudWatch:
    • Services → CloudWatch.
  2. In the left pane, choose AlarmsAll alarmsCreate alarm.
  3. Click Select metric and choose a metric that reflects deployment health. Common patterns:
    • EC2 / Application metrics like:
      • CPU%, memory, or custom app health metric exposed to CloudWatch.
    • Or a CodeDeploy metric (if using CodeDeploy metrics via CloudWatch):
      • Example namespace: AWS/CodeDeploy (depending on what you’ve configured) and metric for failed instances/deployments.
  4. Configure the alarm:
    • Set the threshold so it goes to ALARM when your deployment is unhealthy (e.g., error count > 0, failed instances > 0).
  5. Configure actions (SNS topic, email, etc.) if desired.
  6. Click Next, give the alarm a Name and Description, and then click Create alarm.

Repeat as needed for all metrics you want to watch.


2.2 Attach alarms and monitoring to the deployment group

  1. Go back to CodeDeploy → your ApplicationDeployment group (as in section 1).
  2. Click the Deployment group name, then choose Edit.
  3. Scroll to the Alarms / Monitoring / Deployment settings section:
    • Find Alarms (or “Monitor deployments with CloudWatch alarms”).
    • Check/enable Use CloudWatch alarms or similar.
    • Click Add alarm and select the alarms you created in CloudWatch.
  4. Ensure Automatic rollback is set to:
    • Rollback when alarm thresholds are met (in addition to “Rollback when deployment fails”, if desired).
  5. (Optional) In the same edit screen, ensure Log monitoring is enabled:
    • If available, verify:
      • The deployment group or underlying Auto Scaling group / instances use an IAM role that lets the CloudWatch Agent or CloudWatch Logs agent push logs.
      • The logs are being sent to CloudWatch Logs (configured on the instances, not directly in CodeDeploy UI).
  6. At the bottom, click Save changes.

3. (If using CodeBuild/CodePipeline) Verify the integration

If CodeBuild is part of a pipeline that triggers CodeDeploy:

  1. Open CodePipeline:
    • Services → CodePipeline.
  2. Choose your pipeline and click Edit.
  3. Confirm:
    • The Source stage outputs the artifact that CodeDeploy uses (e.g., AppSpec + bundle).
    • The Deploy stage is a CodeDeploy action pointing to:
      • The same Application name.
      • The same Deployment group you just edited.
  4. Save the pipeline if any changes were made.

4. Validate

  1. Trigger a new build in CodeBuild or a new execution in CodePipeline.
  2. In CodeDeploy → Deployments, confirm:
    • New deployments are automatically created when a new revision is produced.
    • If you deliberately break a deployment (for testing), CloudWatch alarms move to ALARM, and CodeDeploy:
      • Marks deployment as Failed.
      • Performs Automatic rollback using the alarms (if configured).

This completes enabling Auto Deploy and Monitoring for CodeDeploy via the AWS console, for use with your AWS CodeBuild-based workflows.

Using CLI

In AWS, “Auto Deploy and Monitoring” for CodeDeploy is configured on the CodeDeploy deployment group, not on the CodeBuild project itself. You remediate this by updating the deployment group via AWS CLI to:

  • Enable CloudWatch alarms (monitoring)
  • Enable automatic rollback (auto actions on failures/alarms)

Below is a minimal, step‑by‑step way to do that.


1. Identify your CodeDeploy application and deployment group

You need:

  • --application-name
  • --deployment-group-name
  • List them if unsure:
aws deploy list-applications
aws deploy list-deployment-groups --application-name MyApplicationName

2. (Optional) Create or identify CloudWatch alarms

If you don’t already have alarms, create them (example):

aws cloudwatch put-metric-alarm \
--alarm-name CodeDeploy-Error-Alarm \
--metric-name Errors \
--namespace AWS/ApplicationELB \
--statistic Sum \
--period 60 \
--threshold 1 \
--comparison-operator GreaterThanOrEqualToThreshold \
--evaluation-periods 1 \
--dimensions Name=LoadBalancer,Value=my-load-balancer \
--alarm-actions arn:aws:sns:us-east-1:123456789012:MySNSTopic

Use your own metric/dimensions/region as appropriate.


3. Enable monitoring (CloudWatch alarms) and auto rollback

Run update-deployment-group to:

  • Turn on alarm monitoring
  • Enable rollback on deployment failure and/or alarm

Example:

aws deploy update-deployment-group \
--application-name MyApplicationName \
--current-deployment-group-name MyDeploymentGroup \
--alarm-configuration '{
"enabled": true,
"ignorePollAlarmFailure": false,
"alarms": [
{ "name": "CodeDeploy-Error-Alarm" }
]
}' \
--auto-rollback-configuration '{
"enabled": true,
"events": [
"DEPLOYMENT_FAILURE",
"DEPLOYMENT_STOP_ON_ALARM"
]
}'

Key fields:

  • "enabled": true under alarm-configuration → monitoring enabled.
  • "enabled": true under auto-rollback-configuration → auto rollback enabled.
  • events:
    • DEPLOYMENT_FAILURE – rollback on deployment failure
    • DEPLOYMENT_STOP_ON_ALARM – rollback when an alarm triggers.

4. (Optional) Ensure your CodeBuild → CodeDeploy pipeline uses this group

If you’re using CodePipeline:

  • Confirm the Deploy stage references MyApplicationName and MyDeploymentGroup.
  • No CLI change is needed in CodeBuild itself; the behavior is controlled entirely by the CodeDeploy deployment group you just updated.

If you share your application and deployment group names (sanitized), I can give an exact command tailored to your setup.

Using Python

Below is how to remediate “CodeDeploy Auto Deploy and Monitoring should be enabled” using Python/boto3. This assumes you’re using AWS CodeDeploy as part of your pipeline (e.g., CodeBuild → CodeDeploy → target).

There are two main things to enable:

  1. Automatic rollback (auto deploy safety)
  2. Monitoring via CloudWatch alarms (so CodeDeploy can use alarms to stop/rollback bad deployments)

1. Prerequisites

  • Python 3.x

  • boto3 installed:

    pip install boto3
  • AWS credentials configured (via AWS CLI profile, env vars, or instance profile):

    aws configure
  • You must know:

    • application_name (CodeDeploy Application)
    • deployment_group_name (CodeDeploy Deployment Group)
    • The name(s) of CloudWatch alarms you want CodeDeploy to monitor.

2. Create / Identify CloudWatch Alarm(s)

If you don’t already have a CloudWatch alarm (e.g., on error rate, 5XX count, latency), create one via console or CloudFormation/Terraform.

You only need the alarm name(s) in Python, e.g.:

  • MyApp-High-5xxErrors
  • MyApp-High-Latency

3. Python script to enable Auto-Rollback and Monitoring

This script:

  • Retrieves existing deployment group config
  • Updates it to:
    • Turn on automatic rollback on DEPLOYMENT_FAILURE (and optionally ALARM/CODE_DEPLOY_HEALTH)
    • Enable alarmConfiguration and attach your alarms
import boto3

region = "us-east-1"
application_name = "MyCodeDeployApp"
deployment_group_name = "MyDeploymentGroup"

# CloudWatch alarms that should be monitored during deployments
alarm_names = [
"MyApp-High-5xxErrors",
"MyApp-High-Latency"
]

codedeploy = boto3.client("codedeploy", region_name=region)

def enable_auto_deploy_and_monitoring():
# 1. Get current deployment group config
resp = codedeploy.get_deployment_group(
applicationName=application_name,
deploymentGroupName=deployment_group_name
)

dg = resp["deploymentGroupInfo"]

# 2. Build new autoRollbackConfiguration (keep existing "events" if you like)
auto_rollback_config = dg.get("autoRollbackConfiguration", {})
auto_rollback_config["enabled"] = True

# If no events specified, set a safe default
if not auto_rollback_config.get("events"):
auto_rollback_config["events"] = [
"DEPLOYMENT_FAILURE", # rollback on failed deployment
"DEPLOYMENT_STOP_ON_ALARM", # rollback if alarm triggers
"DEPLOYMENT_STOP_ON_REQUEST" # optional
]

# 3. Build new alarmConfiguration
alarm_configuration = dg.get("alarmConfiguration", {})
alarm_configuration["enabled"] = True
alarm_configuration["alarms"] = [{"name": name} for name in alarm_names]

# 4. Call update_deployment_group, preserving all other fields
# You MUST pass the existing values for required fields, or they will be reset.
update_kwargs = {
"applicationName": application_name,
"currentDeploymentGroupName": deployment_group_name,
"autoRollbackConfiguration": auto_rollback_config,
"alarmConfiguration": alarm_configuration,
}

# Preserve important existing attributes so they are not wiped out.
# Only add them if present.
if "serviceRoleArn" in dg:
update_kwargs["serviceRoleArn"] = dg["serviceRoleArn"]
if "deploymentConfigName" in dg:
update_kwargs["deploymentConfigName"] = dg["deploymentConfigName"]
if "ec2TagFilters" in dg:
update_kwargs["ec2TagFilters"] = dg["ec2TagFilters"]
if "onPremisesInstanceTagFilters" in dg:
update_kwargs["onPremisesInstanceTagFilters"] = dg["onPremisesInstanceTagFilters"]
if "autoScalingGroups" in dg:
update_kwargs["autoScalingGroups"] = [asg["name"] for asg in dg["autoScalingGroups"]]
if "loadBalancerInfo" in dg:
update_kwargs["loadBalancerInfo"] = dg["loadBalancerInfo"]
if "deploymentStyle" in dg:
update_kwargs["deploymentStyle"] = dg["deploymentStyle"]
if "blueGreenDeploymentConfiguration" in dg:
update_kwargs["blueGreenDeploymentConfiguration"] = dg["blueGreenDeploymentConfiguration"]
if "triggerConfigurations" in dg:
update_kwargs["triggerConfigurations"] = dg["triggerConfigurations"]

codedeploy.update_deployment_group(**update_kwargs)
print("Auto deploy (rollback) and monitoring have been enabled for:",
f"{application_name}/{deployment_group_name}")

if __name__ == "__main__":
enable_auto_deploy_and_monitoring()

4. Integrate with CodeBuild (optional)

In your CodeBuild project’s buildspec, you can:

  • Run tests
  • If tests pass, call this script (once, or as part of environment setup)
  • Then trigger CodeDeploy (e.g., via aws deploy create-deployment)

Example buildspec.yml snippet:

version: 0.2

phases:
install:
commands:
- pip install boto3
build:
commands:
- python enable_codedeploy_autodeploy_monitoring.py
# then your deployment command:
- aws deploy create-deployment \
--application-name MyCodeDeployApp \
--deployment-group-name MyDeploymentGroup \
--deployment-config-name CodeDeployDefault.AllAtOnce \
--s3-location bucket=mybucket,key=myapp.zip,bundleType=zip

This ensures that any deployments triggered from your CodeBuild pipeline use a CodeDeploy deployment group that has auto rollback and monitoring enabled, satisfying the “Auto Deploy and Monitoring should be enabled” requirement.

Using Terraform
resource "aws_codedeploy_deployment_group" "CODEDEPLOY_DEPLOYMENT_GROUP" {
app_name = aws_codedeploy_app.CODEDEPLOY_APP.name
deployment_group_name = "CODEDEPLOY_DEPLOYMENT_GROUP_NAME" # replace with your deployment group name
service_role_arn = "CODEDEPLOY_SERVICE_ROLE_ARN" # replace with your IAM role ARN

# Other required configuration for your deployment group
deployment_config_name = "CodeDeployDefault.AllAtOnce"
autoscaling_groups = ["AUTOSCALING_GROUP_NAME"] # replace if you use ASGs
# or use ecs_service / on_premises_instance_tag_filters etc. as appropriate

auto_rollback_configuration {
enabled = true
events = [
"DEPLOYMENT_FAILURE",
"DEPLOYMENT_STOP_ON_ALARM",
]
}

alarm_configuration {
enabled = true

alarms {
name = "YOUR_CLOUDWATCH_ALARM_NAME" # replace with an existing CloudWatch alarm name
}
}
}

This configuration enables automatic rollback on deployment failure or when the monitoring alarm triggers, and enables alarm-based monitoring on the deployment group; both settings mirror the update-deployment-group CLI behavior and will overwrite any existing rollback/alarm configuration on this deployment group. No resource replacement is required; terraform plan should show in-place updates to auto_rollback_configuration and alarm_configuration for aws_codedeploy_deployment_group.CODEDEPLOY_DEPLOYMENT_GROUP.