How can I assign environment variable that has reference of conditional resource in serverless.yml?

Viewed 65

I want to put resource's attributes into environment variable.
The problem is that resource is not ALWAYS created. It is only created in production.
Because of this situation, when I try to deploy to another stage, such as dev, Template format error: Unresolved resource dependencies [MyQueue] in the Resources block of the template error occured.

Is there any way to allocate environment variable conditionally per stage??

service: condition-test

provider:
  name: aws
  runtime: nodejs12.x
  stage: ${opt:stage, 'dev'}
  environment:
    TEST_QUEUE_URL:
      Ref: TestQueue

resources:
  Conditions:
    MyCondition: !Equals ['prod', '${self:provider.stage}']
 # false
  Resources:
    MyQueue:
      Type: AWS::SQS:Queue
      Condition: MyCondition
      Properties:
        QueueName: 'my-test-queue-${self:provider.stage}'
1 Answers

You can set custom environment variables based on stage like below:

service: condition-test

provider:
  name: aws
  runtime: nodejs12.x
  stage: ${opt:stage, 'dev'}
  environment: ${self:custom.env_vars.${self:provider.stage}}

custom:
  env_vars:
    alpha:
      KEY_1: Val
      KEY_2: Val2
      KEY_3: Val3
    prod:
      TEST_QUEUE_URL:
        Ref: TestQueue
      KEY_2: Val_5
      KEY_3: Val_6

resources:
  Conditions:
    MyCondition: !Equals ['prod', '${self:provider.stage}']
 # false
  Resources:
    MyQueue:
      Type: AWS::SQS:Queue
      Condition: MyCondition
      Properties:
        QueueName: 'my-test-queue-${self:provider.stage}'
Related