Building a weather monitor with AWS SAM and Terraform — part 1

Richard Chou
3 min readNov 26, 2023

--

Source code can be found here

Part 2 Part 3

This article is the “data fetcher” part of the weather monitor. It is comprised of a Lambda function and EventBridge. The Lambda function pulls weather data from api.openweathermap.org and sends the retrieved data to EventBridge.

Deploying to multi-accounts on AWS

The lambda function is developed and tested on local machine. Once commited to GitHub, GitHub actions will deploy to AWS using SAM. SAM will also create an EventBridge schedule and necessary IAM role to trigger Lambda periodically.

SAM will push to multiple AWS accounts using assume role.

For Tools Account to be able to assume role, the IAM role needs to give permission to Tools Account.

I also created two environments on GitHub to store credentials. So when SAM deploys, it will grab necessary credentials depending on which environment it is in.

.github/workflows/production.yml

Specifying prod environment, GitHub actions will pull credentials from prod.

.github/workflows/staging.yml

Specifying staging environment, GitHub actions will pull credentials from staging.

Next SAM will assume role to deploy to prod and staging.

SAM template

template.yaml

Let’s go through the important part in SAM template.

This part creates a Lambda function and gives it permission to push events to EventBridge.

This part creates an EventBridge scheduler and gives it necessary permission to invoke Lambda.

Passing env vars from GitHub secrets to SAM

The openweathermap API key is passed from GitHub secrets to Lambda so Lambda can call the API to get the weather data.

To define env vars, first create Parameters and Environment: Variables blocks in SAM template:

template.yaml

Then, in GitHub workflows, use --parameter-overrides to pass env var. Of course, you can use different API key for staging and production environments.

.github/workflows/production.yml

Finally, you will be able to use env var in the Lambda:

src/app.ts

Developers and Business Owners: Do you need to build a LINE Bot to increase visibility of your business? I’m creating a course to teach you how to build a LINE Bot using AWS Sam, Lambda and DynamoDB.

--

--

Richard Chou

I write about Ruby, Rails, AWS and JavaScript. Occasionally other things.