Microservice with Lambda and API Gateway Using CloudFormation

In this article, I will show you how to create a microservice with AWS Lambda and API Gateway.

What are AWS Lambda and API Gateway

AWS Lambda lets you run your code without provisioning or managing any servers. This gives you a completely serverless architecture with little to no effort on maintenance.

Amazon API Gateway is a fully managed service for managing your APIs. In order for your Lambda to run, it will need a trigger event. AWS allows you to attach multiple different event sources, like SQS, DynamoDB Streams, but in this article, I will focus on API Gateway.

By setting API Gateway as the event source, Lambda can receive your API input and send the output back to API Gateway.

What is AWS CloudFormation?

AWS CloudFormation allows you to create your infrastructure as code. And by deploying your CloudFormation script, AWS will automatically provision all resources specified. This script will serve as the single source of truth for your cloud environment. 

Let’s Get Started

LambdaFunction creates a Lambda function called SampleLambda with a memory size of 128 mb and a timeout of 10 seconds.

LambdaFunction:
   Type: AWS::Lambda::Function
   Properties:
     Code:
       S3Bucket: <BUCKET_NAME>
       S3Key: <BUCKET_KEY>
     Description: Sample Lambda
     FunctionName: SampleLambda
     Handler: main
     MemorySize: 128
     Role: !GetAtt LambdaFunctionRole.Arn
     Runtime: go1.x
     Timeout: 10

LambdaFunctionRole creates a Lambda IAM role called SampleLambdaRole. This gives your Lambda permissions to perform certain actions. The role below allows your Lambda to perform X-Ray PutTraceSegments and PutTelemetryRecords.

LambdaFunctionRole:
   Type: AWS::IAM::Role
   Properties:
     RoleName: SampleLambdaRole
     AssumeRolePolicyDocument:
       Version: '2012-10-17'
       Statement:
       - Effect: Allow
         Action: sts:AssumeRole
         Principal:
           Service:
           - lambda.amazonaws.com
           Path: '/'
           Policies:
           - PolicyName: XRayPolicy
             PolicyDocument:
               Version: '2012-10-17'
               Statement:
               - Effect: Allow
                 Action:
                 - xray:PutTraceSegments
                 - xray:PutTelemetryRecords
                 Resource: '*'

Api creates an API Gateway from a Swagger/OpenAPI file. By doing so, you can document your API at the same time. One limitation is that you will need to upload your Swagger file to S3 before deploying CloudFormation.

ApiAccount allows you to attach a CloudWatch role to your API Gateway.

ApiStage creates an API stage and ApiDeployment deploys your API stage.

Api:
   Type: AWS::ApiGateway::RestApi
   Properties:
     Name: SampleAPIGateway
     Description: Sample API Gateway
     EndpointConfiguration:
       Types:
       - REGIONAL
     Body:
       Fn::Transform:
         Name: AWS::Include
         Parameters:
           Location: !Sub s3://swagger.yaml
ApiAccount:
   Type: AWS::ApiGateway::Account
   Properties:
     CloudWatchRoleArn: !GetAtt CloudWatchRole.Arn
CloudWatchRole:
   Type: AWS::IAM::Role
   Properties:
     AssumeRolePolicyDocument:
       Version: '2012-10-17'
       Statement:
       - Effect: Allow
         Action: sts:AssumeRole
         Principal:
           Service:
           - apigateway.amazonaws.com
         Path: '/'
         ManagedPolicyArns:
         - 'arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs'
