amazon-web-servicesamazon-ecsaws-cdkaws-batch

Adding a secret value to an EcsJobDefinition


I am trying to add a secret value to my ECS Job definition,

        secret_id = f"mysecretid"
        secret = secretsmanager.Secret.from_secret_name_v2(
            self,
            secret_id,
            secret_name=secret_id,
        )

        # Mongo DB URI
        mongodb_uri = ecs.Secret.from_secrets_manager(secret, "MONGODB_URI")

        job_definition = batch.EcsJobDefinition(self, f"{stage}{NAME}JobDefinition",
            container=batch.EcsEc2ContainerDefinition(self, "Container",
                image=image,
                memory=Size.mebibytes(4096),
                cpu=2,
                secrets={"MONGO_DB_URI": mongodb_uri},
                command=["npm run crawl"],
            )
        )      

I am running into the error,

RuntimeError: Passed to parameter props of new aws-cdk-lib.aws_batch.EcsEc2ContainerDefinition: Unable to deserialize value as aws-cdk-lib.aws_batch.EcsEc2ContainerDefinitionProps
ā”œā”€ā”€ šŸ›‘ Failing value is an object
ā”‚      { '$jsii.struct': [Object] }
ā•°ā”€ā”€ šŸ” Failure reason(s):
    ā•°ā”€ Key 'secrets': Unable to deserialize value as map<aws-cdk-lib.aws_batch.Secret> | undefined
        ā”œā”€ā”€ šŸ›‘ Failing value is an object
        ā”‚      { '$jsii.map': [Object] }
        ā•°ā”€ā”€ šŸ” Failure reason(s):
            ā•°ā”€ Key 'MONGO_DB_URI': Unable to deserialize value as aws-cdk-lib.aws_batch.Secret
                ā”œā”€ā”€ šŸ›‘ Failing value is an object
                ā”‚      { '$jsii.byref': 'aws-cdk-lib.aws_ecs.Secret@10003' }
                ā•°ā”€ā”€ šŸ” Failure reason(s):
                    ā•°ā”€ Object of type 'aws-cdk-lib.aws_ecs.Secret' is not convertible to aws-cdk-lib.aws_batch.Secret

Solution

  • The error message is fairly clear:

    Object of type 'aws-cdk-lib.aws_ecs.Secret' is not convertible to aws-cdk-lib.aws_batch.Secret
    

    Since you are creating a Batch Job, instead of an ECS Task, it is expecting a Batch secret instead of an ECS secret. You need to use the batch version of the secret reference.

    Change your code to this:

    # Mongo DB URI
    mongodb_uri = batch.Secret.from_secrets_manager(secret, "MONGODB_URI")