AWS Lambda & GitHub Actions
AWS Lambda
An event-driven, serverless computing platform. It is a computing service that runs code in response to events and automatically manages the computing resources required by that code.
How to set up an AWS Lambda function and auto deployments with Github Actions (in Ruby)
- Create a Lambda function(say
my-serverless-function) on AWS.- Open the Lambda service from AWS home console.
- Open the Functions page of the Lambda console.
- Choose Create function
- Provide the basic information like function name and runtime environment.
- Click on Create function
- Create a GitHub repository, clone it on your system(optional).
- Navigate to your repository, create a file
lambda_function.rb, and provide the sample code of a lambda function.require 'json' def lambda_handler(event:, context:) msg = "Hello from Lambda!" { statusCode: 200, body: JSON.generate(msg) } end - Push the code to your GitHub repository if working locally.
- Navigate to Actions → New Workflow → Set up a workflow yourself.
# This is a basic workflow to help you get started with Actions name: Ruby CI to AWS Lambda # Controls when the workflow will run on: # Triggers the workflow on push or pull request events but only for the main branch push: branches: [ main ] pull_request: branches: [ main ] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: jobs: deploy_source: name: build and deploy lambda runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Ruby uses: ruby/setup-ruby@359bebbc29cbe6c87da6bc9ea3bc930432750108 with: ruby-version: '2.7' - name: Install dependencies run: bundle install env: CI: true - name: zip uses: montudor/action-zip@v0.1.0 with: args: zip -qq -r ./bundle.zip ./ - name: default deploy uses: appleboy/lambda-action@master with: aws_access_key_id: $ aws_secret_access_key: $ aws_region: us-east-2 function_name: ss-auto-deploy-ruby-function zip_file: bundle.zip - Make sure, the
function_name,aws_regionis the same as your lambda function name and the region. - We need to add the value for
AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEYin the secrets. We could hardcode here, but that’s not recommended.- Where to get the access key id and secret access key? Go to AWS Console → Services → IAM → Users → Select your user → Security Credentials → Access Keys.
- In your GitHub repository. Go to Settings → Secrets → Actions and add your access key id and secret access key with the name as given above.
- Now, whenever code is pushed into the main branch of your GitHub repository the changes will be reflected in your AWS Lambda function.
The source code of this activity is available here: https://github.com/ahasunos/aws-lambda-ruby-auto-deploy