1
votes

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
If you are definitely unable to switch to Terraform 0.12 and are thus only interested in 0.11 answers then you should tag your question with terraform0.11. If not then you should remove the 0.11 references and accept the current answer.ydaetskcoR

2 Answers

1
votes

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

1
votes

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
  }
}