问题
this is not a module just a workspace
folder structure:
workspace1
- workspace2
- workspace3
- workspace4
- workspace5
If I CD into workspace for the full path is: /Users/me/my-files/terraform/workspace1/workspace3/workspace4
How can I use terraform functions to be able to get just the path workspace1/workspace3/workspace4
Is there a way I can get the full path (https://www.terraform.io/docs/configuration/functions/abspath.html) and then trim out everything before workspace1? perhaps replace() can do that? There are many more features in the latest tf version though I want to check there isnt a feature that makes this easy I could not find in the docs
# trying to use capture groups doesnt seem to work (just outputs full path)
locals {
test = replace(
abspath(path.root),
"/(.*)(workspace1.*)",
"$2"
)
}
output "test" { value = "${local.test}"
edit this match should work but its not supported:
test = replace(
abspath(path.root),
"/.+?(?=workspace1)/",
"$1"
unsupported Perl syntax: `(?=`.
回答1:
Assuming there aren't any complications like symlinks to make the problem more "interesting", perhaps you could do it by using abspath
both on path.module
and on a relative path from there to your codebase root and then use the length of the latter to trim the former. For example:
locals {
module_path = abspath(path.module)
codebase_root_path = abspath("${path.module}/../..")
# Trim local.codebase_root_path and one additional slash from local.module_path
module_rel_path = substr(local.module_path, length(local.codebase_root_path)+1, length(local.module_path))
}
In the above I'm assuming that the current module is two nesting levels under the codebase root, and using that to discover the absolute path of the codebase root in order to trim it off the absolute module path.
回答2:
This works I think i had the syntax wrong:
#Folder structure
#workspace1
# - workspace2
# - workspace3
# - workspace4
# - workspace5
#abs path on disk: /Users/me/my-files/terraform/workspace1/workspace3/workspace4
locals {
test = replace(
abspath(path.root),
"/.+?(workspace1.*)/",
"$1"
)
}
output "test" { value = "${local.test}" }
来源:https://stackoverflow.com/questions/59637486/how-can-i-get-the-relative-path-of-the-current-director-up-to-an-arbitrary-paren