Prerequisites
AWS account
AWS CLI installed and configured
Go installed on your development machine
Step 1: Create a Lambda Execution Role
First, we need to create an IAM role with the necessary permissions for our Lambda function.
1 – Create a file named trust-policy.json with the following content:
“Version”: “2012-10-17”,
“Statement”: [
{
“Effect”: “Allow”,
“Principal”: {
“Service”: “lambda.amazonaws.com”
},
“Action”: “sts:AssumeRole”
}
]
}
2 – Create the IAM role using the AWS CLI:
3 – Attach the AWSLambdaBasicExecutionRole policy to the role:
Step 2: Create the Lambda Function with Go
1 – Write your Go code. For this tutorial, let’s create a simple function that logs a message. Create a file named main.go:
import (
“github.com/aws/aws-lambda-go/lambda”
“log”
)
func handler() {
log.Println(“Lambda function invoked!”)
}
func main() {
lambda.Start(handler)
}
2 – Build the Go binary for Linux:
3 – Zip the binary:
4 – Create the Lambda function using the AWS CLI:
–zip-file fileb://function.zip –handler bootstrap
–runtime provided.al2 –role arn:aws:iam::AWS-ID:role/lambda-execute-role
Step 3: Create a CloudWatch Event Rule
1 – Create a CloudWatch Event rule to trigger the Lambda function once a day:
2 – Add permission for CloudWatch to invoke your Lambda function:
–statement-id DailyTrigger –action ‘lambda:InvokeFunction’
–principal events.amazonaws.com –source-arn arn:aws:events:us-east-1:AWS-ID:rule/DailyTrigger
3 – Add the Lambda function as a target to the CloudWatch rule:
Step 4: Verify the Setup
1 – Manually invoke the Lambda function to ensure it’s working correctly:
Check the contents of out.txt for any errors or output from your Lambda function.
2 – Check CloudWatch Logs to see if the log group has been created and logs are available:
If the log group does not exist, it might mean the function hasn’t run yet. After manually invoking the function, the log group should be created, and you can check the logs again.
Conclusion
You now have a Lambda function written in Go that runs once a day, triggered by a CloudWatch Event rule. This setup is useful for running scheduled tasks without needing to manage a server.
Feel free to extend this tutorial with more complex logic in your Go function or add more CloudWatch rules for different schedules.