Skip to content
v2.274.0

AWS CodeDeploy Construct Library ​

Introduction ​

AWS CodeDeploy is a deployment service that automates application deployments to Amazon EC2 instances, on-premises instances, serverless Lambda functions, or Amazon ECS services.

The CDK currently supports Amazon EC2, on-premise, AWS Lambda, and Amazon ECS applications.

EC2/on-premise Applications ​

To create a new CodeDeploy Application that deploys to EC2/on-premise instances:

ts
const application = new codedeploy.ServerApplication(this, 'CodeDeployApplication', {
  applicationName: 'MyApplication', // optional property
});
python
application = codedeploy.ServerApplication(self, "CodeDeployApplication",
    application_name="MyApplication"
)
java
ServerApplication application = ServerApplication.Builder.create(this, "CodeDeployApplication")
        .applicationName("MyApplication")
        .build();
csharp
var application = new ServerApplication(this, "CodeDeployApplication", new ServerApplicationProps {
    ApplicationName = "MyApplication"
});
go
application := codedeploy.NewServerApplication(this, jsii.String("CodeDeployApplication"), &ServerApplicationProps{
	ApplicationName: jsii.String("MyApplication"),
})

To import an already existing Application:

ts
const application = codedeploy.ServerApplication.fromServerApplicationName(
  this,
  'ExistingCodeDeployApplication',
  'MyExistingApplication',
);
python
application = codedeploy.ServerApplication.from_server_application_name(self, "ExistingCodeDeployApplication", "MyExistingApplication")
java
IServerApplication application = ServerApplication.fromServerApplicationName(this, "ExistingCodeDeployApplication", "MyExistingApplication");
csharp
var application = ServerApplication.FromServerApplicationName(this, "ExistingCodeDeployApplication", "MyExistingApplication");
go
application := codedeploy.ServerApplication_FromServerApplicationName(this, jsii.String("ExistingCodeDeployApplication"), jsii.String("MyExistingApplication"))

EC2/on-premise Deployment Groups ​

To create a new CodeDeploy Deployment Group that deploys to EC2/on-premise instances:

ts
import * as autoscaling from 'aws-cdk-lib/aws-autoscaling';
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';

declare const application: codedeploy.ServerApplication;
declare const asg: autoscaling.AutoScalingGroup;
declare const alarm: cloudwatch.Alarm;
const deploymentGroup = new codedeploy.ServerDeploymentGroup(this, 'CodeDeployDeploymentGroup', {
  application,
  deploymentGroupName: 'MyDeploymentGroup',
  autoScalingGroups: [asg],
  // adds User Data that installs the CodeDeploy agent on your auto-scaling groups hosts
  // default: true
  installAgent: true,
  // adds EC2 instances matching tags
  ec2InstanceTags: new codedeploy.InstanceTagSet(
    {
      // any instance with tags satisfying
      // key1=v1 or key1=v2 or key2 (any value) or value v3 (any key)
      // will match this group
      'key1': ['v1', 'v2'],
      'key2': [],
      '': ['v3'],
    },
  ),
  // adds on-premise instances matching tags
  onPremiseInstanceTags: new codedeploy.InstanceTagSet(
    // only instances with tags (key1=v1 or key1=v2) AND key2=v3 will match this set
    {
      'key1': ['v1', 'v2'],
    },
    {
      'key2': ['v3'],
    },
  ),
  // CloudWatch alarms
  alarms: [alarm],
  // whether to ignore failure to fetch the status of alarms from CloudWatch
  // default: false
  ignorePollAlarmsFailure: false,
  // whether to skip the step of checking CloudWatch alarms during the deployment process
  // default: false
  ignoreAlarmConfiguration: false,
  // auto-rollback configuration
  autoRollback: {
    failedDeployment: true, // default: true
    stoppedDeployment: true, // default: false
    deploymentInAlarm: true, // default: true if you provided any alarms, false otherwise
  },
  // whether the deployment group was configured to have CodeDeploy install a termination hook into an Auto Scaling group
  // default: false
  terminationHook: true,
});
python
import aws_cdk.aws_autoscaling as autoscaling
import aws_cdk.aws_cloudwatch as cloudwatch

# application: codedeploy.ServerApplication
# asg: autoscaling.AutoScalingGroup
# alarm: cloudwatch.Alarm

deployment_group = codedeploy.ServerDeploymentGroup(self, "CodeDeployDeploymentGroup",
    application=application,
    deployment_group_name="MyDeploymentGroup",
    auto_scaling_groups=[asg],
    # adds User Data that installs the CodeDeploy agent on your auto-scaling groups hosts
    # default: true
    install_agent=True,
    # adds EC2 instances matching tags
    ec2_instance_tags=codedeploy.InstanceTagSet({
        # any instance with tags satisfying
        # key1=v1 or key1=v2 or key2 (any value) or value v3 (any key)
        # will match this group
        "key1": ["v1", "v2"],
        "key2": [],
        "": ["v3"]
    }),
    # adds on-premise instances matching tags
    on_premise_instance_tags=codedeploy.InstanceTagSet({
        "key1": ["v1", "v2"]
    }, {
        "key2": ["v3"]
    }),
    # CloudWatch alarms
    alarms=[alarm],
    # whether to ignore failure to fetch the status of alarms from CloudWatch
    # default: false
    ignore_poll_alarms_failure=False,
    # whether to skip the step of checking CloudWatch alarms during the deployment process
    # default: false
    ignore_alarm_configuration=False,
    # auto-rollback configuration
    auto_rollback=codedeploy.AutoRollbackConfig(
        failed_deployment=True,  # default: true
        stopped_deployment=True,  # default: false
        deployment_in_alarm=True
    ),
    # whether the deployment group was configured to have CodeDeploy install a termination hook into an Auto Scaling group
    # default: false
    termination_hook=True
)
java
import software.amazon.awscdk.services.autoscaling.*;
import software.amazon.awscdk.services.cloudwatch.*;

ServerApplication application;
AutoScalingGroup asg;
Alarm alarm;

ServerDeploymentGroup deploymentGroup = ServerDeploymentGroup.Builder.create(this, "CodeDeployDeploymentGroup")
        .application(application)
        .deploymentGroupName("MyDeploymentGroup")
        .autoScalingGroups(List.of(asg))
        // adds User Data that installs the CodeDeploy agent on your auto-scaling groups hosts
        // default: true
        .installAgent(true)
        // adds EC2 instances matching tags
        .ec2InstanceTags(new InstanceTagSet(Map.of(
                // any instance with tags satisfying
                // key1=v1 or key1=v2 or key2 (any value) or value v3 (any key)
                // will match this group
                "key1", List.of("v1", "v2"),
                "key2", List.of(),
                "", List.of("v3"))))
        // adds on-premise instances matching tags
        .onPremiseInstanceTags(new InstanceTagSet(Map.of(
                "key1", List.of("v1", "v2")), Map.of(
                "key2", List.of("v3"))))
        // CloudWatch alarms
        .alarms(List.of(alarm))
        // whether to ignore failure to fetch the status of alarms from CloudWatch
        // default: false
        .ignorePollAlarmsFailure(false)
        // whether to skip the step of checking CloudWatch alarms during the deployment process
        // default: false
        .ignoreAlarmConfiguration(false)
        // auto-rollback configuration
        .autoRollback(AutoRollbackConfig.builder()
                .failedDeployment(true) // default: true
                .stoppedDeployment(true) // default: false
                .deploymentInAlarm(true)
                .build())
        // whether the deployment group was configured to have CodeDeploy install a termination hook into an Auto Scaling group
        // default: false
        .terminationHook(true)
        .build();
csharp
using Amazon.CDK.AWS.AutoScaling;
using Amazon.CDK.AWS.CloudWatch;

ServerApplication application;
AutoScalingGroup asg;
Alarm alarm;

var deploymentGroup = new ServerDeploymentGroup(this, "CodeDeployDeploymentGroup", new ServerDeploymentGroupProps {
    Application = application,
    DeploymentGroupName = "MyDeploymentGroup",
    AutoScalingGroups = new [] { asg },
    // adds User Data that installs the CodeDeploy agent on your auto-scaling groups hosts
    // default: true
    InstallAgent = true,
    // adds EC2 instances matching tags
    Ec2InstanceTags = new InstanceTagSet(new Dictionary<string, string[]> {
        // any instance with tags satisfying
        // key1=v1 or key1=v2 or key2 (any value) or value v3 (any key)
        // will match this group
        { "key1", new [] { "v1", "v2" } },
        { "key2", new [] {  } },
        { "", new [] { "v3" } }
    }),
    // adds on-premise instances matching tags
    OnPremiseInstanceTags = new InstanceTagSet(new Dictionary<string, string[]> {
        { "key1", new [] { "v1", "v2" } }
    }, new Dictionary<string, string[]> {
        { "key2", new [] { "v3" } }
    }),
    // CloudWatch alarms
    Alarms = new [] { alarm },
    // whether to ignore failure to fetch the status of alarms from CloudWatch
    // default: false
    IgnorePollAlarmsFailure = false,
    // whether to skip the step of checking CloudWatch alarms during the deployment process
    // default: false
    IgnoreAlarmConfiguration = false,
    // auto-rollback configuration
    AutoRollback = new AutoRollbackConfig {
        FailedDeployment = true,  // default: true
        StoppedDeployment = true,  // default: false
        DeploymentInAlarm = true
    },
    // whether the deployment group was configured to have CodeDeploy install a termination hook into an Auto Scaling group
    // default: false
    TerminationHook = true
});
go
import autoscaling "github.com/aws/aws-cdk-go/awscdk"
import cloudwatch "github.com/aws/aws-cdk-go/awscdk"

var application ServerApplication
var asg AutoScalingGroup
var alarm Alarm

deploymentGroup := codedeploy.NewServerDeploymentGroup(this, jsii.String("CodeDeployDeploymentGroup"), &ServerDeploymentGroupProps{
	Application: Application,
	DeploymentGroupName: jsii.String("MyDeploymentGroup"),
	AutoScalingGroups: []IAutoScalingGroup{
		asg,
	},
	// adds User Data that installs the CodeDeploy agent on your auto-scaling groups hosts
	// default: true
	InstallAgent: jsii.Boolean(true),
	// adds EC2 instances matching tags
	Ec2InstanceTags: codedeploy.NewInstanceTagSet(map[string][]*string{
		// any instance with tags satisfying
		// key1=v1 or key1=v2 or key2 (any value) or value v3 (any key)
		// will match this group
		"key1": []*string{
			jsii.String("v1"),
			jsii.String("v2"),
		},
		"key2": []*string{
		},
		"": []*string{
			jsii.String("v3"),
		},
	}),
	// adds on-premise instances matching tags
	OnPremiseInstanceTags: codedeploy.NewInstanceTagSet(map[string][]*string{
		"key1": []*string{
			jsii.String("v1"),
			jsii.String("v2"),
		},
	}, map[string][]*string{
		"key2": []*string{
			jsii.String("v3"),
		},
	}),
	// CloudWatch alarms
	Alarms: []IAlarmRef{
		alarm,
	},
	// whether to ignore failure to fetch the status of alarms from CloudWatch
	// default: false
	IgnorePollAlarmsFailure: jsii.Boolean(false),
	// whether to skip the step of checking CloudWatch alarms during the deployment process
	// default: false
	IgnoreAlarmConfiguration: jsii.Boolean(false),
	// auto-rollback configuration
	AutoRollback: &AutoRollbackConfig{
		FailedDeployment: jsii.Boolean(true),
		 // default: true
		StoppedDeployment: jsii.Boolean(true),
		 // default: false
		DeploymentInAlarm: jsii.Boolean(true),
	},
	// whether the deployment group was configured to have CodeDeploy install a termination hook into an Auto Scaling group
	// default: false
	TerminationHook: jsii.Boolean(true),
})

All properties are optional - if you don't provide an Application, one will be automatically created.

To import an already existing Deployment Group:

ts
declare const application: codedeploy.ServerApplication;
const deploymentGroup = codedeploy.ServerDeploymentGroup.fromServerDeploymentGroupAttributes(
  this,
  'ExistingCodeDeployDeploymentGroup', {
    application,
    deploymentGroupName: 'MyExistingDeploymentGroup',
  },
);
python
# application: codedeploy.ServerApplication

deployment_group = codedeploy.ServerDeploymentGroup.from_server_deployment_group_attributes(self, "ExistingCodeDeployDeploymentGroup",
    application=application,
    deployment_group_name="MyExistingDeploymentGroup"
)
java
ServerApplication application;

IServerDeploymentGroup deploymentGroup = ServerDeploymentGroup.fromServerDeploymentGroupAttributes(this, "ExistingCodeDeployDeploymentGroup", ServerDeploymentGroupAttributes.builder()
        .application(application)
        .deploymentGroupName("MyExistingDeploymentGroup")
        .build());
csharp
ServerApplication application;

var deploymentGroup = ServerDeploymentGroup.FromServerDeploymentGroupAttributes(this, "ExistingCodeDeployDeploymentGroup", new ServerDeploymentGroupAttributes {
    Application = application,
    DeploymentGroupName = "MyExistingDeploymentGroup"
});
go
var application ServerApplication

deploymentGroup := codedeploy.ServerDeploymentGroup_FromServerDeploymentGroupAttributes(this, jsii.String("ExistingCodeDeployDeploymentGroup"), &ServerDeploymentGroupAttributes{
	Application: Application,
	DeploymentGroupName: jsii.String("MyExistingDeploymentGroup"),
})

Load balancers ​

You can specify a load balancer with the loadBalancer property when creating a Deployment Group.

LoadBalancer is an abstract class with static factory methods that allow you to create instances of it from various sources.

With Classic Elastic Load Balancer, you provide it directly:

ts
import * as elb from 'aws-cdk-lib/aws-elasticloadbalancing';

declare const lb: elb.LoadBalancer;
lb.addListener({
  externalPort: 80,
});

const deploymentGroup = new codedeploy.ServerDeploymentGroup(this, 'DeploymentGroup', {
  loadBalancer: codedeploy.LoadBalancer.classic(lb),
});
python
import aws_cdk.aws_elasticloadbalancing as elb

# lb: elb.LoadBalancer

lb.add_listener(
    external_port=80
)

deployment_group = codedeploy.ServerDeploymentGroup(self, "DeploymentGroup",
    load_balancer=codedeploy.LoadBalancer.classic(lb)
)
java
import software.amazon.awscdk.services.elasticloadbalancing.*;

LoadBalancer lb;

lb.addListener(LoadBalancerListener.builder()
        .externalPort(80)
        .build());

ServerDeploymentGroup deploymentGroup = ServerDeploymentGroup.Builder.create(this, "DeploymentGroup")
        .loadBalancer(LoadBalancer.classic(lb))
        .build();
csharp
using Amazon.CDK.AWS.ElasticLoadBalancing;

LoadBalancer lb;

lb.AddListener(new LoadBalancerListener {
    ExternalPort = 80
});

var deploymentGroup = new ServerDeploymentGroup(this, "DeploymentGroup", new ServerDeploymentGroupProps {
    LoadBalancer = LoadBalancer.Classic(lb)
});
go
import elb "github.com/aws/aws-cdk-go/awscdk"

var lb LoadBalancer

lb.AddListener(&LoadBalancerListener{
	ExternalPort: jsii.Number(80),
})

deploymentGroup := codedeploy.NewServerDeploymentGroup(this, jsii.String("DeploymentGroup"), &ServerDeploymentGroupProps{
	LoadBalancer: codedeploy.LoadBalancer_Classic(lb),
})

With Application Load Balancer or Network Load Balancer, you provide a Target Group as the load balancer:

ts
declare const alb: elbv2.ApplicationLoadBalancer;
const listener = alb.addListener('Listener', { port: 80 });
const targetGroup = listener.addTargets('Fleet', { port: 80 });

const deploymentGroup = new codedeploy.ServerDeploymentGroup(this, 'DeploymentGroup', {
  loadBalancer: codedeploy.LoadBalancer.application(targetGroup),
});
python
# alb: elbv2.ApplicationLoadBalancer

listener = alb.add_listener("Listener", port=80)
target_group = listener.add_targets("Fleet", port=80)

deployment_group = codedeploy.ServerDeploymentGroup(self, "DeploymentGroup",
    load_balancer=codedeploy.LoadBalancer.application(target_group)
)
java
ApplicationLoadBalancer alb;

ApplicationListener listener = alb.addListener("Listener", BaseApplicationListenerProps.builder().port(80).build());
ApplicationTargetGroup targetGroup = listener.addTargets("Fleet", AddApplicationTargetsProps.builder().port(80).build());

ServerDeploymentGroup deploymentGroup = ServerDeploymentGroup.Builder.create(this, "DeploymentGroup")
        .loadBalancer(LoadBalancer.application(targetGroup))
        .build();
csharp
ApplicationLoadBalancer alb;

var listener = alb.AddListener("Listener", new BaseApplicationListenerProps { Port = 80 });
var targetGroup = listener.AddTargets("Fleet", new AddApplicationTargetsProps { Port = 80 });

var deploymentGroup = new ServerDeploymentGroup(this, "DeploymentGroup", new ServerDeploymentGroupProps {
    LoadBalancer = LoadBalancer.Application(targetGroup)
});
go
var alb ApplicationLoadBalancer

listener := alb.AddListener(jsii.String("Listener"), &BaseApplicationListenerProps{
	Port: jsii.Number(80),
})
targetGroup := listener.AddTargets(jsii.String("Fleet"), &AddApplicationTargetsProps{
	Port: jsii.Number(80),
})

deploymentGroup := codedeploy.NewServerDeploymentGroup(this, jsii.String("DeploymentGroup"), &ServerDeploymentGroupProps{
	LoadBalancer: codedeploy.LoadBalancer_Application(targetGroup),
})

The loadBalancer property has been deprecated. To provide multiple Elastic Load Balancers as target groups use the loadBalancers parameter:

ts
import * as elb from 'aws-cdk-lib/aws-elasticloadbalancing';
import * as elb2 from 'aws-cdk-lib/aws-elasticloadbalancingv2';

declare const clb: elb.LoadBalancer;
declare const alb: elb2.ApplicationLoadBalancer;
declare const nlb: elb2.NetworkLoadBalancer;

const albListener = alb.addListener('ALBListener', { port: 80 });
const albTargetGroup = albListener.addTargets('ALBFleet', { port: 80 });

const nlbListener = nlb.addListener('NLBListener', { port: 80 });
const nlbTargetGroup = nlbListener.addTargets('NLBFleet', { port: 80 });

const deploymentGroup = new codedeploy.ServerDeploymentGroup(this, 'DeploymentGroup', {
  loadBalancers: [
    codedeploy.LoadBalancer.classic(clb),
    codedeploy.LoadBalancer.application(albTargetGroup),
    codedeploy.LoadBalancer.network(nlbTargetGroup),
  ]
});
python
import aws_cdk.aws_elasticloadbalancing as elb
import aws_cdk.aws_elasticloadbalancingv2 as elb2

# clb: elb.LoadBalancer
# alb: elb2.ApplicationLoadBalancer
# nlb: elb2.NetworkLoadBalancer


alb_listener = alb.add_listener("ALBListener", port=80)
alb_target_group = alb_listener.add_targets("ALBFleet", port=80)

nlb_listener = nlb.add_listener("NLBListener", port=80)
nlb_target_group = nlb_listener.add_targets("NLBFleet", port=80)

deployment_group = codedeploy.ServerDeploymentGroup(self, "DeploymentGroup",
    load_balancers=[
        codedeploy.LoadBalancer.classic(clb),
        codedeploy.LoadBalancer.application(alb_target_group),
        codedeploy.LoadBalancer.network(nlb_target_group)
    ]
)
java
import software.amazon.awscdk.services.elasticloadbalancing.*;
import software.amazon.awscdk.services.elasticloadbalancingv2.*;

LoadBalancer clb;
ApplicationLoadBalancer alb;
NetworkLoadBalancer nlb;


ApplicationListener albListener = alb.addListener("ALBListener", BaseApplicationListenerProps.builder().port(80).build());
ApplicationTargetGroup albTargetGroup = albListener.addTargets("ALBFleet", AddApplicationTargetsProps.builder().port(80).build());

NetworkListener nlbListener = nlb.addListener("NLBListener", BaseNetworkListenerProps.builder().port(80).build());
NetworkTargetGroup nlbTargetGroup = nlbListener.addTargets("NLBFleet", AddNetworkTargetsProps.builder().port(80).build());

ServerDeploymentGroup deploymentGroup = ServerDeploymentGroup.Builder.create(this, "DeploymentGroup")
        .loadBalancers(List.of(LoadBalancer.classic(clb), LoadBalancer.application(albTargetGroup), LoadBalancer.network(nlbTargetGroup)))
        .build();
csharp
using Amazon.CDK.AWS.ElasticLoadBalancing;
using Amazon.CDK.AWS.ElasticLoadBalancingV2;

LoadBalancer clb;
ApplicationLoadBalancer alb;
NetworkLoadBalancer nlb;


var albListener = alb.AddListener("ALBListener", new BaseApplicationListenerProps { Port = 80 });
var albTargetGroup = albListener.AddTargets("ALBFleet", new AddApplicationTargetsProps { Port = 80 });

var nlbListener = nlb.AddListener("NLBListener", new BaseNetworkListenerProps { Port = 80 });
var nlbTargetGroup = nlbListener.AddTargets("NLBFleet", new AddNetworkTargetsProps { Port = 80 });

var deploymentGroup = new ServerDeploymentGroup(this, "DeploymentGroup", new ServerDeploymentGroupProps {
    LoadBalancers = new [] { LoadBalancer.Classic(clb), LoadBalancer.Application(albTargetGroup), LoadBalancer.Network(nlbTargetGroup) }
});
go
import elb "github.com/aws/aws-cdk-go/awscdk"
import elb2 "github.com/aws/aws-cdk-go/awscdk"

var clb LoadBalancer
var alb ApplicationLoadBalancer
var nlb NetworkLoadBalancer


albListener := alb.AddListener(jsii.String("ALBListener"), &BaseApplicationListenerProps{
	Port: jsii.Number(80),
})
albTargetGroup := albListener.AddTargets(jsii.String("ALBFleet"), &AddApplicationTargetsProps{
	Port: jsii.Number(80),
})

nlbListener := nlb.AddListener(jsii.String("NLBListener"), &BaseNetworkListenerProps{
	Port: jsii.Number(80),
})
nlbTargetGroup := nlbListener.AddTargets(jsii.String("NLBFleet"), &AddNetworkTargetsProps{
	Port: jsii.Number(80),
})

deploymentGroup := codedeploy.NewServerDeploymentGroup(this, jsii.String("DeploymentGroup"), &ServerDeploymentGroupProps{
	LoadBalancers: []LoadBalancer{
		codedeploy.LoadBalancer_Classic(clb),
		codedeploy.LoadBalancer_Application(albTargetGroup),
		codedeploy.LoadBalancer_Network(nlbTargetGroup),
	},
})

EC2/on-premise Deployment Configurations ​

You can also pass a Deployment Configuration when creating the Deployment Group:

ts
const deploymentGroup = new codedeploy.ServerDeploymentGroup(this, 'CodeDeployDeploymentGroup', {
  deploymentConfig: codedeploy.ServerDeploymentConfig.ALL_AT_ONCE,
});
python
deployment_group = codedeploy.ServerDeploymentGroup(self, "CodeDeployDeploymentGroup",
    deployment_config=codedeploy.ServerDeploymentConfig.ALL_AT_ONCE
)
java
ServerDeploymentGroup deploymentGroup = ServerDeploymentGroup.Builder.create(this, "CodeDeployDeploymentGroup")
        .deploymentConfig(ServerDeploymentConfig.ALL_AT_ONCE)
        .build();
csharp
var deploymentGroup = new ServerDeploymentGroup(this, "CodeDeployDeploymentGroup", new ServerDeploymentGroupProps {
    DeploymentConfig = ServerDeploymentConfig.ALL_AT_ONCE
});
go
deploymentGroup := codedeploy.NewServerDeploymentGroup(this, jsii.String("CodeDeployDeploymentGroup"), &ServerDeploymentGroupProps{
	DeploymentConfig: codedeploy.ServerDeploymentConfig_ALL_AT_ONCE(),
})

The default Deployment Configuration is ServerDeploymentConfig.ONE_AT_A_TIME.

You can also create a custom Deployment Configuration:

ts
const deploymentConfig = new codedeploy.ServerDeploymentConfig(this, 'DeploymentConfiguration', {
  deploymentConfigName: 'MyDeploymentConfiguration', // optional property
  // one of these is required, but both cannot be specified at the same time
  minimumHealthyHosts: codedeploy.MinimumHealthyHosts.count(2),
  // minimumHealthyHosts: codedeploy.MinimumHealthyHosts.percentage(75),
});
python
deployment_config = codedeploy.ServerDeploymentConfig(self, "DeploymentConfiguration",
    deployment_config_name="MyDeploymentConfiguration",  # optional property
    # one of these is required, but both cannot be specified at the same time
    minimum_healthy_hosts=codedeploy.MinimumHealthyHosts.count(2)
)
java
ServerDeploymentConfig deploymentConfig = ServerDeploymentConfig.Builder.create(this, "DeploymentConfiguration")
        .deploymentConfigName("MyDeploymentConfiguration") // optional property
        // one of these is required, but both cannot be specified at the same time
        .minimumHealthyHosts(MinimumHealthyHosts.count(2))
        .build();
csharp
var deploymentConfig = new ServerDeploymentConfig(this, "DeploymentConfiguration", new ServerDeploymentConfigProps {
    DeploymentConfigName = "MyDeploymentConfiguration",  // optional property
    // one of these is required, but both cannot be specified at the same time
    MinimumHealthyHosts = MinimumHealthyHosts.Count(2)
});
go
deploymentConfig := codedeploy.NewServerDeploymentConfig(this, jsii.String("DeploymentConfiguration"), &ServerDeploymentConfigProps{
	DeploymentConfigName: jsii.String("MyDeploymentConfiguration"),
	 // optional property
	// one of these is required, but both cannot be specified at the same time
	MinimumHealthyHosts: codedeploy.MinimumHealthyHosts_Count(jsii.Number(2)),
})

Or import an existing one:

ts
const deploymentConfig = codedeploy.ServerDeploymentConfig.fromServerDeploymentConfigName(
  this,
  'ExistingDeploymentConfiguration',
  'MyExistingDeploymentConfiguration',
);
python
deployment_config = codedeploy.ServerDeploymentConfig.from_server_deployment_config_name(self, "ExistingDeploymentConfiguration", "MyExistingDeploymentConfiguration")
java
IServerDeploymentConfig deploymentConfig = ServerDeploymentConfig.fromServerDeploymentConfigName(this, "ExistingDeploymentConfiguration", "MyExistingDeploymentConfiguration");
csharp
var deploymentConfig = ServerDeploymentConfig.FromServerDeploymentConfigName(this, "ExistingDeploymentConfiguration", "MyExistingDeploymentConfiguration");
go
deploymentConfig := codedeploy.ServerDeploymentConfig_FromServerDeploymentConfigName(this, jsii.String("ExistingDeploymentConfiguration"), jsii.String("MyExistingDeploymentConfiguration"))

Zonal Configuration ​

CodeDeploy can deploy your application to one Availability Zone at a time, within an AWS Region by configuring zonal configuration.

To create a new deployment configuration with zonal configuration:

ts
const deploymentConfig = new codedeploy.ServerDeploymentConfig(this, 'DeploymentConfiguration', {
  minimumHealthyHosts: codedeploy.MinimumHealthyHosts.count(2),
  zonalConfig: {
    monitorDuration: Duration.minutes(30),
    firstZoneMonitorDuration: Duration.minutes(60),
    minimumHealthyHostsPerZone: codedeploy.MinimumHealthyHostsPerZone.count(1),
  },
});
python
deployment_config = codedeploy.ServerDeploymentConfig(self, "DeploymentConfiguration",
    minimum_healthy_hosts=codedeploy.MinimumHealthyHosts.count(2),
    zonal_config=codedeploy.ZonalConfig(
        monitor_duration=Duration.minutes(30),
        first_zone_monitor_duration=Duration.minutes(60),
        minimum_healthy_hosts_per_zone=codedeploy.MinimumHealthyHostsPerZone.count(1)
    )
)
java
ServerDeploymentConfig deploymentConfig = ServerDeploymentConfig.Builder.create(this, "DeploymentConfiguration")
        .minimumHealthyHosts(MinimumHealthyHosts.count(2))
        .zonalConfig(ZonalConfig.builder()
                .monitorDuration(Duration.minutes(30))
                .firstZoneMonitorDuration(Duration.minutes(60))
                .minimumHealthyHostsPerZone(MinimumHealthyHostsPerZone.count(1))
                .build())
        .build();
csharp
var deploymentConfig = new ServerDeploymentConfig(this, "DeploymentConfiguration", new ServerDeploymentConfigProps {
    MinimumHealthyHosts = MinimumHealthyHosts.Count(2),
    ZonalConfig = new ZonalConfig {
        MonitorDuration = Duration.Minutes(30),
        FirstZoneMonitorDuration = Duration.Minutes(60),
        MinimumHealthyHostsPerZone = MinimumHealthyHostsPerZone.Count(1)
    }
});
go
deploymentConfig := codedeploy.NewServerDeploymentConfig(this, jsii.String("DeploymentConfiguration"), &ServerDeploymentConfigProps{
	MinimumHealthyHosts: codedeploy.MinimumHealthyHosts_Count(jsii.Number(2)),
	ZonalConfig: &ZonalConfig{
		MonitorDuration: awscdk.Duration_Minutes(jsii.Number(30)),
		FirstZoneMonitorDuration: awscdk.Duration_*Minutes(jsii.Number(60)),
		MinimumHealthyHostsPerZone: codedeploy.MinimumHealthyHostsPerZone_Count(jsii.Number(1)),
	},
})

Note: Zonal configuration is only configurable for EC2/on-premise deployments.

Lambda Applications ​

To create a new CodeDeploy Application that deploys to a Lambda function:

ts
const application = new codedeploy.LambdaApplication(this, 'CodeDeployApplication', {
  applicationName: 'MyApplication', // optional property
});
python
application = codedeploy.LambdaApplication(self, "CodeDeployApplication",
    application_name="MyApplication"
)
java
LambdaApplication application = LambdaApplication.Builder.create(this, "CodeDeployApplication")
        .applicationName("MyApplication")
        .build();
csharp
var application = new LambdaApplication(this, "CodeDeployApplication", new LambdaApplicationProps {
    ApplicationName = "MyApplication"
});
go
application := codedeploy.NewLambdaApplication(this, jsii.String("CodeDeployApplication"), &LambdaApplicationProps{
	ApplicationName: jsii.String("MyApplication"),
})

To import an already existing Application:

ts
const application = codedeploy.LambdaApplication.fromLambdaApplicationName(
  this,
  'ExistingCodeDeployApplication',
  'MyExistingApplication',
);
python
application = codedeploy.LambdaApplication.from_lambda_application_name(self, "ExistingCodeDeployApplication", "MyExistingApplication")
java
ILambdaApplication application = LambdaApplication.fromLambdaApplicationName(this, "ExistingCodeDeployApplication", "MyExistingApplication");
csharp
var application = LambdaApplication.FromLambdaApplicationName(this, "ExistingCodeDeployApplication", "MyExistingApplication");
go
application := codedeploy.LambdaApplication_FromLambdaApplicationName(this, jsii.String("ExistingCodeDeployApplication"), jsii.String("MyExistingApplication"))

Lambda Deployment Groups ​

To enable traffic shifting deployments for Lambda functions, CodeDeploy uses Lambda Aliases, which can balance incoming traffic between two different versions of your function. Before deployment, the alias sends 100% of invokes to the version used in production. When you publish a new version of the function to your stack, CodeDeploy will send a small percentage of traffic to the new version, monitor, and validate before shifting 100% of traffic to the new version.

To create a new CodeDeploy Deployment Group that deploys to a Lambda function:

ts
declare const myApplication: codedeploy.LambdaApplication;
declare const func: lambda.Function;
const version = func.currentVersion;
const version1Alias = new lambda.Alias(this, 'alias', {
  aliasName: 'prod',
  version,
});

const deploymentGroup = new codedeploy.LambdaDeploymentGroup(this, 'BlueGreenDeployment', {
  application: myApplication, // optional property: one will be created for you if not provided
  alias: version1Alias,
  deploymentConfig: codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE,
});
python
# my_application: codedeploy.LambdaApplication
# func: lambda.Function

version = func.current_version
version1_alias = lambda_.Alias(self, "alias",
    alias_name="prod",
    version=version
)

deployment_group = codedeploy.LambdaDeploymentGroup(self, "BlueGreenDeployment",
    application=my_application,  # optional property: one will be created for you if not provided
    alias=version1_alias,
    deployment_config=codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE
)
java
LambdaApplication myApplication;
Function func;

Version version = func.getCurrentVersion();
Alias version1Alias = Alias.Builder.create(this, "alias")
        .aliasName("prod")
        .version(version)
        .build();

LambdaDeploymentGroup deploymentGroup = LambdaDeploymentGroup.Builder.create(this, "BlueGreenDeployment")
        .application(myApplication) // optional property: one will be created for you if not provided
        .alias(version1Alias)
        .deploymentConfig(LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE)
        .build();
csharp
LambdaApplication myApplication;
Function func;

var version = func.CurrentVersion;
var version1Alias = new Alias(this, "alias", new AliasProps {
    AliasName = "prod",
    Version = version
});

var deploymentGroup = new LambdaDeploymentGroup(this, "BlueGreenDeployment", new LambdaDeploymentGroupProps {
    Application = myApplication,  // optional property: one will be created for you if not provided
    Alias = version1Alias,
    DeploymentConfig = LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE
});
go
var myApplication LambdaApplication
var func Function

version := func.currentVersion
version1Alias := lambda.NewAlias(this, jsii.String("alias"), &AliasProps{
	AliasName: jsii.String("prod"),
	Version: Version,
})

deploymentGroup := codedeploy.NewLambdaDeploymentGroup(this, jsii.String("BlueGreenDeployment"), &LambdaDeploymentGroupProps{
	Application: myApplication,
	 // optional property: one will be created for you if not provided
	Alias: version1Alias,
	DeploymentConfig: codedeploy.LambdaDeploymentConfig_LINEAR_10PERCENT_EVERY_1MINUTE(),
})

In order to deploy a new version of this function:

  1. Reference the version with the latest changes const version = func.currentVersion.
  2. Re-deploy the stack (this will trigger a deployment).
  3. Monitor the CodeDeploy deployment as traffic shifts between the versions.

Lambda Deployment Rollbacks and Alarms ​

CodeDeploy will roll back if the deployment fails. You can optionally trigger a rollback when one or more alarms are in a failed state:

ts
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';

declare const alias: lambda.Alias;
const alarm = new cloudwatch.Alarm(this, 'Errors', {
  comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD,
  threshold: 1,
  evaluationPeriods: 1,
  metric: alias.metricErrors(),
});
const deploymentGroup = new codedeploy.LambdaDeploymentGroup(this, 'BlueGreenDeployment', {
  alias,
  deploymentConfig: codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE,
  alarms: [
    // pass some alarms when constructing the deployment group
    alarm,
  ],
});

// or add alarms to an existing group
declare const blueGreenAlias: lambda.Alias;
deploymentGroup.addAlarm(new cloudwatch.Alarm(this, 'BlueGreenErrors', {
  comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD,
  threshold: 1,
  evaluationPeriods: 1,
  metric: blueGreenAlias.metricErrors(),
}));
python
import aws_cdk.aws_cloudwatch as cloudwatch

# alias: lambda.Alias

# or add alarms to an existing group
# blue_green_alias: lambda.Alias

alarm = cloudwatch.Alarm(self, "Errors",
    comparison_operator=cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD,
    threshold=1,
    evaluation_periods=1,
    metric=alias.metric_errors()
)
deployment_group = codedeploy.LambdaDeploymentGroup(self, "BlueGreenDeployment",
    alias=alias,
    deployment_config=codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE,
    alarms=[alarm
    ]
)
deployment_group.add_alarm(cloudwatch.Alarm(self, "BlueGreenErrors",
    comparison_operator=cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD,
    threshold=1,
    evaluation_periods=1,
    metric=blue_green_alias.metric_errors()
))
java
import software.amazon.awscdk.services.cloudwatch.*;

Alias alias;

// or add alarms to an existing group
Alias blueGreenAlias;

Alarm alarm = Alarm.Builder.create(this, "Errors")
        .comparisonOperator(ComparisonOperator.GREATER_THAN_THRESHOLD)
        .threshold(1)
        .evaluationPeriods(1)
        .metric(alias.metricErrors())
        .build();
LambdaDeploymentGroup deploymentGroup = LambdaDeploymentGroup.Builder.create(this, "BlueGreenDeployment")
        .alias(alias)
        .deploymentConfig(LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE)
        .alarms(List.of(alarm))
        .build();
deploymentGroup.addAlarm(Alarm.Builder.create(this, "BlueGreenErrors")
        .comparisonOperator(ComparisonOperator.GREATER_THAN_THRESHOLD)
        .threshold(1)
        .evaluationPeriods(1)
        .metric(blueGreenAlias.metricErrors())
        .build());
csharp
using Amazon.CDK.AWS.CloudWatch;

Alias alias;

// or add alarms to an existing group
Alias blueGreenAlias;

var alarm = new Alarm(this, "Errors", new AlarmProps {
    ComparisonOperator = ComparisonOperator.GREATER_THAN_THRESHOLD,
    Threshold = 1,
    EvaluationPeriods = 1,
    Metric = alias.MetricErrors()
});
var deploymentGroup = new LambdaDeploymentGroup(this, "BlueGreenDeployment", new LambdaDeploymentGroupProps {
    Alias = alias,
    DeploymentConfig = LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE,
    Alarms = new [] { alarm }
});
deploymentGroup.AddAlarm(new Alarm(this, "BlueGreenErrors", new AlarmProps {
    ComparisonOperator = ComparisonOperator.GREATER_THAN_THRESHOLD,
    Threshold = 1,
    EvaluationPeriods = 1,
    Metric = blueGreenAlias.MetricErrors()
}));
go
import "github.com/aws/aws-cdk-go/awscdk"

var alias Alias

// or add alarms to an existing group
var blueGreenAlias Alias

alarm := cloudwatch.NewAlarm(this, jsii.String("Errors"), &AlarmProps{
	ComparisonOperator: cloudwatch.ComparisonOperator_GREATER_THAN_THRESHOLD,
	Threshold: jsii.Number(1),
	EvaluationPeriods: jsii.Number(1),
	Metric: alias.metricErrors(),
})
deploymentGroup := codedeploy.NewLambdaDeploymentGroup(this, jsii.String("BlueGreenDeployment"), &LambdaDeploymentGroupProps{
	Alias: Alias,
	DeploymentConfig: codedeploy.LambdaDeploymentConfig_LINEAR_10PERCENT_EVERY_1MINUTE(),
	Alarms: []IAlarmRef{
		alarm,
	},
})
deploymentGroup.AddAlarm(cloudwatch.NewAlarm(this, jsii.String("BlueGreenErrors"), &AlarmProps{
	ComparisonOperator: cloudwatch.ComparisonOperator_GREATER_THAN_THRESHOLD,
	Threshold: jsii.Number(1),
	EvaluationPeriods: jsii.Number(1),
	Metric: blueGreenAlias.metricErrors(),
}))

Pre and Post Hooks ​

CodeDeploy allows you to run an arbitrary Lambda function before traffic shifting actually starts (PreTraffic Hook) and after it completes (PostTraffic Hook). With either hook, you have the opportunity to run logic that determines whether the deployment must succeed or fail. For example, with PreTraffic hook you could run integration tests against the newly created Lambda version (but not serving traffic). With PostTraffic hook, you could run end-to-end validation checks.

ts
declare const warmUpUserCache: lambda.Function;
declare const endToEndValidation: lambda.Function;
declare const alias: lambda.Alias;

// pass a hook whe creating the deployment group
const deploymentGroup = new codedeploy.LambdaDeploymentGroup(this, 'BlueGreenDeployment', {
  alias: alias,
  deploymentConfig: codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE,
  preHook: warmUpUserCache,
});

// or configure one on an existing deployment group
deploymentGroup.addPostHook(endToEndValidation);
python
# warm_up_user_cache: lambda.Function
# end_to_end_validation: lambda.Function
# alias: lambda.Alias


# pass a hook whe creating the deployment group
deployment_group = codedeploy.LambdaDeploymentGroup(self, "BlueGreenDeployment",
    alias=alias,
    deployment_config=codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE,
    pre_hook=warm_up_user_cache
)

# or configure one on an existing deployment group
deployment_group.add_post_hook(end_to_end_validation)
java
Function warmUpUserCache;
Function endToEndValidation;
Alias alias;


// pass a hook whe creating the deployment group
LambdaDeploymentGroup deploymentGroup = LambdaDeploymentGroup.Builder.create(this, "BlueGreenDeployment")
        .alias(alias)
        .deploymentConfig(LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE)
        .preHook(warmUpUserCache)
        .build();

// or configure one on an existing deployment group
deploymentGroup.addPostHook(endToEndValidation);
csharp
Function warmUpUserCache;
Function endToEndValidation;
Alias alias;


// pass a hook whe creating the deployment group
var deploymentGroup = new LambdaDeploymentGroup(this, "BlueGreenDeployment", new LambdaDeploymentGroupProps {
    Alias = alias,
    DeploymentConfig = LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE,
    PreHook = warmUpUserCache
});

// or configure one on an existing deployment group
deploymentGroup.AddPostHook(endToEndValidation);
go
var warmUpUserCache Function
var endToEndValidation Function
var alias Alias


// pass a hook whe creating the deployment group
deploymentGroup := codedeploy.NewLambdaDeploymentGroup(this, jsii.String("BlueGreenDeployment"), &LambdaDeploymentGroupProps{
	Alias: alias,
	DeploymentConfig: codedeploy.LambdaDeploymentConfig_LINEAR_10PERCENT_EVERY_1MINUTE(),
	PreHook: warmUpUserCache,
})

// or configure one on an existing deployment group
deploymentGroup.AddPostHook(endToEndValidation)

Import an existing Lambda Deployment Group ​

To import an already existing Deployment Group:

ts
declare const application: codedeploy.LambdaApplication;
const deploymentGroup = codedeploy.LambdaDeploymentGroup.fromLambdaDeploymentGroupAttributes(this, 'ExistingCodeDeployDeploymentGroup', {
  application,
  deploymentGroupName: 'MyExistingDeploymentGroup',
});
python
# application: codedeploy.LambdaApplication

deployment_group = codedeploy.LambdaDeploymentGroup.from_lambda_deployment_group_attributes(self, "ExistingCodeDeployDeploymentGroup",
    application=application,
    deployment_group_name="MyExistingDeploymentGroup"
)
java
LambdaApplication application;

ILambdaDeploymentGroup deploymentGroup = LambdaDeploymentGroup.fromLambdaDeploymentGroupAttributes(this, "ExistingCodeDeployDeploymentGroup", LambdaDeploymentGroupAttributes.builder()
        .application(application)
        .deploymentGroupName("MyExistingDeploymentGroup")
        .build());
csharp
LambdaApplication application;

var deploymentGroup = LambdaDeploymentGroup.FromLambdaDeploymentGroupAttributes(this, "ExistingCodeDeployDeploymentGroup", new LambdaDeploymentGroupAttributes {
    Application = application,
    DeploymentGroupName = "MyExistingDeploymentGroup"
});
go
var application LambdaApplication

deploymentGroup := codedeploy.LambdaDeploymentGroup_FromLambdaDeploymentGroupAttributes(this, jsii.String("ExistingCodeDeployDeploymentGroup"), &LambdaDeploymentGroupAttributes{
	Application: Application,
	DeploymentGroupName: jsii.String("MyExistingDeploymentGroup"),
})

Lambda Deployment Configurations ​

CodeDeploy for Lambda comes with predefined configurations for traffic shifting. The predefined configurations are available as LambdaDeploymentConfig constants.

ts
const config = codedeploy.LambdaDeploymentConfig.CANARY_10PERCENT_30MINUTES;

declare const application: codedeploy.LambdaApplication;
declare const alias: lambda.Alias;
const deploymentGroup = new codedeploy.LambdaDeploymentGroup(this, 'BlueGreenDeployment', {
  application,
  alias,
  deploymentConfig: config,
});
python
# application: codedeploy.LambdaApplication
# alias: lambda.Alias
config = codedeploy.LambdaDeploymentConfig.CANARY_10PERCENT_30MINUTES
deployment_group = codedeploy.LambdaDeploymentGroup(self, "BlueGreenDeployment",
    application=application,
    alias=alias,
    deployment_config=config
)
java
LambdaApplication application;
Alias alias;
ILambdaDeploymentConfig config = LambdaDeploymentConfig.CANARY_10PERCENT_30MINUTES;
LambdaDeploymentGroup deploymentGroup = LambdaDeploymentGroup.Builder.create(this, "BlueGreenDeployment")
        .application(application)
        .alias(alias)
        .deploymentConfig(config)
        .build();
csharp
LambdaApplication application;
Alias alias;
var config = LambdaDeploymentConfig.CANARY_10PERCENT_30MINUTES;
var deploymentGroup = new LambdaDeploymentGroup(this, "BlueGreenDeployment", new LambdaDeploymentGroupProps {
    Application = application,
    Alias = alias,
    DeploymentConfig = config
});
go
var application LambdaApplication
var alias Alias
config := codedeploy.LambdaDeploymentConfig_CANARY_10PERCENT_30MINUTES()
deploymentGroup := codedeploy.NewLambdaDeploymentGroup(this, jsii.String("BlueGreenDeployment"), &LambdaDeploymentGroupProps{
	Application: Application,
	Alias: Alias,
	DeploymentConfig: config,
})

If you want to specify your own strategy, you can do so with the LambdaDeploymentConfig construct, letting you specify precisely how fast a new function version is deployed.

ts
const config = new codedeploy.LambdaDeploymentConfig(this, 'CustomConfig', {
  trafficRouting: new codedeploy.TimeBasedCanaryTrafficRouting({
    interval: Duration.minutes(15),
    percentage: 5,
  }),
});

declare const application: codedeploy.LambdaApplication;
declare const alias: lambda.Alias;
const deploymentGroup = new codedeploy.LambdaDeploymentGroup(this, 'BlueGreenDeployment', {
  application,
  alias,
  deploymentConfig: config,
});
python
# application: codedeploy.LambdaApplication
# alias: lambda.Alias
config = codedeploy.LambdaDeploymentConfig(self, "CustomConfig",
    traffic_routing=codedeploy.TimeBasedCanaryTrafficRouting(
        interval=Duration.minutes(15),
        percentage=5
    )
)
deployment_group = codedeploy.LambdaDeploymentGroup(self, "BlueGreenDeployment",
    application=application,
    alias=alias,
    deployment_config=config
)
java
LambdaApplication application;
Alias alias;
LambdaDeploymentConfig config = LambdaDeploymentConfig.Builder.create(this, "CustomConfig")
        .trafficRouting(TimeBasedCanaryTrafficRouting.Builder.create()
                .interval(Duration.minutes(15))
                .percentage(5)
                .build())
        .build();
LambdaDeploymentGroup deploymentGroup = LambdaDeploymentGroup.Builder.create(this, "BlueGreenDeployment")
        .application(application)
        .alias(alias)
        .deploymentConfig(config)
        .build();
csharp
LambdaApplication application;
Alias alias;
var config = new LambdaDeploymentConfig(this, "CustomConfig", new LambdaDeploymentConfigProps {
    TrafficRouting = new TimeBasedCanaryTrafficRouting(new TimeBasedCanaryTrafficRoutingProps {
        Interval = Duration.Minutes(15),
        Percentage = 5
    })
});
var deploymentGroup = new LambdaDeploymentGroup(this, "BlueGreenDeployment", new LambdaDeploymentGroupProps {
    Application = application,
    Alias = alias,
    DeploymentConfig = config
});
go
var application LambdaApplication
var alias Alias
config := codedeploy.NewLambdaDeploymentConfig(this, jsii.String("CustomConfig"), &LambdaDeploymentConfigProps{
	TrafficRouting: codedeploy.NewTimeBasedCanaryTrafficRouting(&TimeBasedCanaryTrafficRoutingProps{
		Interval: awscdk.Duration_Minutes(jsii.Number(15)),
		Percentage: jsii.Number(5),
	}),
})
deploymentGroup := codedeploy.NewLambdaDeploymentGroup(this, jsii.String("BlueGreenDeployment"), &LambdaDeploymentGroupProps{
	Application: Application,
	Alias: Alias,
	DeploymentConfig: config,
})

You can specify a custom name for your deployment config, but if you do you will not be able to update the interval/percentage through CDK.

ts
const config = new codedeploy.LambdaDeploymentConfig(this, 'CustomConfig', {
  trafficRouting: new codedeploy.TimeBasedCanaryTrafficRouting({
    interval: Duration.minutes(15),
    percentage: 5,
  }),
  deploymentConfigName: 'MyDeploymentConfig',
});
python
config = codedeploy.LambdaDeploymentConfig(self, "CustomConfig",
    traffic_routing=codedeploy.TimeBasedCanaryTrafficRouting(
        interval=Duration.minutes(15),
        percentage=5
    ),
    deployment_config_name="MyDeploymentConfig"
)
java
LambdaDeploymentConfig config = LambdaDeploymentConfig.Builder.create(this, "CustomConfig")
        .trafficRouting(TimeBasedCanaryTrafficRouting.Builder.create()
                .interval(Duration.minutes(15))
                .percentage(5)
                .build())
        .deploymentConfigName("MyDeploymentConfig")
        .build();
csharp
var config = new LambdaDeploymentConfig(this, "CustomConfig", new LambdaDeploymentConfigProps {
    TrafficRouting = new TimeBasedCanaryTrafficRouting(new TimeBasedCanaryTrafficRoutingProps {
        Interval = Duration.Minutes(15),
        Percentage = 5
    }),
    DeploymentConfigName = "MyDeploymentConfig"
});
go
config := codedeploy.NewLambdaDeploymentConfig(this, jsii.String("CustomConfig"), &LambdaDeploymentConfigProps{
	TrafficRouting: codedeploy.NewTimeBasedCanaryTrafficRouting(&TimeBasedCanaryTrafficRoutingProps{
		Interval: awscdk.Duration_Minutes(jsii.Number(15)),
		Percentage: jsii.Number(5),
	}),
	DeploymentConfigName: jsii.String("MyDeploymentConfig"),
})

To import an already existing Deployment Config:

ts
const deploymentConfig = codedeploy.LambdaDeploymentConfig.fromLambdaDeploymentConfigName(
  this,
  'ExistingDeploymentConfiguration',
  'MyExistingDeploymentConfiguration',
);
python
deployment_config = codedeploy.LambdaDeploymentConfig.from_lambda_deployment_config_name(self, "ExistingDeploymentConfiguration", "MyExistingDeploymentConfiguration")
java
ILambdaDeploymentConfig deploymentConfig = LambdaDeploymentConfig.fromLambdaDeploymentConfigName(this, "ExistingDeploymentConfiguration", "MyExistingDeploymentConfiguration");
csharp
var deploymentConfig = LambdaDeploymentConfig.FromLambdaDeploymentConfigName(this, "ExistingDeploymentConfiguration", "MyExistingDeploymentConfiguration");
go
deploymentConfig := codedeploy.LambdaDeploymentConfig_FromLambdaDeploymentConfigName(this, jsii.String("ExistingDeploymentConfiguration"), jsii.String("MyExistingDeploymentConfiguration"))

ECS Applications ​

To create a new CodeDeploy Application that deploys an ECS service:

ts
const application = new codedeploy.EcsApplication(this, 'CodeDeployApplication', {
  applicationName: 'MyApplication', // optional property
});
python
application = codedeploy.EcsApplication(self, "CodeDeployApplication",
    application_name="MyApplication"
)
java
EcsApplication application = EcsApplication.Builder.create(this, "CodeDeployApplication")
        .applicationName("MyApplication")
        .build();
csharp
var application = new EcsApplication(this, "CodeDeployApplication", new EcsApplicationProps {
    ApplicationName = "MyApplication"
});
go
application := codedeploy.NewEcsApplication(this, jsii.String("CodeDeployApplication"), &EcsApplicationProps{
	ApplicationName: jsii.String("MyApplication"),
})

To import an already existing Application:

ts
const application = codedeploy.EcsApplication.fromEcsApplicationName(
  this,
  'ExistingCodeDeployApplication',
  'MyExistingApplication',
);
python
application = codedeploy.EcsApplication.from_ecs_application_name(self, "ExistingCodeDeployApplication", "MyExistingApplication")
java
IEcsApplication application = EcsApplication.fromEcsApplicationName(this, "ExistingCodeDeployApplication", "MyExistingApplication");
csharp
var application = EcsApplication.FromEcsApplicationName(this, "ExistingCodeDeployApplication", "MyExistingApplication");
go
application := codedeploy.EcsApplication_FromEcsApplicationName(this, jsii.String("ExistingCodeDeployApplication"), jsii.String("MyExistingApplication"))

ECS Deployment Groups ​

CodeDeploy can be used to deploy to load-balanced ECS services. CodeDeploy performs ECS blue-green deployments by managing ECS task sets and load balancer target groups. During a blue-green deployment, one task set and target group runs the original version of your ECS task definition ('blue') and another task set and target group runs the new version of your ECS task definition ('green').

CodeDeploy orchestrates traffic shifting during ECS blue-green deployments by using a load balancer listener to balance incoming traffic between the 'blue' and 'green' task sets/target groups running two different versions of your ECS task definition. Before deployment, the load balancer listener sends 100% of requests to the 'blue' target group. When you publish a new version of the task definition and start a CodeDeploy deployment, CodeDeploy can send a small percentage of traffic to the new 'green' task set behind the 'green' target group, monitor, and validate before shifting 100% of traffic to the new version.

To create a new CodeDeploy Deployment Group that deploys to an ECS service:

ts
declare const myApplication: codedeploy.EcsApplication;
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.FargateTaskDefinition;
declare const blueTargetGroup: elbv2.ITargetGroup;
declare const greenTargetGroup: elbv2.ITargetGroup;
declare const listener: elbv2.IApplicationListener;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  deploymentController: {
    type: ecs.DeploymentControllerType.CODE_DEPLOY,
  },
});

new codedeploy.EcsDeploymentGroup(this, 'BlueGreenDG', {
  service,
  blueGreenDeploymentConfig: {
    blueTargetGroup,
    greenTargetGroup,
    listener,
  },
  deploymentConfig: codedeploy.EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES,
});
python
# my_application: codedeploy.EcsApplication
# cluster: ecs.Cluster
# task_definition: ecs.FargateTaskDefinition
# blue_target_group: elbv2.ITargetGroup
# green_target_group: elbv2.ITargetGroup
# listener: elbv2.IApplicationListener


service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    deployment_controller=ecs.DeploymentController(
        type=ecs.DeploymentControllerType.CODE_DEPLOY
    )
)

codedeploy.EcsDeploymentGroup(self, "BlueGreenDG",
    service=service,
    blue_green_deployment_config=codedeploy.EcsBlueGreenDeploymentConfig(
        blue_target_group=blue_target_group,
        green_target_group=green_target_group,
        listener=listener
    ),
    deployment_config=codedeploy.EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES
)
java
EcsApplication myApplication;
Cluster cluster;
FargateTaskDefinition taskDefinition;
ITargetGroup blueTargetGroup;
ITargetGroup greenTargetGroup;
IApplicationListener listener;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .deploymentController(DeploymentController.builder()
                .type(DeploymentControllerType.CODE_DEPLOY)
                .build())
        .build();

EcsDeploymentGroup.Builder.create(this, "BlueGreenDG")
        .service(service)
        .blueGreenDeploymentConfig(EcsBlueGreenDeploymentConfig.builder()
                .blueTargetGroup(blueTargetGroup)
                .greenTargetGroup(greenTargetGroup)
                .listener(listener)
                .build())
        .deploymentConfig(EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES)
        .build();