ApiStage:
   Type: 'AWS::ApiGateway::Stage'
   DependsOn:
   - ApiAccount 
   Properties: 
   DeploymentId: !Ref ApiDeployment 
   MethodSettings: 
   - DataTraceEnabled: true
   HttpMethod: '*' 
   LoggingLevel: INFO 
   ResourcePath: /*
   RestApiId: !Ref Api
   StageName: !Ref StageParameter 
ApiDeployment:
   Type: AWS::ApiGateway::Deployment
   Properties:
     RestApiId: !Ref Api

Congratulations! You now have a CloudFormation script ready to deploy.

But before you can deploy, you will need to run the package command. This will transform your Swagger file and add it to packaged-template.yaml.

$ aws cloudformation package --template-file template.yaml --s3-prefix $BUCKET_KEY --s3-bucket $BUCKET_NAME --output-template-file packaged-template.yaml

Next, run the deploy command to deploy the Lambda and API Gateway to your AWS account.

$ aws cloudformation deploy --template-file packaged-template.yaml --stack-name sample-stack --capabilities CAPABILITY_NAMED_IAM

Hope this article helped create a microservice with AWS Lambda and API Gateway using CloudFormation.

If you liked this article, please do share this article with your friends and family.

Speed up your Internet with this DNS

You can now speed up your Internet just by simply changing your DNS.

You might have heard of Google Public DNS, but it is not the fastest. Cloudflare teamed up with APNIC to create a DNS over HTTPS which encrypts your DNS queries and is able to resolve queries faster than all other DNS.

Speed up your Internet with Cloudflare DNS

Most DNS, if not all, do not provide secure queries. So even if you have established secure connections, your DNS queries are not encrypted.

Speed up your Internet now

To do so, simply configure your network settings to use 1.1.1.1 and 1.0.0.1 as your DNS.

For Windows

  1. Click on the Start menu, then click on Control Panel.
  2. Click on Network and Internet.
  3. Click on Change Adapter Settings.
  4. Right click on the Wi-Fi network you are connected to, then click Properties.
  5. Select Internet Protocol Version 4 (or Version 6 if desired).
  6. Click Properties.
  7. Write down any existing DNS server entries for future reference.
  8. Click Use The Following DNS Server Addresses.
  9. Replace those addresses with the 1.1.1.1 DNS addresses:
    • For IPv4: 1.1.1.1 and 1.0.0.1
    • For IPv6: 2606:4700:4700::1111 and 2606:4700:4700::1001
  10. Click OK, then Close.
  11. Restart your browser.

For MacOS

  1. Open System Preferences.
  2. Search for DNS Servers and select it from the dropdown.
  3. Click the + button to add a DNS Server and enter 1.1.1.1
  4. Click + again and enter 1.0.0.1 (This is for redundancy.)
  5. Click Ok, then click Apply.

Not on Windows or MacOS? Check out their setup guide for other devices.

Hope this short article showed you how to speed up your Internet and protect your privacy.

If you own a web server and have not setup SSL, this article will show you how to get a free certificate with Let’s Encrypt and deploy it on your server.

If you liked this article, don’t forget to share this article with your friends and family.

Enable HTTP/2 on Nginx

Have you enable HTTP/2 on your Nginx server? If you have not, you should.

In this article, I will show you how to enable HTTP/2 in less than 5 minutes.

Before we begin, let’s verify that it is not enabled on our website with this tool provided by KeyCDN.

HTTP/2 not enabled

If you have yet to setup SSL on your server, check out this tutorial on how you can install free SSL certificates on your servers before continuing below.

Let’s Enable HTTP/2

Edit your Nginx configuration (eg. /etc/nginx/conf.d/default.conf) with any text editor.

server {
    listen 443 ssl http2;
    ...
}

In the server block, as shown above, simply add http2 and you are done!

Now let’s verify that HTTP/2 has been enabled.

Voila!

Enable HTTP/2 on Nginx

Hope this short article helped you learned how to enabled HTTP/2 on Nginx.

If you liked this article, don’t forget to share this article with your friends and family.

Create Swap File on Linux Servers for Better Performance

Are you running a low memory server and your applications are crashing? You can create swap file to prevent your applications from crashing in just 5 minutes.

Low memory servers often crash when there is a sudden spike in workload. However, upgrading your server is not an option (yet) due to budget. Restarting your services or applications is cumbersome and it is not possible to check every second if anything has crashed.

In this article, I will show you how you can create swap file Read More

Optimize PHP-FPM on Low Memory Nginx Servers

Are you running PHP-FPM on low memory Nginx servers and your services are crashing frequently?

The simplest way to resolve this problem is to upgrade your server, but not when you have a tight budget.

Databases usually take up a large portion of your memory but limiting memory usage may cause problems. However, if your website has low traffic, you will be able to limit your server’s memory usage without affecting performance.

In this article, I will show you how you can optimize PHP-FPM Read More

Update WordPress with SELinux Enabled

Are you getting permission errors when you update WordPress with SELinux enabled? And facing similar errors you when you install plugins like W3 Total Cache?

You are not alone!

I had just experienced this problem and it took me several hours to realize that it is due to SELinux. But don’t be tempted to disable SELinux completely.

In this article, I will show you how you can update WordPress with SELinux enabled. Read More

Free SSL Certificates with Let’s Encrypt for Nginx on CentOS 7

Are you paying too much for SSL certificates? Are you looking for free SSL certificates?

You can get free SSL certificates with Let’s Encrypt and deploy it with Certbot in less than 10 minutes!

In this article, I will show you how you can install and deploy SSL certificates for Nginx servers running on CentOS 7.

What is Let’s Encrypt

Let’s Encrypt is a CA (Certificate Authority) that provides free SSL DV (Domain Validation) certificates. These free SSL certificates allow websites to Read More