aws-cloudformationaws-cdkautoscalingamazon-amilaunch-configuration

Assigning a launch configuration to an Auto-Scaling Group using CDK


Note: the code here is Go but happy to see answers in any CDK language.

In AWS CDK, you can create Launch Configurations:

// Create the launch configuration
lc := awsautoscaling.NewCfnLaunchConfiguration(
    stack,
    jsii.String("asg-lc"),
    &awsautoscaling.CfnLaunchConfigurationProps{
        ...
    },
)

But there is no obvious parameter or function in the Auto-Scaling Group props to attach it.

I have set the update policy:

UpdatePolicy: awsautoscaling.UpdatePolicy_RollingUpdate,

What I want to do is be able to call an auto-refresh in the CI system when an AMI configuration has changed:

aws autoscaling start-instance-refresh --cli-input-json file://asg-refresh.json

The problem is that the launch configuration appears to have been created automatically when the stack is first created and doesn't change on update and has incorrect values (AMI ID is outdated).

Is there a way to define/refresh the launch config using CDK to update the AMI ID? It's a simple change in the UI.


Solution

  • If you use the L2 AutoScalingGroup Construct, you can run cdk deploy after updating the AMI and it should launch a new one for you. Also with this Construct, the Launch Configuration is created for you. You don't really need to worry about it.

                IMachineImage image = MachineImage.Lookup(new LookupMachineImageProps()
                {
                    Name = "MY-AMI", // this can be updated on subsequent deploys
                });
    
                
                AutoScalingGroup asg = new AutoScalingGroup(this, $"MY-ASG", new AutoScalingGroupProps()
                {
                    AllowAllOutbound = false,
                    AssociatePublicIpAddress = false,
                    AutoScalingGroupName = $"MY-ASG",
                    Vpc = network.Vpc,
                    VpcSubnets = new SubnetSelection() { Subnets = network.Vpc.PrivateSubnets },
                    MinCapacity = 1,
                    MaxCapacity = 2,
                    MachineImage = image, 
                    InstanceType = new InstanceType("m5.xlarge"),
                    SecurityGroup = sg,
                    UpdatePolicy = UpdatePolicy.RollingUpdate(new RollingUpdateOptions()
                    {
                        
                    }),
                });