Last active
September 17, 2022 07:57
-
-
Save xbalaji/f3b73340693ac690f38fbf02091588dc to your computer and use it in GitHub Desktop.
terraform-external-data-oneliner.tf
This file contains hidden or 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
# from https://gist.github.com/alastairmccormack/a8c290738145f1c94a86029aca66cb8e | |
# branch name accessible via: ${data.external.git-branch.result.branch} | |
data "external" "git-branch" { | |
program = ["/bin/bash", "-c", "jq -n --arg branch `git rev-parse --abbrev-ref HEAD` '{\"branch\":$branch}'"] | |
} | |
# https://stackoverflow.com/questions/70950150/how-to-use-an-aws-cli-command-in-a-terraform-external-data-source | |
data "external" "json" { | |
program = ["sh", "-c", "aws cloudfront list-cloud-front-origin-access-identities | jq -r ' .CloudFrontOriginAccessIdentityList.Items[] | select(.Comment == \"Created for Nackle Shared CF in pprd\") | {id: .Id}'"] | |
} | |
output "jsonid" { | |
value = data.external.json.result["id"] | |
} | |
# tf external data onliner to check if bucket exists | |
# if [[ $(aws s3api head-bucket --bucket $1 2>&1 || true) ]]; then echo '{\"exists\": \"0\"}'; else echo '{\"exists\": \"1\"}'; fi | |
# | |
# invoke as: terraform plan -var bucket=<bucket-to-check> | |
variable "bucket" { | |
type = string | |
} | |
data "external" "bucket" { | |
program = ["bash", "-c", "if [[ $(aws s3api head-bucket --bucket `jq -rM '.bucket'` 2>&1 || true) ]]; then echo '{\"exists\": \"0\"}'; else echo '{\"exists\": \"1\"}'; fi"] | |
query = { | |
bucket = var.bucket | |
} | |
} | |
output "bucket-status" { | |
value = data.external.bucket.result["exists"] | |
} | |
locals { | |
bucket_exists = data.external.bucket.result["exists"] == "1" ? 1 : 0 | |
} | |
output "bucket-flag" { | |
value = local.bucket_exists | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment