Skip to content

Instantly share code, notes, and snippets.

@IgorDePaula
Created October 23, 2025 22:38
Show Gist options
  • Save IgorDePaula/0f5d84cdf683582091138b95f626cd82 to your computer and use it in GitHub Desktop.
Save IgorDePaula/0f5d84cdf683582091138b95f626cd82 to your computer and use it in GitHub Desktop.
Cria lambda com ecr no terraform
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "5.82.1"
}
}
}
// Used by get the current aws number account.
data "aws_caller_identity" "current" {
}
resource "aws_ecr_repository" "noiselesstech" {
name = "noiselesstech"
force_delete = true
image_scanning_configuration {
scan_on_push = true
}
}
resource "aws_ecr_lifecycle_policy" "default_policy" {
repository = aws_ecr_repository.noiselesstech.name
policy = <<EOF
{
"rules": [
{
"rulePriority": 1,
"description": "Keep only the last ${var.untagged_images} untagged images.",
"selection": {
"tagStatus": "untagged",
"countType": "imageCountMoreThan",
"countNumber": ${var.untagged_images}
},
"action": {
"type": "expire"
}
}
]
}
EOF
}
resource "null_resource" "docker_packaging" {
provisioner "local-exec" {
command = <<EOF
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin ${data.aws_caller_identity.current.account_id}.dkr.ecr.us-east-1.amazonaws.com
docker build -t "${aws_ecr_repository.noiselesstech.repository_url}:latest" -f Dockerfile .
docker push "${aws_ecr_repository.noiselesstech.repository_url}:latest"
EOF
}
triggers = {
"run_at" = timestamp()
}
depends_on = [
aws_ecr_repository.noiselesstech,
]
}
variable "untagged_images" {
default = 3
}
resource "aws_lambda_function" "profile_faker_function" {
function_name = "profile-faker-dev"
timeout = 5 # seconds
image_uri = "${aws_ecr_repository.noiselesstech.repository_url}:latest"
package_type = "Image"
role = aws_iam_role.api_function_role.arn
environment {
variables = {
ENVIRONMENT = "dev"
}
}
}
data "aws_iam_policy_document" "policy-document" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["lambda.amazonaws.com"]
}
}
}
resource "aws_iam_role" "api_function_role" {
name = "lambda_iam_role"
assume_role_policy = data.aws_iam_policy_document.policy-document.json
}
resource "aws_iam_role_policy_attachment" "basic" {
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
role = aws_iam_role.api_function_role.name
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment