Documentation
¶
Overview ¶
Package util provides utility functions for Terragrunt.
Index ¶
- Constants
- func AsTerraformEnvVarJSONValue(value any) (string, error)
- func CanonicalPath(path string, basePath string) (string, error)
- func CanonicalPaths(paths []string, basePath string) ([]string, error)
- func CleanPath(path string) string
- func CleanString(s string) string
- func CommaSeparatedStrings(list []string) string
- func CompileGlobs(basePath string, globPaths ...string) (map[string]glob.Glob, error)
- func ContainsPath(path, subpath string) bool
- func Copy(ctx context.Context, dst io.Writer, src io.Reader) (int64, error)
- func CopyFile(source string, destination string) error
- func CopyFolderContents(logger log.Logger, source, destination, manifestFile string, ...) error
- func CopyFolderContentsWithFilter(logger log.Logger, source, destination, manifestFile string, ...) error
- func DirContainsTFFiles(dirPath string) (bool, error)
- func DoWithRetry(ctx context.Context, actionDescription string, maxRetries int, ...) error
- func EncodeBase64Sha1(str string) string
- func EnsureDirectory(path string) error
- func ExcludeFiltersFromFile(baseDir, filename string) ([]string, error)
- func FileExists(path string) bool
- func FileNotExists(path string) bool
- func FileOrData(maybePath string) (string, error)
- func FileSHA256(filePath string) ([]byte, error)
- func FindTFFiles(rootPath string) ([]string, error)
- func FirstElement[S ~[]E, E comparable](list S) E
- func GenerateRandomSha256() (string, error)
- func GetCacheDir() (string, error)
- func GetElement[S ~[]E, E comparable](list S, index int) E
- func GetExitCode(err error) (int, error)
- func GetFiltersFromFile(baseDir, filename string) ([]string, error)
- func GetPathRelativeTo(path string, basePath string) (string, error)
- func GetRandomTime(lowerBound, upperBound time.Duration) time.Duration
- func GetTempDir() (string, error)
- func GlobCanonicalPath(l log.Logger, basePath string, globPaths ...string) ([]string, error)
- func Grep(regex *regexp.Regexp, glob string) (bool, error)
- func HasPathPrefix(path, prefix string) bool
- func IsCommandExecutable(ctx context.Context, command string, args ...string) bool
- func IsDir(path string) bool
- func IsDirectoryEmpty(dirPath string) (bool, error)
- func IsFile(path string) bool
- func IsSymLink(path string) bool
- func IsTFFile(path string) bool
- func JoinTerraformModulePath(modulesFolder string, path string) string
- func KindOf(value any) reflect.Kind
- func LastElement[S ~[]E, E comparable](list S) E
- func ListContainsSublist[S ~[]E, E comparable](list, sublist S) bool
- func ListHasPrefix[S ~[]E, E comparable](list, prefix S) bool
- func ListTfFiles(directoryPath string, walkWithSymlinks bool) ([]string, error)
- func MatchSha256Checksum(file, filename []byte) []byte
- func MatchesAny(regExps []string, s string) bool
- func MergeStringSlices(a, b []string) []string
- func Min(x, y int) int
- func MoveFile(source string, destination string) error
- func MustWalkTerraformOutput(value any, path ...string) any
- func NewFileManifest(logger log.Logger, manifestFolder string, manifestFile string) *fileManifest
- func ParseTimestamp(ts string) (time.Time, error)
- func PrefixedWriter(writer io.Writer, prefix string) io.Writer
- func ReadFileAsString(path string) (string, error)
- func RegexFoundInTFFiles(workingDir string, pattern *regexp.Regexp) (bool, error)
- func RemoveDuplicatesFromList[S ~[]E, E comparable](list S) S
- func RemoveDuplicatesFromListKeepLast[S ~[]E, E comparable](list S) S
- func RemoveElementFromList[S ~[]E, E comparable](list S, element E) S
- func RemoveEmptyElements[S ~[]E, E comparable](list S) S
- func RemoveSublistFromList[S ~[]E, E comparable](list, sublist S) S
- func SanitizePath(baseDir string, file string) (string, error)
- func SecondElement[S ~[]E, E comparable](list S) E
- func SplitComma(s, sep string) []string
- func SplitPath(path string) []string
- func SplitUrls(s, sep string) []string
- func TerragruntExcludes(path string) bool
- func UniqueID() string
- func WalkDirWithSymlinks(root string, externalWalkFn fs.WalkDirFunc) error
- func WriteFileWithSamePermissions(source string, destination string, contents []byte) error
- func WriterNotifier(writer io.Writer, notifyFn func(p []byte)) io.Writer
- type CmdOutput
- type FatalError
- type KeyLocks
- type Lockfile
- type MaxRetriesExceeded
- type PathIsNotDirectory
- type PathIsNotFile
- type ProcessExecutionError
- type TrapWriter
Constants ¶
const ( TerraformLockFile = ".terraform.lock.hcl" TerragruntCacheDir = ".terragrunt-cache" DefaultBoilerplateDir = ".boilerplate" TfFileExtension = ".tf" ChecksumReadBlock = 8192 )
const Base62Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
const UniqueIDLength = 6 // Should be good for 62^6 = 56+ billion combinations
Variables ¶
This section is empty.
Functions ¶
func AsTerraformEnvVarJSONValue ¶ added in v0.67.7
AsTerraformEnvVarJSONValue converts the given value to a JSON value that can be passed to Terraform as an environment variable. For the most part, this converts the value directly to JSON using Go's built-in json.Marshal. However, we have special handling for strings, which with normal JSON conversion would be wrapped in quotes, but when passing them to Terraform via env vars, we need to NOT wrap them in quotes, so this method adds special handling for that case.
func CanonicalPath ¶ added in v0.6.0
CanonicalPath returns the canonical version of the given path, relative to the given base path. That is, if the given path is a relative path, assume it is relative to the given base path. A canonical path is an absolute path with all relative components (e.g. "../") fully resolved, which makes it safe to compare paths as strings.
func CanonicalPaths ¶ added in v0.6.0
CanonicalPaths returns the canonical version of the given paths, relative to the given base path. That is, if a given path is a relative path, assume it is relative to the given base path. A canonical path is an absolute path with all relative components (e.g. "../") fully resolved, which makes it safe to compare paths as strings.
func CleanPath ¶ added in v0.9.0
CleanPath is a wrapper around filepath.Clean.
Use this function when cleaning paths to ensure the returned path uses / as the path separator to improve cross-platform compatibility
func CleanString ¶ added in v0.78.0
CleanString normalizes line endings across different platforms.
func CommaSeparatedStrings ¶ added in v0.12.17
CommaSeparatedStrings returns an HCL compliant formatted list of strings (each string within double quote)
func CompileGlobs ¶ added in v0.86.1
func ContainsPath ¶ added in v0.23.24
ContainsPath returns true if path contains the given subpath E.g. path="foo/bar/bee", subpath="bar/bee" -> true E.g. path="foo/bar/bee", subpath="bar/be" -> false (because be is not a directory)
func CopyFolderContents ¶ added in v0.9.4
func CopyFolderContents( logger log.Logger, source, destination, manifestFile string, includeInCopy []string, excludeFromCopy []string, ) error
CopyFolderContents copies the files and folders within the source folder into the destination folder. Note that hidden files and folders (those starting with a dot) will be skipped. Will create a specified manifest file that contains paths of all copied files.
func CopyFolderContentsWithFilter ¶ added in v0.19.0
func CopyFolderContentsWithFilter(logger log.Logger, source, destination, manifestFile string, filter func(absolutePath string) bool) error
CopyFolderContentsWithFilter copies the files and folders within the source folder into the destination folder.
func DirContainsTFFiles ¶ added in v0.88.1
DirContainsTFFiles checks if the given directory contains any Terraform/OpenTofu files (.tf, .tofu, .tf.json, .tofu.json)
func DoWithRetry ¶ added in v0.19.0
func DoWithRetry(ctx context.Context, actionDescription string, maxRetries int, sleepBetweenRetries time.Duration, logger log.Logger, logLevel log.Level, action func(ctx context.Context) error) error
DoWithRetry runs the specified action. If it returns a value, return that value. If it returns an error, sleep for sleepBetweenRetries and try again, up to a maximum of maxRetries retries. If maxRetries is exceeded, return a MaxRetriesExceeded error.
func EncodeBase64Sha1 ¶ added in v0.9.7
EncodeBase64Sha1 Returns the base 64 encoded sha1 hash of the given string
func EnsureDirectory ¶ added in v0.24.3
EnsureDirectory creates a directory at this path if it does not exist, or error if the path exists and is a file.
func ExcludeFiltersFromFile ¶ added in v0.97.0
ExcludeFiltersFromFile returns a list of filters from the given filename, where each filter starts on a new line.
Note that this is a backwards compatibility implementation for the `--queue-excludes-file` flag, so it's going to append the ! prefix to each filter to negate it.
func FileExists ¶
FileExists returns true if the given file exists.
func FileNotExists ¶ added in v0.21.6
FileNotExists returns true if the given file does not exist.
func FileOrData ¶ added in v0.31.0
FileOrData will read the contents of the data of the given arg if it is a file, and otherwise return the contents by itself. This will return an error if the given path is a directory.
func FileSHA256 ¶ added in v0.64.3
FileSHA256 calculates the SHA256 hash of the file at the given path.
func FindTFFiles ¶ added in v0.88.1
FindTFFiles walks through the directory and returns all OpenTofu/Terraform files (.tf, .tofu, .tf.json, .tofu.json)
func FirstElement ¶ added in v0.73.0
func FirstElement[S ~[]E, E comparable](list S) E
FirstElement returns the first element from the given `list`.
func GenerateRandomSha256 ¶ added in v0.38.4
func GetCacheDir ¶ added in v0.56.4
GetCacheDir returns the global terragrunt cache directory for the current user.
func GetElement ¶ added in v0.73.0
func GetElement[S ~[]E, E comparable](list S, index int) E
GetElement returns the element with the specified `index` from the given `list`. if `index` is -1, the last element is returned.
func GetExitCode ¶ added in v0.62.0
GetExitCode returns the exit code of a command. If the error does not implement errorCode or is not an exec.ExitError or *errors.MultiError type, the error is returned.
func GetFiltersFromFile ¶ added in v0.96.0
GetFiltersFromFile returns a list of filter queries from the given filename, where each filter query starts on a new line.
func GetPathRelativeTo ¶ added in v0.4.0
GetPathRelativeTo returns the relative path you would have to take to get from basePath to path.
func GetRandomTime ¶ added in v0.6.4
GetRandomTime gets a random time duration between the lower bound and upper bound. This is useful because some of our automated tests wound up flooding the AWS API all at once, leading to a "Subscriber limit exceeded" error. TODO: Some of the more exotic test cases fail, but it's not worth catching them given the intended use of this function.
func GetTempDir ¶ added in v0.58.7
GetTempDir returns the global terragrunt temp directory.
func GlobCanonicalPath ¶ added in v0.50.1
GlobCanonicalPath returns the canonical versions of the given glob paths, relative to the given base path.
func Grep ¶
Grep returns true if the given regex can be found in any of the files matched by the given glob.
func HasPathPrefix ¶ added in v0.23.24
HasPathPrefix returns true if path starts with the given path prefix E.g. path="/foo/bar/biz", prefix="/foo/bar" -> true E.g. path="/foo/bar/biz", prefix="/foo/ba" -> false (because ba is not a directory path)
func IsCommandExecutable ¶ added in v0.52.0
IsCommandExecutable - returns true if a command can be executed without errors.
func IsDirectoryEmpty ¶ added in v0.54.0
IsDirectoryEmpty - returns true if the given path exists and is a empty directory.
func IsSymLink ¶ added in v0.19.0
IsSymLink returns true if the given file is a symbolic link Per https://stackoverflow.com/a/18062079/2308858
func IsTFFile ¶ added in v0.88.1
IsTFFile checks if a given file is a Terraform/OpenTofu file (.tf, .tofu, .tf.json, .tofu.json)
func JoinTerraformModulePath ¶ added in v0.13.13
JoinTerraformModulePath joins two paths together with a double-slash between them, as this is what Terraform uses to identify where a "repo" ends and a path within the repo begins. Note: The Terraform docs only mention two forward-slashes, so it's not clear if on Windows those should be two back-slashes? https://www.terraform.io/docs/modules/sources.html
func LastElement ¶ added in v0.73.0
func LastElement[S ~[]E, E comparable](list S) E
LastElement returns the last element from the given `list`.
func ListContainsSublist ¶ added in v0.23.24
func ListContainsSublist[S ~[]E, E comparable](list, sublist S) bool
ListContainsSublist returns true if an instance of the sublist can be found in the given list
func ListHasPrefix ¶ added in v0.23.24
func ListHasPrefix[S ~[]E, E comparable](list, prefix S) bool
ListHasPrefix returns true if list starts with the given prefix list
func ListTfFiles ¶ added in v0.54.0
ListTfFiles returns a list of all TF files in the specified directory.
func MatchSha256Checksum ¶ added in v0.64.3
MatchSha256Checksum returns the SHA256 checksum for the given file and filename.
func MatchesAny ¶ added in v0.17.0
func MergeStringSlices ¶ added in v0.69.6
MergeStringSlices combines two string slices removing duplicates
func MoveFile ¶ added in v0.85.1
MoveFile attempts to rename a file from source to destination, if this fails due to invalid cross-device link it falls back to copying the file contents and deleting the original file.
func MustWalkTerraformOutput ¶ added in v0.36.2
MustWalkTerraformOutput is a helper utility to deeply return a value from a terraform output.
nil will be returned if the path is invalid
Using an example terraform output:
a = {
b = {
c = "foo"
}
"d" = [
1,
2
]
}
path ["a", "b", "c"] will return "foo"
path ["a", "d", "1"] will return 2
path ["a", "foo"] will return nil
func NewFileManifest ¶ added in v0.66.7
func PrefixedWriter ¶ added in v0.45.1
func ReadFileAsString ¶ added in v0.4.0
ReadFileAsString returns the contents of the file at the given path as a string.
func RegexFoundInTFFiles ¶ added in v0.88.1
RegexFoundInTFFiles walks through the directory and checks if any OpenTofu/Terraform files (.tf, .tofu, .tf.json, .tofu.json) contain the given regex pattern
func RemoveDuplicatesFromList ¶ added in v0.12.11
func RemoveDuplicatesFromList[S ~[]E, E comparable](list S) S
RemoveDuplicatesFromList returns a copy of the given list with all duplicates removed (keeping the first encountereds)
func RemoveDuplicatesFromListKeepLast ¶ added in v0.12.11
func RemoveDuplicatesFromListKeepLast[S ~[]E, E comparable](list S) S
RemoveDuplicatesFromListKeepLast returns a copy of the given list with all duplicates removed (keeping the last encountereds)
func RemoveElementFromList ¶ added in v0.6.0
func RemoveElementFromList[S ~[]E, E comparable](list S, element E) S
RemoveElementFromList returns a copy of the given list with all instances of the given element removed.
func RemoveEmptyElements ¶ added in v0.73.0
func RemoveEmptyElements[S ~[]E, E comparable](list S) S
RemoveEmptyElements returns a copy of the given list without empty elements.
func RemoveSublistFromList ¶ added in v0.56.4
func RemoveSublistFromList[S ~[]E, E comparable](list, sublist S) S
RemoveSublistFromList returns a copy of the given list with all instances of the given sublist removed
func SanitizePath ¶ added in v0.82.3
SanitizePath resolves a file path within a base directory, returning the sanitized path or an error if it attempts to access anything outside the base directory.
func SecondElement ¶ added in v0.73.0
func SecondElement[S ~[]E, E comparable](list S) E
SecondElement returns the second element from the given `list`.
func SplitComma ¶ added in v0.68.9
SplitComma splits the given string by comma and returns a slice of the substrings.
func SplitPath ¶ added in v0.23.24
SplitPath splits the given path into a list. E.g. "foo/bar/boo.txt" -> ["foo", "bar", "boo.txt"] E.g. "/foo/bar/boo.txt" -> ["", "foo", "bar", "boo.txt"] Notice that if path is absolute the resulting list will begin with an empty string.
func SplitUrls ¶ added in v0.46.2
SplitUrls slices s into all substrings separated by sep and returns a slice of the substrings between those separators. Taking into account that the `=` sign can also be used as a git tag, e.g. `git@github.com/test.git?ref=feature`
func TerragruntExcludes ¶ added in v0.27.0
func UniqueID ¶ added in v0.67.7
func UniqueID() string
UniqueID returns a unique (ish) id we can use to name resources so they don't conflict with each other. Uses base 62 to generate a 6 character string that's unlikely to collide with the handful of tests we run in parallel. Based on code here:
http://stackoverflow.com/a/9543797/483528
func WalkDirWithSymlinks ¶ added in v0.87.2
func WalkDirWithSymlinks(root string, externalWalkFn fs.WalkDirFunc) error
WalkDirWithSymlinks traverses a directory tree using filepath.WalkDir, following symbolic links and calling the provided function for each file or directory encountered. It handles both regular symlinks and circular symlinks without getting into infinite loops.
func WriteFileWithSamePermissions ¶ added in v0.9.4
WriteFileWithSamePermissions writes a file to the given destination with the given contents using the same permissions as the file at source.
Types ¶
type FatalError ¶ added in v0.50.9
type FatalError struct {
Underlying error
}
FatalError is error interface for cases that should not be retried.
func (FatalError) Error ¶ added in v0.50.9
func (err FatalError) Error() string
func (FatalError) Unwrap ¶ added in v0.77.10
func (err FatalError) Unwrap() error
type KeyLocks ¶ added in v0.58.4
type KeyLocks struct {
// contains filtered or unexported fields
}
KeyLocks manages a map of locks, each associated with a string key.
func NewKeyLocks ¶ added in v0.58.4
func NewKeyLocks() *KeyLocks
NewKeyLocks creates a new instance of KeyLocks.
type Lockfile ¶ added in v0.56.4
func NewLockfile ¶ added in v0.56.4
type MaxRetriesExceeded ¶ added in v0.19.0
MaxRetriesExceeded is an error that occurs when the maximum amount of retries is exceeded.
func (MaxRetriesExceeded) Error ¶ added in v0.19.0
func (err MaxRetriesExceeded) Error() string
type PathIsNotDirectory ¶ added in v0.24.3
type PathIsNotDirectory struct {
// contains filtered or unexported fields
}
PathIsNotDirectory is returned when the given path is unexpectedly not a directory.
func (PathIsNotDirectory) Error ¶ added in v0.24.3
func (err PathIsNotDirectory) Error() string
type PathIsNotFile ¶ added in v0.31.0
type PathIsNotFile struct {
// contains filtered or unexported fields
}
PathIsNotFile is returned when the given path is unexpectedly not a file.
func (PathIsNotFile) Error ¶ added in v0.31.0
func (err PathIsNotFile) Error() string
type ProcessExecutionError ¶ added in v0.62.0
type ProcessExecutionError struct {
Err error
WorkingDir string
Command string
Args []string
Output CmdOutput
DisableSummary bool
}
ProcessExecutionError - error returned when a command fails, contains StdOut and StdErr
func (ProcessExecutionError) Error ¶ added in v0.62.0
func (err ProcessExecutionError) Error() string
func (ProcessExecutionError) ExitStatus ¶ added in v0.62.0
func (err ProcessExecutionError) ExitStatus() (int, error)
func (ProcessExecutionError) Unwrap ¶ added in v0.68.0
func (err ProcessExecutionError) Unwrap() error
type TrapWriter ¶ added in v0.56.4
type TrapWriter struct {
// contains filtered or unexported fields
}
TrapWriter intercepts any messages received from the `writer` output. Used when necessary to filter logs from terraform.
func NewTrapWriter ¶ added in v0.56.4
func NewTrapWriter(writer io.Writer) *TrapWriter
NewTrapWriter returns a new TrapWriter instance.
func (*TrapWriter) Flush ¶ added in v0.69.2
func (trap *TrapWriter) Flush() error
Flush flushes intercepted messages to the writer.