Vladimir Kuznetsov
Vladimir Kuznetsov

Reputation: 1891

Serverless — How to pass S3 bucket name as an environment variable to my app

I need to provide the name of the S3 bucket, which serverless create for me, to my application. Here is a simplified version of my serverless.yml file.

service: dummy-service
app: dummy-service

custom:
  bucket: "I have no idea what to write here!"

provider:
  name: aws
  runtime: nodejs10.x
  region: eu-central-1
  iamRoleStatements:
    - Effect: Allow
      Action:
        - s3:PutObject
        - s3:GetObject
      Resource:
        - "Fn::Join":
          - ""
          - - "arn:aws:s3:::"
            - Ref: DummyBucket
            - "*"
  environment:
    BUCKET: ${self:custom.bucket}

resources:
  Resources:
    DummyBucket:
      Type: AWS::S3::Bucket

functions:
  createOrUpdate:
    handler: handler.dummy
    events:
      - http:
          path: dummy
          method: POST

I have figured out how to make a reference in the iamRoleStatements section. But can't understand how to get it as a string for the environment variable.

Any help is welcome. Thanks.

Upvotes: 4

Views: 1848

Answers (1)

Erez
Erez

Reputation: 1750

You can use Ref to get the bucket name

service: dummy-service
app: dummy-service

custom:
  bucket:
    Ref: DummyBucket

provider:
  name: aws
  runtime: nodejs10.x
  region: eu-central-1
  iamRoleStatements:
    - Effect: Allow
      Action:
        - s3:PutObject
        - s3:GetObject
      Resource:
        - "Fn::Join":
          - ""
          - - "arn:aws:s3:::"
            - Ref: DummyBucket
            - "*"
  environment:
    BUCKET: ${self:custom.bucket}

resources:
  Resources:
    DummyBucket:
      Type: AWS::S3::Bucket

functions:
  createOrUpdate:
    handler: handler.dummy
    events:
      - http:
          path: dummy
          method: POST

Upvotes: 4

Related Questions