Deploy resources only if a file exists in Terraform

7.9k Views Asked by At

I have a requirement where I have to deploy resources only if a certain file exists at a certain location otherwise it will skip the resource.

Like here is the code to deploy a certain identity provider in certain AWS accounts. Along with this identity provider (say abc) many other identity providers are also deployed from the same main.tf file so all has to be here. The only challenge is while deploying the IAM layer for any accounts we will only deploy this certain resource only if abc-${var.aws_account}.xml file exists in the filepath in
saml_metadata_document part. If it does not exists in the path it will simply ignore the resource creation and will go ahead with the rest of the code.

resource "aws_iam_saml_provider" "xyz" {
    name                   = "abc-${var.aws_account}"
    saml_metadata_document =  "${file("${path.module}/metadata/abc-${var.aws_account}.xml")}"
}

Folder Structure

IAM-Module
  |
  main.tf
  variables.tf
  metadata
     |
     abc-127367223.xml
     abc-983297832.xml
     abc-342374384.xml

How can a conditional check be put in Terraform 0.11 to check the file exists?

2

There are 2 best solutions below

0
On

If it is allowed. Instead of existence of the file, use the file size. If file size is zero, then do not create a resource, otherwise create.

data "local_file" "hoge" {
  filename = "${path.module}/hoge"
}

resource "null_resource" "hoge" {
  count = length(data.local_file.hoge.content) > 0 ? 1 : 0

  provisioner "local-exec" {
    command = <<EOF
cat "${path.module}/${data.local_file.hoge.filename}"
EOF
  }
}
9
On

count can be used to create an array of resources instead of just a single resource, so setting count = 0 will create an array of resources of length 0, effectively disabling the resource.

resource "aws_iam_saml_provider" "xyz" { 
   name = "abc-${var.aws_account}" 
   saml_metadata_document = "${file("${path.module}/metadata/abc-${var.aws_account}.xml")}" 
   count = fileexists("${path.module}/metadata/abc-${var.aws_account}.xml") ? 1 : 0
}

NOTE You will need access to fileexists which only exists in 0.12