pythonaws-cdkaws-auto-scaling

Can't use aws_cdk.Fn.conditionIf in AutoScalingGroup


I'm currently making a Stack using python aws cdk V2 and I want to make certain conditions be ran on the template instead in CDK synth so by updating a parameter in cloudformation the template can adapt and not have to be re-synthesised.

Having that said, I currently have this code to make the AutoScaling Group:

autoscaling.AutoScalingGroup(
            self,
            "MagentoAutoScalingInstance",
            auto_scaling_group_name=f"MagentoAutoScalingGroup{self._parameters.environment.value_as_string}",
            vpc=self.vpc,
            vpc_subnets=ec2.SubnetSelection(
                subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS
            ),
            instance_type=ec2.InstanceType(self._parameters.auto_scaling_instance_type.value_as_string),
            instance_monitoring=aws_cdk.Fn.condition_if(
                self._conditions.is_production.logical_id,
                autoscaling.Monitoring.DETAILED,
                autoscaling.Monitoring.BASIC
            ),
            new_instances_protected_from_scale_in=True,
            machine_image=ec2.AmazonLinuxImage(
                generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2
            ),
            role=self.auto_scaling_role,
            security_group=self.auto_scaling_sg
        )

But when I try cdk synth I get the following type error:

TypeError: type of argument instance_monitoring must be o
ne of (aws_cdk.aws_autoscaling.Monitoring, NoneType); got jsii._reference_map.InterfaceDynamicProxy instead 

The option Fn.condition_if exists so I suppose this should be possible. Am I missing anything?


Solution

  • You must apply the condition to a L1 resource.

    Looking in the CDK source code, we see that the L2 AutoScalingGroup construct uses the instance monitoring prop to define a L1 CfnLaunchConfiguration. The L1 construct is given an id of "LaunchConfig". The Launch Configuration's instance_monitoring prop is then set to True if the Monitoring.DETAILED prop was passed.

    So we leave the L2's instance_monitoring prop undefined and manually apply the condition to the L1 construct using escape hatch syntax:

    # Get a reference to the L1 construct
    cfn_launch_config = cast(
        autoscaling.CfnLaunchConfiguration, asg.node.find_child("LaunchConfig")
    )
    
    # Set the InstanceMonitoring property of the L1 LaunchConfiguration to a Fn::If
    cfn_launch_config.instance_monitoring = Fn.condition_if(
        self._conditions.is_production.logical_id, True, False
    )
    

    The workaround is required because Fn.condition_if only resolves at deploy-time. For this reason, say the docs: "In general, we recommend against using AWS CloudFormation parameters with the AWS CDK."