Search code examples
amazon-web-servicesaws-cloudformationaws-samaws-sam-cliesbuild

Where does AWS SAM-generated buildspec get the S3_BUCKET value from?


New to AWS SAM. I used the sam init CLI command to provision a new, barebones Node 16.x/JavaScript lambda (serverless application) and for the most part I understand what all the auto-generated code does, except the generated buildspec.yml:

version: 0.2
phases:
  install:
    commands:
      # Install all dependencies (including dependencies for running tests)
      - npm install
  pre_build:
    commands:
      # Discover and run unit tests in the '__tests__' directory
      - npm run test
      # Remove all unit tests to reduce the size of the package that will be ultimately uploaded to Lambda
      - rm -rf ./__tests__
      # Remove all dependencies not needed for the Lambda deployment package (the packages from devDependencies in package.json)
      - npm prune --production
  build:
    commands:
      # Use AWS SAM to package the application by using AWS CloudFormation
      - aws cloudformation package --template template.yaml --s3-bucket $S3_BUCKET --output-template template-export.yml
artifacts:
  type: zip
  files:
    - template-export.yml

It looks like this file gets executed when I run sam build, and it looks like its packaging up my code into a deployable Node/JavaScript application (that will be executable as an AWS JavaScript Lambda) and it looks like its publishing this packaged/deployable application to an S3 bucket. I'm guessing that when I run sam deploy, that the deployment instructs CloudFormation to deploy the packaged/deployable function (stored in that S3 location) to my provisioned Lambda as its executable code.

So to begin with, if anything I've said above is incorrect or mistaken, please begin by correcting me and by providing the necessary course correction! But assuming I'm more or less on track...

I'm not understanding how or where the $S3_BUCKET variable is passed in. I don't see that anywhere else in the generated code, even after doing a grep. I assume that since this is standard, boilerplate AWS SAM that most other projects are auto-generated with the same type of setup, so hopefully it is something the community can help me figure out: where is buildspec.yml (ESBuild?) finding the value for $S3_BUCKET?


Solution

  • I use AWS SAM pretty often and, while I don't know every in and out of the application, the $S3_BUCKET variable gets passed in when the application is packaged. Here is my makefile for an application as an example. The output of the cloudformation then gets dropped onto AWS in that s3 bucket. I hope this helps

    https://i.sstatic.net/p7g4y.jpg

    Here is the aws documentation as well