This post will show you How to Deploy Serverless Applications using Terraform Easily with step by step procedure..
If you are interested in learning, Request you to go through the below recommended tutorial.
DevOps Full Course Tutorial for Beginners - DevOps Free Training OnlineDocker Full Course Tutorial for Beginners - Docker Free Training Online
Kubernetes Full Course Tutorial for Beginners - Kubernetes Free Training Online
Ansible Full Course Tutorial for Beginners - Ansible Free Training Online
Openstack Full Course Tutorial for Beginners - Openstack Free Training Online
Let's Get Started.
How to Deploy Serverless Application using Terraform
In order to deploy a serverless applications using Terraform, you will need to have Terraform installed on your local machine and have access to an AWS account.
1. Create a new directory for your Terraform project and navigate to it.
2. In the project directory, create a new file named main.tf and add the following code to it:
provider "aws" {
region = "us-east-1"
}
resource "aws_lambda_function" "example_function" {
function_name = "example_function"
runtime = "nodejs12.x"
handler = "index.handler"
role = "${aws_iam_role.example_role.arn}"
code = {
s3_bucket = "example_bucket"
s3_key = "example_key"
}
}
resource "aws_iam_role" "example_role" {
name = "example_role"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
EOF
}
resource "aws_iam_policy" "example_policy" {
name = "example_policy"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:*"
],
"Resource": "arn:aws:logs:*:*:*"
}
]
}
EOF
}
resource "aws_iam_role_policy_attachment" "example_attachment" {
role = "${aws_iam_role.example_role.name}"
policy_arn = "${aws_iam_policy.example_policy.arn}"
}
3. In the same project directory, create a new file named variables.tf and add the following code to it:
variable "s3_bucket" {
default = "example_bucket"
}
variable "s3_key" {
default = "example_key"
}
4. In the same project directory, create a new file named terraform.tfvars and add the following code to it:
s3_bucket = "example_bucket"
s3_key = "example_key"
5. Run the following command to initialize Terraform:
terraform init
6. Run the following command to create a plan for the resources to be created:
terraform plan
7. Run the following command to apply the plan and create the resources:
terraform apply
8. Verify that the resources have been created in the AWS Management Console.
9. To update the resources, make changes to the main.tf file and rerun the terraform plan and terraform apply commands.
0 Comments