0
votes

Is it possible in terraform to retrieve the first file with a name matching some regex in either the current directory, or any parent directory?

For example, I would want it to first check for config.json in the current directory. If it exists, it stops. If it doesn't, it checks for ../config.json, then ../../config.json, etc.

.
├── directory1
│   ├── subdirectory1
│   │   └── main.tf
│   └── config.json
└── directory2
    └── config.json

In this example, it should return directory1/config.json. I would then want to use jsondecode to parse some value in this configuration file and assign it to a variable.

The closest functionality I've seen to this is fileset, but I don't think it can be used to solve this problem.

1
I think you have the right idea. You could use your regex with fileset to return a list of all matches, and then return the first element from the list assuming it meets the criteria you want. The return behavior seems to be parent directory versus child, and normal alphanumeric sorting.Matt Schuchard

1 Answers

0
votes

I acutally did something similar quite recently.

Select the first file of a chain, which is present:

output "first_match" {
    value = try(
            tolist(fileset(path.module, "file1"))[0], 
            tolist(fileset(path.module, "folder/file2"))[0], 
            tolist(fileset(path.module, "folder/folder/file3"))[0], 
            "default if nothing matches")
}