Search code examples
amazon-web-servicesdockeraws-cdkaws-fargateaws-ssm

import an existing SSM Parameter and add as an Task Image environment variable in ApplicationLoadBalancedFargateService


I have parameters in SSM that is saved looking something like /dbUrl/prod , /dbUrl/dev and so on where it is in the format /dbUrl/${stage}.

I want to get this parameter and set as an environment variable for the task definition so I have a different value for the variable based on different environment. Right now stuck on how to import an existing parameter

Also is it possible to access the DB_URL value as process.env.DB_URL inside my node.js code after I manage to set the environment variable here

Docs I was following
ApplicationLoadBalancedFargateService
ApplicationLoadBalancedTaskImageOptions#secrets

      const socketService = new ecs_patterns.ApplicationLoadBalancedFargateService(this, `socketService${props.stage}`, {
        cluster: cluster,
        loadBalancer: loadBalancer ,
        memoryLimitMiB: 2048,
        cpu: 1024,
        desiredCount: 2,
        listenerPort: 1111,
        taskImageOptions: {
          image: ContainerImage.fromAsset("../socket"),
          environment: {
          },
          secrets: {
            DB_URL: //how to import existing /dbUrl/${props.stage} from SSM
          }
        },
        
      });
    

Solution

  • You linked to documentation on the secrets prop of the ApplicationLoadBalancedTaskImageOptions. The docs specify that the type of the secrets prop is { [string]: Secret }.

    You can follow the link to the documentation of Secret to see how it can be obtained. You will see that it has a fromSsmParameter method, which is what you need. That method takes in an IParameter.

    To import an existing String Parameter, you can use one of the from* methods defined in the StringParameter class. For example, you can use fromSecureStringParameterAttributes