Last active
November 14, 2021 17:45
-
-
Save abiydv/cb686fa6ce978f74823f4f3dc5e94c20 to your computer and use it in GitHub Desktop.
Terraform for each conditionals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is an example to bulk upload files to S3 | |
# A local source directory and sample pattern are provided as variables. | |
# All matching files are uploaded to S3 | |
locals { | |
file_list = toset(fileset(var.source_path, var.source_file_pattern)) | |
# If you use terragrunt, use this local block instead to ignore | |
# the .terragrunt-source-manifest file it adds to each directory. | |
# This is useful if there is no common pattern to files. | |
file_list = toset([for k in toset(fileset(var.source_path, var.source_file_pattern)) : k if length(regexall(".*terragrunt.*", k)) == 0]) | |
} | |
variable "s3_bucket" { | |
description = "S3 bucket to upload the files to" | |
} | |
variable "s3_key" { | |
description = "Sub-directory on S3 to upload the files to" | |
} | |
variable "source_path" { | |
description = "Source directory on local to watch for files to upload" | |
} | |
variable "source_file_pattern" { | |
description = "Pattern to match for files" | |
} | |
resource "aws_s3_bucket_object" "this" { | |
for_each = local.file_list | |
bucket = var.s3_bucket | |
key = format("%s/%s", var.s3_key, each.key) | |
source = format("%s/%s", var.source_path, each.key) | |
etag = filemd5(format("%s/%s", var.source_path, each.key)) | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is an example to upload files to S3 "conditionally" | |
# A list of files is in the local variable files_list. | |
# If the file exists on disk, it's uploaded, otherwise | |
# terraform skips to the next item in files_list. | |
locals { | |
files_list = toset(["file1.txt", "file2.txt", "file3.txt"]) | |
} | |
variable "s3_bucket" { | |
description = "S3 bucket to upload the files to" | |
} | |
variable "s3_key" { | |
description = "Sub-directory on S3 to upload the files to" | |
} | |
variable "source_path" { | |
description = "Source directory on local to watch for files to upload" | |
} | |
resource "aws_s3_bucket_object" "this" { | |
for_each = toset([for k in local.files_list : k if fileexists("${path.module}/${k}")]) | |
bucket = var.s3_bucket | |
key = format("%s/%s", var.s3_key, each.key) | |
source = format("%s/%s", var.source_path, each.key) | |
etag = filemd5(format("%s/%s", var.source_path, each.key)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment