Use custom resources Export value in function environment variables

Hi! I’m trying to deploy a function that depends on the custom resources I specified. I would like to set the output value of some resources to environment variable at the function level. Unfortunately, it fails because the Lambda function seems to be deployed first and the output values are not yet exported. Is it a use case that serverless can handle?

To give some context, the “Queue” is really related to the service, this is why I’d like to create it with this service and avoid to add a separate step to create first the queue then deploy the service.

An example below

serverless.yml

functions:
  consumer:
    environment:
      QUEUE_URL:
        'Fn::ImportValue': QueueUrl-${self:provider.stage}
    handler: handler.consume
    events:
      - sqs:
          arn: somevalidarn
          batchSize: 1

resources:
  - ${file(cloudformation/queue.yml)}

cloudformation/queue.yml

Resources:
  Queue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: ${self:provider.stage}-queue
      RedrivePolicy:
        deadLetterTargetArn:
          Fn::GetAtt:
            - "DeadLetterQueue"
            - "Arn"
        maxReceiveCount: 5
  DeadLetterQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: ${self:provider.stage}-deadletter-queue
Outputs:
  QueueUrl:
    Description: "URL of the queue"
    Value:
      Ref: Queue
    Export:
      Name: QueueUrl-${self:provider.stage}
  QueueArn:
    Description: "ARN of the queue"
    Value:
      Fn::GetAtt:
        - "Queue"
        - "Arn"
    Export:
      Name: QueueArn-${self:provider.stage}
  DeadLetterQueueUrl:
    Description: "Url of the dead letter queue"
    Value:
      Ref: DeadLetterQueue
    Export:
      Name: DeadLetterQueueUrl-${self:provider.stage}
  DeadLetterQueueArn:
    Description: "ARN of the dead letter queue"
    Value:
      Fn::GetAtt:
        - "DeadLetterQueue"
        - "Arn"
    Export:
      Name: DeadLetterQueueArn-${self:provider.stage}
1 Like

Oops, I found out that I could just do that directly in the serverless config file

functions:
  consumer:
    environment:
      QUEUE_ARN:
        Fn::GetAtt:
          - "Queue"
          - "Arn"
      QUEUE_URL:
        Ref: Queue
3 Likes

Nice for you but I was hoping to get how to actually do what you originally tried.

1 Like