csharp
EcsApplication myApplication;
Cluster cluster;
FargateTaskDefinition taskDefinition;
ITargetGroup blueTargetGroup;
ITargetGroup greenTargetGroup;
IApplicationListener listener;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    DeploymentController = new DeploymentController {
        Type = DeploymentControllerType.CODE_DEPLOY
    }
});

new EcsDeploymentGroup(this, "BlueGreenDG", new EcsDeploymentGroupProps {
    Service = service,
    BlueGreenDeploymentConfig = new EcsBlueGreenDeploymentConfig {
        BlueTargetGroup = blueTargetGroup,
        GreenTargetGroup = greenTargetGroup,
        Listener = listener
    },
    DeploymentConfig = EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES
});
go
var myApplication EcsApplication
var cluster Cluster
var taskDefinition FargateTaskDefinition
var blueTargetGroup ITargetGroup
var greenTargetGroup ITargetGroup
var listener IApplicationListener


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	DeploymentController: &DeploymentController{
		Type: ecs.DeploymentControllerType_CODE_DEPLOY,
	},
})

codedeploy.NewEcsDeploymentGroup(this, jsii.String("BlueGreenDG"), &EcsDeploymentGroupProps{
	Service: Service,
	BlueGreenDeploymentConfig: &EcsBlueGreenDeploymentConfig{
		BlueTargetGroup: *BlueTargetGroup,
		GreenTargetGroup: *GreenTargetGroup,
		Listener: *Listener,
	},
	DeploymentConfig: codedeploy.EcsDeploymentConfig_CANARY_10PERCENT_5MINUTES(),
})

In order to deploy a new task definition version to the ECS service, deploy the changes directly through CodeDeploy using the CodeDeploy APIs or console. When the CODE_DEPLOY deployment controller is used, the ECS service cannot be deployed with a new task definition version through CloudFormation.

For more information on the behavior of CodeDeploy blue-green deployments for ECS, see What happens during an Amazon ECS deployment in the CodeDeploy user guide.

Note: If you wish to deploy updates to your ECS service through CDK and CloudFormation instead of directly through CodeDeploy, using the CfnCodeDeployBlueGreenHook construct is the recommended approach instead of using the EcsDeploymentGroup construct. For a comparison of ECS blue-green deployments through CodeDeploy (using EcsDeploymentGroup) and through CloudFormation (using CfnCodeDeployBlueGreenHook), see Create an Amazon ECS blue/green deployment through AWS CloudFormation in the CloudFormation user guide.

ECS Deployment Rollbacks and Alarms ​

CodeDeploy will automatically roll back if a deployment fails. You can optionally trigger an automatic rollback when one or more alarms are in a failed state during a deployment, or if the deployment stops.

In this example, CodeDeploy will monitor and roll back on alarms set for the number of unhealthy ECS tasks in each of the blue and green target groups, as well as alarms set for the number HTTP 5xx responses seen in each of the blue and green target groups.

ts
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';

declare const service: ecs.FargateService;
declare const blueTargetGroup: elbv2.ApplicationTargetGroup;
declare const greenTargetGroup: elbv2.ApplicationTargetGroup;
declare const listener: elbv2.IApplicationListener;

// Alarm on the number of unhealthy ECS tasks in each target group
const blueUnhealthyHosts = new cloudwatch.Alarm(this, 'BlueUnhealthyHosts', {
  alarmName: Stack.of(this).stackName + '-Unhealthy-Hosts-Blue',
  metric: blueTargetGroup.metricUnhealthyHostCount(),
  threshold: 1,
  evaluationPeriods: 2,
});

const greenUnhealthyHosts = new cloudwatch.Alarm(this, 'GreenUnhealthyHosts', {
  alarmName: Stack.of(this).stackName + '-Unhealthy-Hosts-Green',
  metric: greenTargetGroup.metricUnhealthyHostCount(),
  threshold: 1,
  evaluationPeriods: 2,
});

// Alarm on the number of HTTP 5xx responses returned by each target group
const blueApiFailure = new cloudwatch.Alarm(this, 'Blue5xx', {
  alarmName: Stack.of(this).stackName + '-Http-5xx-Blue',
  metric: blueTargetGroup.metricHttpCodeTarget(
    elbv2.HttpCodeTarget.TARGET_5XX_COUNT,
    { period: Duration.minutes(1) },
  ),
  threshold: 1,
  evaluationPeriods: 1,
});

const greenApiFailure = new cloudwatch.Alarm(this, 'Green5xx', {
  alarmName: Stack.of(this).stackName + '-Http-5xx-Green',
  metric: greenTargetGroup.metricHttpCodeTarget(
    elbv2.HttpCodeTarget.TARGET_5XX_COUNT,
    { period: Duration.minutes(1) },
  ),
  threshold: 1,
  evaluationPeriods: 1,
});

new codedeploy.EcsDeploymentGroup(this, 'BlueGreenDG', {
  // CodeDeploy will monitor these alarms during a deployment and automatically roll back
  alarms: [blueUnhealthyHosts, greenUnhealthyHosts, blueApiFailure, greenApiFailure],
  autoRollback: {
    // CodeDeploy will automatically roll back if a deployment is stopped
    stoppedDeployment: true,
  },
  service,
  blueGreenDeploymentConfig: {
    blueTargetGroup,
    greenTargetGroup,
    listener,
  },
  deploymentConfig: codedeploy.EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES,
});
python
import aws_cdk.aws_cloudwatch as cloudwatch

# service: ecs.FargateService
# blue_target_group: elbv2.ApplicationTargetGroup
# green_target_group: elbv2.ApplicationTargetGroup
# listener: elbv2.IApplicationListener


# Alarm on the number of unhealthy ECS tasks in each target group
blue_unhealthy_hosts = cloudwatch.Alarm(self, "BlueUnhealthyHosts",
    alarm_name=Stack.of(self).stack_name + "-Unhealthy-Hosts-Blue",
    metric=blue_target_group.metric_unhealthy_host_count(),
    threshold=1,
    evaluation_periods=2
)

green_unhealthy_hosts = cloudwatch.Alarm(self, "GreenUnhealthyHosts",
    alarm_name=Stack.of(self).stack_name + "-Unhealthy-Hosts-Green",
    metric=green_target_group.metric_unhealthy_host_count(),
    threshold=1,
    evaluation_periods=2
)

# Alarm on the number of HTTP 5xx responses returned by each target group
blue_api_failure = cloudwatch.Alarm(self, "Blue5xx",
    alarm_name=Stack.of(self).stack_name + "-Http-5xx-Blue",
    metric=blue_target_group.metric_http_code_target(elbv2.HttpCodeTarget.TARGET_5XX_COUNT, period=Duration.minutes(1)),
    threshold=1,
    evaluation_periods=1
)

green_api_failure = cloudwatch.Alarm(self, "Green5xx",
    alarm_name=Stack.of(self).stack_name + "-Http-5xx-Green",
    metric=green_target_group.metric_http_code_target(elbv2.HttpCodeTarget.TARGET_5XX_COUNT, period=Duration.minutes(1)),
    threshold=1,
    evaluation_periods=1
)

codedeploy.EcsDeploymentGroup(self, "BlueGreenDG",
    # CodeDeploy will monitor these alarms during a deployment and automatically roll back
    alarms=[blue_unhealthy_hosts, green_unhealthy_hosts, blue_api_failure, green_api_failure],
    auto_rollback=codedeploy.AutoRollbackConfig(
        # CodeDeploy will automatically roll back if a deployment is stopped
        stopped_deployment=True
    ),
    service=service,
    blue_green_deployment_config=codedeploy.EcsBlueGreenDeploymentConfig(
        blue_target_group=blue_target_group,
        green_target_group=green_target_group,
        listener=listener
    ),
    deployment_config=codedeploy.EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES
)
java
import software.amazon.awscdk.services.cloudwatch.*;

FargateService service;
ApplicationTargetGroup blueTargetGroup;
ApplicationTargetGroup greenTargetGroup;
IApplicationListener listener;


// Alarm on the number of unhealthy ECS tasks in each target group
Alarm blueUnhealthyHosts = Alarm.Builder.create(this, "BlueUnhealthyHosts")
        .alarmName(Stack.of(this).getStackName() + "-Unhealthy-Hosts-Blue")
        .metric(blueTargetGroup.metricUnhealthyHostCount())
        .threshold(1)
        .evaluationPeriods(2)
        .build();

Alarm greenUnhealthyHosts = Alarm.Builder.create(this, "GreenUnhealthyHosts")
        .alarmName(Stack.of(this).getStackName() + "-Unhealthy-Hosts-Green")
        .metric(greenTargetGroup.metricUnhealthyHostCount())
        .threshold(1)
        .evaluationPeriods(2)
        .build();

// Alarm on the number of HTTP 5xx responses returned by each target group
Alarm blueApiFailure = Alarm.Builder.create(this, "Blue5xx")
        .alarmName(Stack.of(this).getStackName() + "-Http-5xx-Blue")
        .metric(blueTargetGroup.metricHttpCodeTarget(HttpCodeTarget.TARGET_5XX_COUNT, MetricOptions.builder().period(Duration.minutes(1)).build()))
        .threshold(1)
        .evaluationPeriods(1)
        .build();

Alarm greenApiFailure = Alarm.Builder.create(this, "Green5xx")
        .alarmName(Stack.of(this).getStackName() + "-Http-5xx-Green")
        .metric(greenTargetGroup.metricHttpCodeTarget(HttpCodeTarget.TARGET_5XX_COUNT, MetricOptions.builder().period(Duration.minutes(1)).build()))
        .threshold(1)
        .evaluationPeriods(1)
        .build();

EcsDeploymentGroup.Builder.create(this, "BlueGreenDG")
        // CodeDeploy will monitor these alarms during a deployment and automatically roll back
        .alarms(List.of(blueUnhealthyHosts, greenUnhealthyHosts, blueApiFailure, greenApiFailure))
        .autoRollback(AutoRollbackConfig.builder()
                // CodeDeploy will automatically roll back if a deployment is stopped
                .stoppedDeployment(true)
                .build())
        .service(service)
        .blueGreenDeploymentConfig(EcsBlueGreenDeploymentConfig.builder()
                .blueTargetGroup(blueTargetGroup)
                .greenTargetGroup(greenTargetGroup)
                .listener(listener)
                .build())
        .deploymentConfig(EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES)
        .build();
csharp
using Amazon.CDK.AWS.CloudWatch;

FargateService service;
ApplicationTargetGroup blueTargetGroup;
ApplicationTargetGroup greenTargetGroup;
IApplicationListener listener;


// Alarm on the number of unhealthy ECS tasks in each target group
var blueUnhealthyHosts = new Alarm(this, "BlueUnhealthyHosts", new AlarmProps {
    AlarmName = Stack.Of(this).StackName + "-Unhealthy-Hosts-Blue",
    Metric = blueTargetGroup.MetricUnhealthyHostCount(),
    Threshold = 1,
    EvaluationPeriods = 2
});

var greenUnhealthyHosts = new Alarm(this, "GreenUnhealthyHosts", new AlarmProps {
    AlarmName = Stack.Of(this).StackName + "-Unhealthy-Hosts-Green",
    Metric = greenTargetGroup.MetricUnhealthyHostCount(),
    Threshold = 1,
    EvaluationPeriods = 2
});

// Alarm on the number of HTTP 5xx responses returned by each target group
var blueApiFailure = new Alarm(this, "Blue5xx", new AlarmProps {
    AlarmName = Stack.Of(this).StackName + "-Http-5xx-Blue",
    Metric = blueTargetGroup.MetricHttpCodeTarget(HttpCodeTarget.TARGET_5XX_COUNT, new MetricOptions { Period = Duration.Minutes(1) }),
    Threshold = 1,
    EvaluationPeriods = 1
});

var greenApiFailure = new Alarm(this, "Green5xx", new AlarmProps {
    AlarmName = Stack.Of(this).StackName + "-Http-5xx-Green",
    Metric = greenTargetGroup.MetricHttpCodeTarget(HttpCodeTarget.TARGET_5XX_COUNT, new MetricOptions { Period = Duration.Minutes(1) }),
    Threshold = 1,
    EvaluationPeriods = 1
});

