Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 760
Vladimir Kuznetsov Avatar asked Sep 07 '25 10:09

Vladimir Kuznetsov


1 Answers

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
like image 106
Erez Avatar answered Sep 10 '25 02:09

Erez