Introduction#
Github this is day 1 learning terraform
- Install terraform
- Run nginx
- Create a lambda function
Install terraform#
Download the binary for linux and update the PATH
wget https://releases.hashicorp.com/terraform/1.3.4/terraform_1.3.4_linux_386.zip
or install from cli
https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli
update the PATH
export PATH=/home/ec2-user/workspace/terraform:$PATH
check
terraform -help
Run Nginx#
terraform {required_providers {docker = {source = "kreuzwerker/docker"version = "~> 2.13.0"}}}provider "docker" {}resource "docker_image" "nginx" {name = "nginx:latest"keep_locally = false}resource "docker_container" "nginx" {image = docker_image.nginx.latestname = "tutorial"ports {internal = 80external = 8000}}
then run
terraform init
and apply
terraform apply
need SSH port forwarding (either using vscode or from terminal)
ssh -L 8000:localhost:8000 ec2-user@ssm-vscode
then open browser from your local machine localhost:8000 and shoud see the nginx running
Create a Lambda in Terraform#
create a bucket to store the lambda source code and dependencies
resource "random_pet" "lambda_bucket_name" {prefix = "learn-terraform-functions"length = 4}resource "aws_s3_bucket" "lambda_bucket" {bucket = random_pet.lambda_bucket_name.idforce_destroy = true}
s3 object which store the lambda source code and dependencies
resource "aws_s3_object" "lambda_hello_world" {bucket = aws_s3_bucket.lambda_bucket.idkey = "hello-world.zip"source = data.archive_file.lambda_hello_world.output_pathetag = filemd5(data.archive_file.lambda_hello_world.output_path)}
create a lambda function
resource "aws_lambda_function" "hello_world" {function_name = "HelloWorld"s3_bucket = aws_s3_bucket.lambda_bucket.ids3_key = aws_s3_object.lambda_hello_world.keyruntime = "nodejs12.x"handler = "hello.handler"source_code_hash = data.archive_file.lambda_hello_world.output_base64sha256role = aws_iam_role.lambda_exec.arn}
lambda function role
resource "aws_iam_role" "lambda_exec" {name = "serverless_lambda"assume_role_policy = jsonencode({Version = "2012-10-17"Statement = [{Action = "sts:AssumeRole"Effect = "Allow"Sid = ""Principal = {Service = "lambda.amazonaws.com"}}]})}
add policy for the lambda role
resource "aws_iam_role_policy_attachment" "lambda_policy" {role = aws_iam_role.lambda_exec.namepolicy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"}
Troubleshooting#
might need to downgrade to aws 4.0.0 for compatible or check how to create a S3 in the newest aws terraform Version 4 S3 Bucket Refactor
terraform {required_providers {aws = {source = "hashicorp/aws"version = "~> 4.0.0"}}