new EcsDeploymentGroup(this, "BlueGreenDG", new EcsDeploymentGroupProps {
    // CodeDeploy will monitor these alarms during a deployment and automatically roll back
    Alarms = new [] { blueUnhealthyHosts, greenUnhealthyHosts, blueApiFailure, greenApiFailure },
    AutoRollback = new AutoRollbackConfig {
        // CodeDeploy will automatically roll back if a deployment is stopped
        StoppedDeployment = true
    },
    Service = service,
    BlueGreenDeploymentConfig = new EcsBlueGreenDeploymentConfig {
        BlueTargetGroup = blueTargetGroup,
        GreenTargetGroup = greenTargetGroup,
        Listener = listener
    },
    DeploymentConfig = EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var service FargateService
var blueTargetGroup ApplicationTargetGroup
var greenTargetGroup ApplicationTargetGroup
var listener IApplicationListener


// Alarm on the number of unhealthy ECS tasks in each target group
blueUnhealthyHosts := cloudwatch.NewAlarm(this, jsii.String("BlueUnhealthyHosts"), &AlarmProps{
	AlarmName: jsii.String(awscdk.stack_Of(this).stackName + "-Unhealthy-Hosts-Blue"),
	Metric: blueTargetGroup.MetricUnhealthyHostCount(),
	Threshold: jsii.Number(1),
	EvaluationPeriods: jsii.Number(2),
})

greenUnhealthyHosts := cloudwatch.NewAlarm(this, jsii.String("GreenUnhealthyHosts"), &AlarmProps{
	AlarmName: jsii.String(awscdk.stack_Of(this).stackName + "-Unhealthy-Hosts-Green"),
	Metric: greenTargetGroup.*MetricUnhealthyHostCount(),
	Threshold: jsii.Number(1),
	EvaluationPeriods: jsii.Number(2),
})

// Alarm on the number of HTTP 5xx responses returned by each target group
blueApiFailure := cloudwatch.NewAlarm(this, jsii.String("Blue5xx"), &AlarmProps{
	AlarmName: jsii.String(awscdk.stack_Of(this).stackName + "-Http-5xx-Blue"),
	Metric: blueTargetGroup.MetricHttpCodeTarget(elbv2.HttpCodeTarget_TARGET_5XX_COUNT, &MetricOptions{
		Period: awscdk.Duration_Minutes(jsii.Number(1)),
	}),
	Threshold: jsii.Number(1),
	EvaluationPeriods: jsii.Number(1),
})

greenApiFailure := cloudwatch.NewAlarm(this, jsii.String("Green5xx"), &AlarmProps{
	AlarmName: jsii.String(awscdk.stack_Of(this).stackName + "-Http-5xx-Green"),
	Metric: greenTargetGroup.*MetricHttpCodeTarget(elbv2.HttpCodeTarget_TARGET_5XX_COUNT, &MetricOptions{
		Period: awscdk.Duration_*Minutes(jsii.Number(1)),
	}),
	Threshold: jsii.Number(1),
	EvaluationPeriods: jsii.Number(1),
})

codedeploy.NewEcsDeploymentGroup(this, jsii.String("BlueGreenDG"), &EcsDeploymentGroupProps{
	// CodeDeploy will monitor these alarms during a deployment and automatically roll back
	Alarms: []IAlarmRef{
		blueUnhealthyHosts,
		greenUnhealthyHosts,
		blueApiFailure,
		greenApiFailure,
	},
	AutoRollback: &AutoRollbackConfig{
		// CodeDeploy will automatically roll back if a deployment is stopped
		StoppedDeployment: jsii.Boolean(true),
	},
	Service: Service,
	BlueGreenDeploymentConfig: &EcsBlueGreenDeploymentConfig{
		BlueTargetGroup: *BlueTargetGroup,
		GreenTargetGroup: *GreenTargetGroup,
		Listener: *Listener,
	},
	DeploymentConfig: codedeploy.EcsDeploymentConfig_CANARY_10PERCENT_5MINUTES(),
})

Deployment validation and manual deployment approval ​

CodeDeploy blue-green deployments provide an opportunity to validate the new task definition version running on the 'green' ECS task set prior to shifting any production traffic to the new version. A second 'test' listener serving traffic on a different port be added to the load balancer. For example, the test listener can serve test traffic on port 9001 while the main listener serves production traffic on port 443. During a blue-green deployment, CodeDeploy can then shift 100% of test traffic over to the 'green' task set/target group prior to shifting any production traffic during the deployment.

ts
declare const myApplication: codedeploy.EcsApplication;
declare const service: ecs.FargateService;
declare const blueTargetGroup: elbv2.ITargetGroup;
declare const greenTargetGroup: elbv2.ITargetGroup;
declare const listener: elbv2.IApplicationListener;
declare const testListener: elbv2.IApplicationListener;

new codedeploy.EcsDeploymentGroup(this, 'BlueGreenDG', {
  service,
  blueGreenDeploymentConfig: {
    blueTargetGroup,
    greenTargetGroup,
    listener,
    testListener,
  },
  deploymentConfig: codedeploy.EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES,
});
python
# my_application: codedeploy.EcsApplication
# service: ecs.FargateService
# blue_target_group: elbv2.ITargetGroup
# green_target_group: elbv2.ITargetGroup
# listener: elbv2.IApplicationListener
# test_listener: elbv2.IApplicationListener


codedeploy.EcsDeploymentGroup(self, "BlueGreenDG",
    service=service,
    blue_green_deployment_config=codedeploy.EcsBlueGreenDeploymentConfig(
        blue_target_group=blue_target_group,
        green_target_group=green_target_group,
        listener=listener,
        test_listener=test_listener
    ),
    deployment_config=codedeploy.EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES
)
java
EcsApplication myApplication;
FargateService service;
ITargetGroup blueTargetGroup;
ITargetGroup greenTargetGroup;
IApplicationListener listener;
IApplicationListener testListener;


EcsDeploymentGroup.Builder.create(this, "BlueGreenDG")
        .service(service)
        .blueGreenDeploymentConfig(EcsBlueGreenDeploymentConfig.builder()
                .blueTargetGroup(blueTargetGroup)
                .greenTargetGroup(greenTargetGroup)
                .listener(listener)
                .testListener(testListener)
                .build())
        .deploymentConfig(EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES)
        .build();
csharp
EcsApplication myApplication;
FargateService service;
ITargetGroup blueTargetGroup;
ITargetGroup greenTargetGroup;
IApplicationListener listener;
IApplicationListener testListener;


new EcsDeploymentGroup(this, "BlueGreenDG", new EcsDeploymentGroupProps {
    Service = service,
    BlueGreenDeploymentConfig = new EcsBlueGreenDeploymentConfig {
        BlueTargetGroup = blueTargetGroup,
        GreenTargetGroup = greenTargetGroup,
        Listener = listener,
        TestListener = testListener
    },
    DeploymentConfig = EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES
});
go
var myApplication EcsApplication
var service FargateService
var blueTargetGroup ITargetGroup
var greenTargetGroup ITargetGroup
var listener IApplicationListener
var testListener IApplicationListener


codedeploy.NewEcsDeploymentGroup(this, jsii.String("BlueGreenDG"), &EcsDeploymentGroupProps{
	Service: Service,
	BlueGreenDeploymentConfig: &EcsBlueGreenDeploymentConfig{
		BlueTargetGroup: *BlueTargetGroup,
		GreenTargetGroup: *GreenTargetGroup,
		Listener: *Listener,
		TestListener: *TestListener,
	},
	DeploymentConfig: codedeploy.EcsDeploymentConfig_CANARY_10PERCENT_5MINUTES(),
})

Automated validation steps can run during the CodeDeploy deployment after shifting test traffic and before shifting production traffic. CodeDeploy supports registering Lambda functions as lifecycle hooks for an ECS deployment. These Lambda functions can run automated validation steps against the test traffic port, for example in response to the AfterAllowTestTraffic lifecycle hook. For more information about how to specify the Lambda functions to run for each CodeDeploy lifecycle hook in an ECS deployment, see the AppSpec 'hooks' for an Amazon ECS deployment section in the CodeDeploy user guide.

After provisioning the 'green' ECS task set and re-routing test traffic during a blue-green deployment, CodeDeploy can wait for approval before continuing the deployment and re-routing production traffic. During this approval wait time, you can complete additional validation steps prior to exposing the new 'green' task set to production traffic, such as manual testing through the test listener port or running automated integration test suites.

To approve the deployment, validation steps use the CodeDeploy [ContinueDeployment API(https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ContinueDeployment.html). If the ContinueDeployment API is not called within the approval wait time period, CodeDeploy will stop the deployment and can automatically roll back the deployment.

ts
declare const service: ecs.FargateService;
declare const blueTargetGroup: elbv2.ITargetGroup;
declare const greenTargetGroup: elbv2.ITargetGroup;
declare const listener: elbv2.IApplicationListener;
declare const testListener: elbv2.IApplicationListener;

new codedeploy.EcsDeploymentGroup(this, 'BlueGreenDG', {
  autoRollback: {
    // CodeDeploy will automatically roll back if the 8-hour approval period times out and the deployment stops
    stoppedDeployment: true,
  },
  service,
  blueGreenDeploymentConfig: {
    // The deployment will wait for approval for up to 8 hours before stopping the deployment
    deploymentApprovalWaitTime: Duration.hours(8),
    blueTargetGroup,
    greenTargetGroup,
    listener,
    testListener,
  },
  deploymentConfig: codedeploy.EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES,
});
python
# service: ecs.FargateService
# blue_target_group: elbv2.ITargetGroup
# green_target_group: elbv2.ITargetGroup
# listener: elbv2.IApplicationListener
# test_listener: elbv2.IApplicationListener


codedeploy.EcsDeploymentGroup(self, "BlueGreenDG",
    auto_rollback=codedeploy.AutoRollbackConfig(
        # CodeDeploy will automatically roll back if the 8-hour approval period times out and the deployment stops
        stopped_deployment=True
    ),
    service=service,
    blue_green_deployment_config=codedeploy.EcsBlueGreenDeploymentConfig(
        # The deployment will wait for approval for up to 8 hours before stopping the deployment
        deployment_approval_wait_time=Duration.hours(8),
        blue_target_group=blue_target_group,
        green_target_group=green_target_group,
        listener=listener,
        test_listener=test_listener
    ),
    deployment_config=codedeploy.EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES
)
java
FargateService service;
ITargetGroup blueTargetGroup;
ITargetGroup greenTargetGroup;
IApplicationListener listener;
IApplicationListener testListener;


EcsDeploymentGroup.Builder.create(this, "BlueGreenDG")
        .autoRollback(AutoRollbackConfig.builder()
                // CodeDeploy will automatically roll back if the 8-hour approval period times out and the deployment stops
                .stoppedDeployment(true)
                .build())
        .service(service)
        .blueGreenDeploymentConfig(EcsBlueGreenDeploymentConfig.builder()
                // The deployment will wait for approval for up to 8 hours before stopping the deployment
                .deploymentApprovalWaitTime(Duration.hours(8))
                .blueTargetGroup(blueTargetGroup)
                .greenTargetGroup(greenTargetGroup)
                .listener(listener)
                .testListener(testListener)
                .build())
        .deploymentConfig(EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES)
        .build();
csharp
FargateService service;
ITargetGroup blueTargetGroup;
ITargetGroup greenTargetGroup;
IApplicationListener listener;
IApplicationListener testListener;


new EcsDeploymentGroup(this, "BlueGreenDG", new EcsDeploymentGroupProps {
    AutoRollback = new AutoRollbackConfig {
        // CodeDeploy will automatically roll back if the 8-hour approval period times out and the deployment stops
        StoppedDeployment = true
    },
    Service = service,
    BlueGreenDeploymentConfig = new EcsBlueGreenDeploymentConfig {
        // The deployment will wait for approval for up to 8 hours before stopping the deployment
        DeploymentApprovalWaitTime = Duration.Hours(8),
        BlueTargetGroup = blueTargetGroup,
        GreenTargetGroup = greenTargetGroup,
        Listener = listener,
        TestListener = testListener
    },
    DeploymentConfig = EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES
});
go
var service FargateService
var blueTargetGroup ITargetGroup
var greenTargetGroup ITargetGroup
var listener IApplicationListener
var testListener IApplicationListener


codedeploy.NewEcsDeploymentGroup(this, jsii.String("BlueGreenDG"), &EcsDeploymentGroupProps{
	AutoRollback: &AutoRollbackConfig{
		// CodeDeploy will automatically roll back if the 8-hour approval period times out and the deployment stops
		StoppedDeployment: jsii.Boolean(true),
	},
	Service: Service,
	BlueGreenDeploymentConfig: &EcsBlueGreenDeploymentConfig{
		// The deployment will wait for approval for up to 8 hours before stopping the deployment
		DeploymentApprovalWaitTime: awscdk.Duration_Hours(jsii.Number(8)),
		BlueTargetGroup: *BlueTargetGroup,
		GreenTargetGroup: *GreenTargetGroup,
		Listener: *Listener,
		TestListener: *TestListener,
	},
	DeploymentConfig: codedeploy.EcsDeploymentConfig_CANARY_10PERCENT_5MINUTES(),
})

Deployment bake time ​

You can specify how long CodeDeploy waits before it terminates the original 'blue' ECS task set when a blue-green deployment is complete in order to let the deployment "bake" a while. During this bake time, CodeDeploy will continue to monitor any CloudWatch alarms specified for the deployment group and will automatically roll back if those alarms go into a failed state.

ts
import { aws_cloudwatch as cloudwatch } from 'aws-cdk-lib';

declare const service: ecs.FargateService;
declare const blueTargetGroup: elbv2.ITargetGroup;
declare const greenTargetGroup: elbv2.ITargetGroup;
declare const listener: elbv2.IApplicationListener;
declare const blueUnhealthyHosts: cloudwatch.Alarm;
declare const greenUnhealthyHosts: cloudwatch.Alarm;
declare const blueApiFailure: cloudwatch.Alarm;
declare const greenApiFailure: cloudwatch.Alarm;

new codedeploy.EcsDeploymentGroup(this, 'BlueGreenDG', {
  service,
  blueGreenDeploymentConfig: {
    blueTargetGroup,
    greenTargetGroup,
    listener,
    // CodeDeploy will wait for 30 minutes after completing the blue-green deployment before it terminates the blue tasks
    terminationWaitTime: Duration.minutes(30),
  },
  // CodeDeploy will continue to monitor these alarms during the 30-minute bake time and will automatically
  // roll back if they go into a failed state at any point during the deployment.
  alarms: [blueUnhealthyHosts, greenUnhealthyHosts, blueApiFailure, greenApiFailure],
  deploymentConfig: codedeploy.EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES,
});
python
from aws_cdk import aws_cloudwatch as cloudwatch

# service: ecs.FargateService
# blue_target_group: elbv2.ITargetGroup
# green_target_group: elbv2.ITargetGroup
# listener: elbv2.IApplicationListener
# blue_unhealthy_hosts: cloudwatch.Alarm
# green_unhealthy_hosts: cloudwatch.Alarm
# blue_api_failure: cloudwatch.Alarm
# green_api_failure: cloudwatch.Alarm


codedeploy.EcsDeploymentGroup(self, "BlueGreenDG",
    service=service,
    blue_green_deployment_config=codedeploy.EcsBlueGreenDeploymentConfig(
        blue_target_group=blue_target_group,
        green_target_group=green_target_group,
        listener=listener,
        # CodeDeploy will wait for 30 minutes after completing the blue-green deployment before it terminates the blue tasks
        termination_wait_time=Duration.minutes(30)
    ),
    # CodeDeploy will continue to monitor these alarms during the 30-minute bake time and will automatically
    # roll back if they go into a failed state at any point during the deployment.
    alarms=[blue_unhealthy_hosts, green_unhealthy_hosts, blue_api_failure, green_api_failure],
    deployment_config=codedeploy.EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES
)
java
import software.amazon.awscdk.services.cloudwatch.*;

FargateService service;
ITargetGroup blueTargetGroup;
ITargetGroup greenTargetGroup;
IApplicationListener listener;
Alarm blueUnhealthyHosts;
Alarm greenUnhealthyHosts;
Alarm blueApiFailure;
Alarm greenApiFailure;


EcsDeploymentGroup.Builder.create(this, "BlueGreenDG")
        .service(service)
        .blueGreenDeploymentConfig(EcsBlueGreenDeploymentConfig.builder()
                .blueTargetGroup(blueTargetGroup)
                .greenTargetGroup(greenTargetGroup)
                .listener(listener)
                // CodeDeploy will wait for 30 minutes after completing the blue-green deployment before it terminates the blue tasks
                .terminationWaitTime(Duration.minutes(30))
                .build())
        // CodeDeploy will continue to monitor these alarms during the 30-minute bake time and will automatically
        // roll back if they go into a failed state at any point during the deployment.
        .alarms(List.of(blueUnhealthyHosts, greenUnhealthyHosts, blueApiFailure, greenApiFailure))
        .deploymentConfig(EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES)
        .build();
csharp
using Amazon.CDK.AWS.CloudWatch;

FargateService service;
ITargetGroup blueTargetGroup;
ITargetGroup greenTargetGroup;
IApplicationListener listener;
Alarm blueUnhealthyHosts;
Alarm greenUnhealthyHosts;
Alarm blueApiFailure;
Alarm greenApiFailure;


new EcsDeploymentGroup(this, "BlueGreenDG", new EcsDeploymentGroupProps {
    Service = service,
    BlueGreenDeploymentConfig = new EcsBlueGreenDeploymentConfig {
        BlueTargetGroup = blueTargetGroup,
        GreenTargetGroup = greenTargetGroup,
        Listener = listener,
        // CodeDeploy will wait for 30 minutes after completing the blue-green deployment before it terminates the blue tasks
        TerminationWaitTime = Duration.Minutes(30)
    },
    // CodeDeploy will continue to monitor these alarms during the 30-minute bake time and will automatically
    // roll back if they go into a failed state at any point during the deployment.
    Alarms = new [] { blueUnhealthyHosts, greenUnhealthyHosts, blueApiFailure, greenApiFailure },
    DeploymentConfig = EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var service FargateService
var blueTargetGroup ITargetGroup
var greenTargetGroup ITargetGroup
var listener IApplicationListener
var blueUnhealthyHosts Alarm
var greenUnhealthyHosts Alarm
var blueApiFailure Alarm
var greenApiFailure Alarm


codedeploy.NewEcsDeploymentGroup(this, jsii.String("BlueGreenDG"), &EcsDeploymentGroupProps{
	Service: Service,
	BlueGreenDeploymentConfig: &EcsBlueGreenDeploymentConfig{
		BlueTargetGroup: *BlueTargetGroup,
		GreenTargetGroup: *GreenTargetGroup,
		Listener: *Listener,
		// CodeDeploy will wait for 30 minutes after completing the blue-green deployment before it terminates the blue tasks
		TerminationWaitTime: awscdk.Duration_Minutes(jsii.Number(30)),
	},
	// CodeDeploy will continue to monitor these alarms during the 30-minute bake time and will automatically
	// roll back if they go into a failed state at any point during the deployment.
	Alarms: []IAlarmRef{
		blueUnhealthyHosts,
		greenUnhealthyHosts,
		blueApiFailure,
		greenApiFailure,
	},
	DeploymentConfig: codedeploy.EcsDeploymentConfig_CANARY_10PERCENT_5MINUTES(),
})

Import an existing ECS Deployment Group ​

To import an already existing Deployment Group:

ts
declare const application: codedeploy.EcsApplication;
const deploymentGroup = codedeploy.EcsDeploymentGroup.fromEcsDeploymentGroupAttributes(this, 'ExistingCodeDeployDeploymentGroup', {
  application,
  deploymentGroupName: 'MyExistingDeploymentGroup',
});
python
# application: codedeploy.EcsApplication

deployment_group = codedeploy.EcsDeploymentGroup.from_ecs_deployment_group_attributes(self, "ExistingCodeDeployDeploymentGroup",
    application=application,
    deployment_group_name="MyExistingDeploymentGroup"
)
java
EcsApplication application;

IEcsDeploymentGroup deploymentGroup = EcsDeploymentGroup.fromEcsDeploymentGroupAttributes(this, "ExistingCodeDeployDeploymentGroup", EcsDeploymentGroupAttributes.builder()
        .application(application)
        .deploymentGroupName("MyExistingDeploymentGroup")
        .build());
csharp
EcsApplication application;

var deploymentGroup = EcsDeploymentGroup.FromEcsDeploymentGroupAttributes(this, "ExistingCodeDeployDeploymentGroup", new EcsDeploymentGroupAttributes {
    Application = application,
    DeploymentGroupName = "MyExistingDeploymentGroup"
});
go
var application EcsApplication

deploymentGroup := codedeploy.EcsDeploymentGroup_FromEcsDeploymentGroupAttributes(this, jsii.String("ExistingCodeDeployDeploymentGroup"), &EcsDeploymentGroupAttributes{
	Application: Application,
	DeploymentGroupName: jsii.String("MyExistingDeploymentGroup"),
})

ECS Deployment Configurations ​

CodeDeploy for ECS comes with predefined configurations for traffic shifting. The predefined configurations are available as LambdaDeploymentConfig constants.

ts
const config = codedeploy.EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES;
python
config = codedeploy.EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES
java
IEcsDeploymentConfig config = EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES;
csharp
var config = EcsDeploymentConfig.CANARY_10PERCENT_5MINUTES;
go
config := codedeploy.EcsDeploymentConfig_CANARY_10PERCENT_5MINUTES()

If you want to specify your own strategy, you can do so with the EcsDeploymentConfig construct, letting you specify precisely how fast an ECS service is deployed.

ts
new codedeploy.EcsDeploymentConfig(this, 'CustomConfig', {
  trafficRouting: new codedeploy.TimeBasedCanaryTrafficRouting({
    interval: Duration.minutes(15),
    percentage: 5,
  }),
});
python
codedeploy.EcsDeploymentConfig(self, "CustomConfig",
    traffic_routing=codedeploy.TimeBasedCanaryTrafficRouting(
        interval=Duration.minutes(15),
        percentage=5
    )
)
java
EcsDeploymentConfig.Builder.create(this, "CustomConfig")
        .trafficRouting(TimeBasedCanaryTrafficRouting.Builder.create()
                .interval(Duration.minutes(15))
                .percentage(5)
                .build())
        .build();
csharp
new EcsDeploymentConfig(this, "CustomConfig", new EcsDeploymentConfigProps {
    TrafficRouting = new TimeBasedCanaryTrafficRouting(new TimeBasedCanaryTrafficRoutingProps {
        Interval = Duration.Minutes(15),
        Percentage = 5
    })
});
go
codedeploy.NewEcsDeploymentConfig(this, jsii.String("CustomConfig"), &EcsDeploymentConfigProps{
	TrafficRouting: codedeploy.NewTimeBasedCanaryTrafficRouting(&TimeBasedCanaryTrafficRoutingProps{
		Interval: awscdk.Duration_Minutes(jsii.Number(15)),
		Percentage: jsii.Number(5),
	}),
})

You can specify a custom name for your deployment config, but if you do you will not be able to update the interval/percentage through CDK.

ts
const config = new codedeploy.EcsDeploymentConfig(this, 'CustomConfig', {
  trafficRouting: new codedeploy.TimeBasedCanaryTrafficRouting({
    interval: Duration.minutes(15),
    percentage: 5,
  }),
  deploymentConfigName: 'MyDeploymentConfig',
});
python
config = codedeploy.EcsDeploymentConfig(self, "CustomConfig",
    traffic_routing=codedeploy.TimeBasedCanaryTrafficRouting(
        interval=Duration.minutes(15),
        percentage=5
    ),
    deployment_config_name="MyDeploymentConfig"
)
java
EcsDeploymentConfig config = EcsDeploymentConfig.Builder.create(this, "CustomConfig")
        .trafficRouting(TimeBasedCanaryTrafficRouting.Builder.create()
                .interval(Duration.minutes(15))
                .percentage(5)
                .build())
        .deploymentConfigName("MyDeploymentConfig")
        .build();
csharp
var config = new EcsDeploymentConfig(this, "CustomConfig", new EcsDeploymentConfigProps {
    TrafficRouting = new TimeBasedCanaryTrafficRouting(new TimeBasedCanaryTrafficRoutingProps {
        Interval = Duration.Minutes(15),
        Percentage = 5
    }),
    DeploymentConfigName = "MyDeploymentConfig"
});
go
config := codedeploy.NewEcsDeploymentConfig(this, jsii.String("CustomConfig"), &EcsDeploymentConfigProps{
	TrafficRouting: codedeploy.NewTimeBasedCanaryTrafficRouting(&TimeBasedCanaryTrafficRoutingProps{
		Interval: awscdk.Duration_Minutes(jsii.Number(15)),
		Percentage: jsii.Number(5),
	}),
	DeploymentConfigName: jsii.String("MyDeploymentConfig"),
})

Or import an existing one:

ts
const deploymentConfig = codedeploy.EcsDeploymentConfig.fromEcsDeploymentConfigName(
  this,
  'ExistingDeploymentConfiguration',
  'MyExistingDeploymentConfiguration',
);
python
deployment_config = codedeploy.EcsDeploymentConfig.from_ecs_deployment_config_name(self, "ExistingDeploymentConfiguration", "MyExistingDeploymentConfiguration")
java
IEcsDeploymentConfig deploymentConfig = EcsDeploymentConfig.fromEcsDeploymentConfigName(this, "ExistingDeploymentConfiguration", "MyExistingDeploymentConfiguration");
csharp
var deploymentConfig = EcsDeploymentConfig.FromEcsDeploymentConfigName(this, "ExistingDeploymentConfiguration", "MyExistingDeploymentConfiguration");
go
deploymentConfig := codedeploy.EcsDeploymentConfig_FromEcsDeploymentConfigName(this, jsii.String("ExistingDeploymentConfiguration"), jsii.String("MyExistingDeploymentConfiguration"))

ECS Deployments ​

cdk-constructs: Experimental

An experimental construct is available on the Construct Hub called @cdklabs/cdk-ecs-codedeploy that manages ECS CodeDeploy deployments.

ts
declare const deploymentGroup: codedeploy.IEcsDeploymentGroup;
declare const taskDefinition: ecs.ITaskDefinition;

new EcsDeployment({
  deploymentGroup,
  targetService: {
    taskDefinition,
    containerName: 'mycontainer',
    containerPort: 80,
  },
});
python
# deployment_group: codedeploy.IEcsDeploymentGroup
# task_definition: ecs.ITaskDefinition


EcsDeployment({
    "deployment_group": deployment_group,
    "target_service": {
        "task_definition": task_definition,
        "container_name": "mycontainer",
        "container_port": 80
    }
})
java
IEcsDeploymentGroup deploymentGroup;
ITaskDefinition taskDefinition;


new EcsDeployment(Map.of(
        "deploymentGroup", deploymentGroup,
        "targetService", Map.of(
                "taskDefinition", taskDefinition,
                "containerName", "mycontainer",
                "containerPort", 80)));
csharp
IEcsDeploymentGroup deploymentGroup;
ITaskDefinition taskDefinition;


new EcsDeployment(new Dictionary<string, object> {
    { "deploymentGroup", deploymentGroup },
    { "targetService", new Struct {
        TaskDefinition = taskDefinition,
        ContainerName = "mycontainer",
        ContainerPort = 80
    } }
});
go
var deploymentGroup IEcsDeploymentGroup
var taskDefinition ITaskDefinition


NewEcsDeployment(map[string]interface{}{
	"deploymentGroup": deploymentGroup,
	"targetService": map[string]interface{}{
		"taskDefinition": taskDefinition,
		"containerName": jsii.String("mycontainer"),
		"containerPort": jsii.Number(80),
	},
})

The deployment will use the AutoRollbackConfig for the EcsDeploymentGroup unless it is overridden in the deployment:

ts
declare const deploymentGroup: codedeploy.IEcsDeploymentGroup;
declare const taskDefinition: ecs.ITaskDefinition;

new EcsDeployment({
  deploymentGroup,
  targetService: {
    taskDefinition,
    containerName: 'mycontainer',
    containerPort: 80,
  },
  autoRollback: {
    failedDeployment: true,
    deploymentInAlarm: true,
    stoppedDeployment: false,
  },
});
python
# deployment_group: codedeploy.IEcsDeploymentGroup
# task_definition: ecs.ITaskDefinition


EcsDeployment({
    "deployment_group": deployment_group,
    "target_service": {
        "task_definition": task_definition,
        "container_name": "mycontainer",
        "container_port": 80
    },
    "auto_rollback": {
        "failed_deployment": True,
        "deployment_in_alarm": True,
        "stopped_deployment": False
    }
})
java
IEcsDeploymentGroup deploymentGroup;
ITaskDefinition taskDefinition;


new EcsDeployment(Map.of(
        "deploymentGroup", deploymentGroup,
        "targetService", Map.of(
                "taskDefinition", taskDefinition,
                "containerName", "mycontainer",
                "containerPort", 80),
        "autoRollback", Map.of(
                "failedDeployment", true,
                "deploymentInAlarm", true,
                "stoppedDeployment", false)));
csharp
IEcsDeploymentGroup deploymentGroup;
ITaskDefinition taskDefinition;


new EcsDeployment(new Dictionary<string, object> {
    { "deploymentGroup", deploymentGroup },
    { "targetService", new Struct {
        TaskDefinition = taskDefinition,
        ContainerName = "mycontainer",
        ContainerPort = 80
    } },
    { "autoRollback", new Struct {
        FailedDeployment = true,
        DeploymentInAlarm = true,
        StoppedDeployment = false
    } }
});
go
var deploymentGroup IEcsDeploymentGroup
var taskDefinition ITaskDefinition


NewEcsDeployment(map[string]interface{}{
	"deploymentGroup": deploymentGroup,
	"targetService": map[string]interface{}{
		"taskDefinition": taskDefinition,
		"containerName": jsii.String("mycontainer"),
		"containerPort": jsii.Number(80),
	},
	"autoRollback": map[string]*bool{
		"failedDeployment": jsii.Boolean(true),
		"deploymentInAlarm": jsii.Boolean(true),
		"stoppedDeployment": jsii.Boolean(false),
	},
})

By default, the CodeDeploy Deployment will timeout after 30 minutes. The timeout value can be overridden:

ts
declare const deploymentGroup: codedeploy.IEcsDeploymentGroup;
declare const taskDefinition: ecs.ITaskDefinition;

new EcsDeployment({
  deploymentGroup,
  targetService: {
    taskDefinition,
    containerName: 'mycontainer',
    containerPort: 80,
  },
  timeout: Duration.minutes(60),
});
python
# deployment_group: codedeploy.IEcsDeploymentGroup
# task_definition: ecs.ITaskDefinition


EcsDeployment({
    "deployment_group": deployment_group,
    "target_service": {
        "task_definition": task_definition,
        "container_name": "mycontainer",
        "container_port": 80
    },
    "timeout": Duration.minutes(60)
})
java
IEcsDeploymentGroup deploymentGroup;
ITaskDefinition taskDefinition;


new EcsDeployment(Map.of(
        "deploymentGroup", deploymentGroup,
        "targetService", Map.of(
                "taskDefinition", taskDefinition,
                "containerName", "mycontainer",
                "containerPort", 80),
        "timeout", Duration.minutes(60)));
csharp
IEcsDeploymentGroup deploymentGroup;
ITaskDefinition taskDefinition;


new EcsDeployment(new Dictionary<string, object> {
    { "deploymentGroup", deploymentGroup },
    { "targetService", new Struct {
        TaskDefinition = taskDefinition,
        ContainerName = "mycontainer",
        ContainerPort = 80
    } },
    { "timeout", Duration.Minutes(60) }
});
go
var deploymentGroup IEcsDeploymentGroup
var taskDefinition ITaskDefinition


NewEcsDeployment(map[string]interface{}{
	"deploymentGroup": deploymentGroup,
	"targetService": map[string]interface{}{
		"taskDefinition": taskDefinition,
		"containerName": jsii.String("mycontainer"),
		"containerPort": jsii.Number(80),
	},
	"timeout": awscdk.Duration_minutes(jsii.Number(60)),
})

Types ​

NameKindSummary
BaseDeploymentConfigConstruct (L2)The base class for ServerDeploymentConfig, EcsDeploymentConfig, and LambdaDeploymentConfig deployment configurations.
CustomLambdaDeploymentConfigConstruct (L2)A custom Deployment Configuration for a Lambda Deployment Group.
EcsApplicationConstruct (L2)A CodeDeploy Application that deploys to an Amazon ECS service.
EcsDeploymentConfigConstruct (L2)A custom Deployment Configuration for an ECS Deployment Group.
EcsDeploymentGroupConstruct (L2)A CodeDeploy deployment group that orchestrates ECS blue-green deployments.
LambdaApplicationConstruct (L2)A CodeDeploy Application that deploys to an AWS Lambda function.
LambdaDeploymentConfigConstruct (L2)A custom Deployment Configuration for a Lambda Deployment Group.
LambdaDeploymentGroupConstruct (L2)
ServerApplicationConstruct (L2)A CodeDeploy Application that deploys to EC2/on-premise instances.
ServerDeploymentConfigConstruct (L2)A custom Deployment Configuration for an EC2/on-premise Deployment Group.
ServerDeploymentGroupConstruct (L2)A CodeDeploy Deployment Group that deploys to EC2/on-premise instances.
CfnApplicationConstruct (L1)The AWS::CodeDeploy::Application resource creates an AWS CodeDeploy application.
CfnDeploymentConfigConstruct (L1)The AWS::CodeDeploy::DeploymentConfig resource creates a set of deployment rules, deployment success conditions, and deployment failure conditions that AWS CodeDeploy uses during a deployment.
CfnDeploymentGroupConstruct (L1)The AWS::CodeDeploy::DeploymentGroup resource creates an AWS CodeDeploy deployment group that specifies which instances your application revisions are deployed to, along with other deployment options.
AllAtOnceTrafficRoutingClassDefine a traffic routing config of type 'AllAtOnce'.
AutoRollbackConfigStructThe configuration for automatically rolling back deployments in a given Deployment Group.
BaseDeploymentConfigOptionsStructConstruction properties of BaseDeploymentConfig.
BaseDeploymentConfigPropsStructComplete base deployment config properties that are required to be supplied by the implementation of the BaseDeploymentConfig class.
BaseTrafficShiftingConfigPropsStructCommon properties of traffic shifting routing configurations.
CanaryTrafficRoutingConfigStructRepresents the configuration specific to canary traffic shifting.
CfnApplicationPropsStructProperties for defining a CfnApplication.
CfnDeploymentConfig.MinimumHealthyHostsPerZonePropertyStructInformation about the minimum number of healthy instances per Availability Zone.
CfnDeploymentConfig.MinimumHealthyHostsPropertyStructMinimumHealthyHosts is a property of the DeploymentConfig resource that defines how many instances must remain healthy during an AWS CodeDeploy deployment.
CfnDeploymentConfig.TimeBasedCanaryPropertyStructA configuration that shifts traffic from one version of a Lambda function or Amazon ECS task set to another in two increments.
CfnDeploymentConfig.TimeBasedLinearPropertyStructA configuration that shifts traffic from one version of a Lambda function or ECS task set to another in equal increments, with an equal number of minutes between each increment.
CfnDeploymentConfig.TrafficRoutingConfigPropertyStructThe configuration that specifies how traffic is shifted from one version of a Lambda function to another version during an AWS Lambda deployment, or from one Amazon ECS task set to another during an Amazon ECS deployment.
CfnDeploymentConfig.ZonalConfigPropertyStructConfigure the ZonalConfig object if you want AWS CodeDeploy to deploy your application to one Availability Zone at a time, within an AWS Region. By deploying to one Availability Zone at a time, you can expose your deployment to a progressively larger audience as confidence in the deployment's performance and viability grows. If you don't configure the ZonalConfig object, CodeDeploy deploys your application to a random selection of hosts across a Region.
CfnDeploymentConfigPropsStructProperties for defining a CfnDeploymentConfig.
CfnDeploymentGroup.AlarmConfigurationPropertyStructThe AlarmConfiguration property type configures CloudWatch alarms for an AWS CodeDeploy deployment group.
CfnDeploymentGroup.AlarmPropertyStructThe Alarm property type specifies a CloudWatch alarm to use for an AWS CodeDeploy deployment group.
CfnDeploymentGroup.AutoRollbackConfigurationPropertyStructThe AutoRollbackConfiguration property type configures automatic rollback for an AWS CodeDeploy deployment group when a deployment is not completed successfully.
CfnDeploymentGroup.BlueGreenDeploymentConfigurationPropertyStructInformation about blue/green deployment options for a deployment group.
CfnDeploymentGroup.BlueInstanceTerminationOptionPropertyStructInformation about whether instances in the original environment are terminated when a blue/green deployment is successful.
CfnDeploymentGroup.DeploymentPropertyStructDeployment is a property of the DeploymentGroup resource that specifies an AWS CodeDeploy application revision to be deployed to instances in the deployment group. If you specify an application revision, your target revision is deployed as soon as the provisioning process is complete.
CfnDeploymentGroup.DeploymentReadyOptionPropertyStructInformation about how traffic is rerouted to instances in a replacement environment in a blue/green deployment.
CfnDeploymentGroup.DeploymentStylePropertyStructInformation about the type of deployment, either in-place or blue/green, you want to run and whether to route deployment traffic behind a load balancer.
CfnDeploymentGroup.EC2TagFilterPropertyStructInformation about an Amazon EC2 tag filter.
CfnDeploymentGroup.EC2TagSetListObjectPropertyStructThe EC2TagSet property type specifies information about groups of tags applied to Amazon EC2 instances.
CfnDeploymentGroup.EC2TagSetPropertyStructThe EC2TagSet property type specifies information about groups of tags applied to Amazon EC2 instances.
CfnDeploymentGroup.ECSServicePropertyStructContains the service and cluster names used to identify an Amazon ECS deployment's target.
CfnDeploymentGroup.ELBInfoPropertyStructThe ELBInfo property type specifies information about the Elastic Load Balancing load balancer used for an CodeDeploy deployment group.
CfnDeploymentGroup.GitHubLocationPropertyStructGitHubLocation is a property of the CodeDeploy DeploymentGroup Revision property that specifies the location of an application revision that is stored in GitHub.
CfnDeploymentGroup.GreenFleetProvisioningOptionPropertyStructInformation about the instances that belong to the replacement environment in a blue/green deployment.
CfnDeploymentGroup.LoadBalancerInfoPropertyStructThe LoadBalancerInfo property type specifies information about the load balancer or target group used for an AWS CodeDeploy deployment group.
CfnDeploymentGroup.OnPremisesTagSetListObjectPropertyStructThe OnPremisesTagSetListObject property type specifies lists of on-premises instance tag groups.
CfnDeploymentGroup.OnPremisesTagSetPropertyStructThe OnPremisesTagSet property type specifies a list containing other lists of on-premises instance tag groups.
CfnDeploymentGroup.RevisionLocationPropertyStructRevisionLocation is a property that defines the location of the CodeDeploy application revision to deploy.
CfnDeploymentGroup.S3LocationPropertyStructS3Location is a property of the CodeDeploy DeploymentGroup Revision property that specifies the location of an application revision that is stored in Amazon Simple Storage Service ( Amazon S3 ).
CfnDeploymentGroup.TagFilterPropertyStructTagFilter is a property type of the AWS::CodeDeploy::DeploymentGroup resource that specifies which on-premises instances to associate with the deployment group. To register on-premise instances with AWS CodeDeploy , see Configure Existing On-Premises Instances by Using AWS CodeDeploy in the AWS CodeDeploy User Guide .
CfnDeploymentGroup.TargetGroupInfoPropertyStructThe TargetGroupInfo property type specifies information about a target group in Elastic Load Balancing to use in a deployment.
CfnDeploymentGroup.TargetGroupPairInfoPropertyStructInformation about two target groups and how traffic is routed during an Amazon ECS deployment.
CfnDeploymentGroup.TrafficRoutePropertyStructInformation about a listener.
CfnDeploymentGroup.TriggerConfigPropertyStructInformation about notification triggers for the deployment group.
CfnDeploymentGroupPropsStructProperties for defining a CfnDeploymentGroup.
ComputePlatformEnumThe compute platform of a deployment configuration.
CustomLambdaDeploymentConfigPropsStructProperties of a reference to a CodeDeploy Lambda Deployment Configuration.
CustomLambdaDeploymentConfigTypeEnumLambda Deployment config type.
EcsApplicationPropsStructConstruction properties for EcsApplication.
EcsBlueGreenDeploymentConfigStructSpecify how the deployment behaves and how traffic is routed to the ECS service during a blue-green ECS deployment.
EcsDeploymentConfigPropsStructConstruction properties of EcsDeploymentConfig.
EcsDeploymentGroupAttributesStructProperties of a reference to a CodeDeploy ECS Deployment Group.
EcsDeploymentGroupPropsStructConstruction properties for EcsDeploymentGroup.
IBaseDeploymentConfigInterfaceThe base class for ServerDeploymentConfig, EcsDeploymentConfig, and LambdaDeploymentConfig deployment configurations.
IBindableDeploymentConfigInterfaceA DeploymentConfig that can specialize itself based on the target group it will be used for.
IEcsApplicationInterfaceRepresents a reference to a CodeDeploy Application deploying to Amazon ECS.
IEcsDeploymentConfigInterfaceThe Deployment Configuration of an ECS Deployment Group.
IEcsDeploymentGroupInterfaceInterface for an ECS deployment group.
ILambdaApplicationInterfaceRepresents a reference to a CodeDeploy Application deploying to AWS Lambda.
ILambdaDeploymentConfigInterfaceThe Deployment Configuration of a Lambda Deployment Group.
ILambdaDeploymentGroupInterfaceInterface for a Lambda deployment groups.
InstanceTagSetClassRepresents a set of instance tag groups.
IServerApplicationInterfaceRepresents a reference to a CodeDeploy Application deploying to EC2/on-premise instances.
IServerDeploymentConfigInterfaceThe Deployment Configuration of an EC2/on-premise Deployment Group.
IServerDeploymentGroupInterface
LambdaApplicationPropsStructConstruction properties for LambdaApplication.
LambdaDeploymentConfigImportPropsStructProperties of a reference to a CodeDeploy Lambda Deployment Configuration.
LambdaDeploymentConfigPropsStructConstruction properties of LambdaDeploymentConfig.
LambdaDeploymentGroupAttributesStructProperties of a reference to a CodeDeploy Lambda Deployment Group.
LambdaDeploymentGroupPropsStructConstruction properties for LambdaDeploymentGroup.
LinearTrafficRoutingConfigStructRepresents the configuration specific to linear traffic shifting.
LoadBalancerClassAn interface of an abstract load balancer, as needed by CodeDeploy.
LoadBalancerGenerationEnumThe generations of AWS load balancing solutions.
MinimumHealthyHostsClassMinimum number of healthy hosts for a server deployment.
MinimumHealthyHostsPerZoneClassMinimum number of healthy hosts per availability zone for a server deployment.
ServerApplicationPropsStructConstruction properties for ServerApplication.
ServerDeploymentConfigPropsStructConstruction properties of ServerDeploymentConfig.
ServerDeploymentGroupAttributesStructProperties of a reference to a CodeDeploy EC2/on-premise Deployment Group.
ServerDeploymentGroupPropsStructConstruction properties for ServerDeploymentGroup.
TimeBasedCanaryTrafficRoutingClassDefine a traffic routing config of type 'TimeBasedCanary'.
TimeBasedCanaryTrafficRoutingPropsStructConstruction properties for TimeBasedCanaryTrafficRouting.
TimeBasedLinearTrafficRoutingClassDefine a traffic routing config of type 'TimeBasedLinear'.
TimeBasedLinearTrafficRoutingPropsStructConstruction properties for TimeBasedLinearTrafficRouting.
TrafficRoutingClassRepresents how traffic is shifted during a CodeDeploy deployment.
TrafficRoutingConfigStructRepresents the structure to pass into the underlying CfnDeploymentConfig class.
ZonalConfigStructConfiguration for CodeDeploy to deploy your application to one Availability Zone at a time within an AWS Region.