pythonamazon-ec2aws-cdkaws-batch

AWS Python CDK - define the launch template for Batch Compute Environment


In my Python CDK Stack, I'm trying to configure an AWS Batch Compute Environment to be able to use a Launch Template I'm creating in the same stack. Example:

launch_template = ec2.CfnLaunchTemplate(
    scope=self,
    id=f"{stack_id}-EC2LaunchTemplate",
    launch_template_name=f"{stack_id}-EC2LaunchTemplate",
    launch_template_data=ec2.CfnLaunchTemplate.LaunchTemplateDataProperty(
        image_id="ami-xxxxxxxxxxx",
        instance_type="xxxxxxxxxx",
        ebs_optimized=True,
        user_data=Fn.base64(...)
    )
)

compute_env_gpu = batch.ManagedEc2EcsComputeEnvironment(
    scope=self,
    id="compute_env_id",
    ...
    launch_template=launch_template
)

My Stack without the launch template works well. The definition as above passes cdk synth, but fails cdk deploy with the following error:

Resource handler returned message: "Error executing request, Exception : LaunchTemplateId or LaunchTemplateName is required.

If instead I use this:

launch_template=batch.CfnComputeEnvironment.LaunchTemplateSpecificationProperty(
    launch_template_name=f"{stack_id}-EC2LaunchTemplate",
)

I get this error:

RuntimeError: Passed to parameter props of new aws-cdk-lib.aws_batch.ManagedEc2EcsComputeEnvironment: Unable to deserialize value as aws-cdk-lib.aws_batch.ManagedEc2EcsComputeEnvironmentProps
ā”œā”€ā”€ šŸ›‘ Failing value is an object
ā”‚      { '$jsii.struct': [Object] }
ā•°ā”€ā”€ šŸ” Failure reason(s):
    ā•°ā”€ Key 'launchTemplate': Unable to deserialize value as aws-cdk-lib.aws_ec2.ILaunchTemplate | undefined
        ā”œā”€ā”€ šŸ›‘ Failing value is an object
        ā”‚      { '$jsii.struct': [Object] }
        ā•°ā”€ā”€ šŸ” Failure reason(s):
            ā•°ā”€ Value does not have the "$jsii.byref" key

How can I fix this?


Solution

  • batch.ManagedEc2EcsComputeEnvironment.launch_template is expecting ec2.ILaunchTemplate interface which ec2.CfnLaunchTemplate does not satisfy. Use ec2.LaunchTemplate instead.