Skip to main content

Config file

Infracost uses config files to help manage multiple Terraform projects within a repo, especially when dealing with complex setups like monorepos or Terragrunt repos. Config files also help define how projects map to Terraform var files so that Infracost knows how to apply them.

The Infracost team writes and manages config files for customers and companies doing a PoC with Infracost Cloud, please email us at hello@infracost.io for details.

Overview​

By default, Infracost attempts to automatically detect the projects in your repository when you run infracost scan. This works for many cases, but for more complex repositories, you may need to adjust the detection process to ensure the right projects and configurations are included. The auto-detected projects are reported as part of the scan output; running infracost scan --json (or infracost inspect --json) shows the full project list the CLI used.

If auto-detect does not correctly detect the projects and var file mappings, or if additional config is needed, Infracost provides 3 options for specifying config:

  1. Auto-detect config & customizations: Used when auto-detect needs tweaking for your repo.
  2. Static config file: Best for static, simple repo structures.
  3. Advanced config template: For complex repo structures with many changing projects.

If we consider the following example repository structure, we can see how each option could be implemented.

├── environment
│ ├── dev.tfvars
│ ├── qual.tfvars
│ └── prod.tfvars
├── modules
│ └── ... # terraform modules
├── infra
│ └── main.tf
└── legacy
└── main.tf

Each tfvars file stored under the environment folder corresponds to a different environment project. The dev, qual, and prod environments. There are also two directories containing infrastructure code, but the legacy directory is no longer active, so we do not want Infracost to include it. Below are three examples based on different approaches to managing this setup.

Option 1: Auto-detect config & customizations​

For more complex repo structures, Infracost’s default auto-detection may need a bit of fine-tuning. This option allows you to provide simple "hints" that guide Infracost to accurately detect the projects and var files without the need for a fully static config.

In the example above, Infracost would automatically detect the dev and prod environments, but it might overlook the qual environment unless specified. Additionally, it could detect the legacy project, which we’d prefer to exclude. By customizing the auto-detect settings, you can ensure that all the active environments (dev, qual, and prod) are included, while legacy is ignored. See the Auto-detect parameters section for a list of the supported parameters in the autodetect block.

The autodetect block is read from a config template: save it as infracost.yml.tmpl in the root of your repo, or paste it into the config file setting in Infracost Cloud (see Usage). Because it has no projects section, Infracost keeps the auto-detected projects and applies your hints to them. Don't put it in a static infracost.yml. A static file is used as-is, so a file with only an autodetect block gives you a single project at the repo root.

infracost.yml.tmpl
version: "0.3"
autodetect:
env_names:
- dev
- qual
- prod
exclude_dirs:
- legacy

Option 2: Static config file​

For straightforward, static setups where the project structure doesn’t change frequently, you can manually define each project and its associated Terraform var files in a static config file. This approach works well when you have a small fixed set of projects and environments. See the Static config file section for a list of the parameters you can use in the projects block.

version: "0.3"
projects:
- path: infra
name: dev
terraform:
var_files:
- ../environment/dev.tfvars
- path: infra
name: qual
terraform:
var_files:
- ../environment/qual.tfvars
- path: infra
name: prod
terraform:
var_files:
- ../environment/prod.tfvars

Option 3: Advanced config template​

For more dynamic setups, such as when projects are regularly added or removed, you can use an advanced config template. This allows you to loop over the environment projects and automatically generate the config for active environments.

Here’s how you can loop through the environment files and create an infra project for each one. The legacy directory is left out because the template only creates projects for infra. See the Advanced config template section for syntax details.

infracost.yml.tmpl
version: "0.3"
projects:
{{- range $project := matchPaths "environment/:env.tfvars" }}
- path: infra
name: {{ $project.env }}
terraform:
var_files:
- {{ relPath "infra" $project._path }}
{{- end }}

Save the template as infracost.yml.tmpl at the root of your repo. Whenever infracost scan runs, it expands the template against the current directory tree and uses the resulting config — you don't need to commit the rendered file. The expanded form will look something like this:

version: "0.3"
projects:
- path: infra
name: dev
terraform:
var_files:
- ../environment/dev.tfvars
- path: infra
name: qual
terraform:
var_files:
- ../environment/qual.tfvars
- path: infra
name: prod
terraform:
var_files:
- ../environment/prod.tfvars
tip

A template that has a projects section replaces auto-detect: Infracost only runs the projects your template lists. If you want auto-detect's projects plus some extra settings, start from the template that replicates auto-detect and add to it.

note

Infracost checks each repo's rendered template. If the rendered output has a top-level projects section, only those projects run, even if the section is empty: projects: followed by a range that matched nothing gives that repo no projects. If the rendered output has no projects section, for example because projects: sits inside an {{ if }} that didn't render for that repo, Infracost uses auto-detect's projects for it. See Fixed projects for some repos, auto-detect for the rest for an example that handles both cases explicitly.

Usage​

To use config files in your repos, follow these steps:

1. Source Control Integrations (GitHub, Azure Repos and GitLab App)​

When Infracost Cloud runs on a repo from the GitHub, GitLab or Azure Repos App integration, it uses the first of these that is set. The rest are ignored, and nothing is merged:

  1. Repo-level config file in Infracost Cloud: Go to Repos, open the repo and go to its Settings tab. Use this for a repo that needs its own config, for example fixed project paths.

  2. Org-level config file in Infracost Cloud: Go to Org Settings > Repo settings > Repo config file. This is the default for every repo in the integration that has no repo-level config.

    Default config file used by all repos in the GitHub, Azure Repos or GitLab App integration
  3. infracost.yml.tmpl (or infracost.yaml.tmpl) in the repo root.

  4. infracost.yml (or infracost.yaml) in the repo root.

  5. Auto-detect, if none of the above exist.

A config stored in Infracost Cloud wins over any file committed to the repo. If you set an org-level config, files committed to your repos are no longer used, and a repo-level config completely replaces the org-level one. Both settings accept static config files and config templates.

Don't use a fixed path: . project in an org-level config

The org-level config applies to every repo. If it lists a fixed project such as:

version: "0.3"
projects:
- path: .

then every repo gets exactly one project at its root, and auto-detect no longer runs. In practice this means:

  • Repos with Terraform in subfolders get an empty root project. It's priced at $0 and shows a "No source files found" error.
  • Repos with no infrastructure code show errors instead of being skipped.
  • Terragrunt, CloudFormation, Kubernetes/Helm and other projects that auto-detect would have found are not detected.
  • Resources from the missed projects can't be linked from your cloud account back to the code that defines them.

For org-wide settings, start from the template that replicates auto-detect and add your settings to it. That way each repo still gets its own detected projects. If a repo needs fixed project paths, set them in that repo's repo-level config instead.

To update the repo based on the new config, go to the Repos page, make sure the 'Current branch' is set to the branch you want, click the "Re-run policies/estimates" button and wait for the page to update. You should now see the project list from the new config.

2. CI/CD integrations​

Commit infracost.yml (a static config) or infracost.yml.tmpl (an advanced template) to the root of your repository. infracost scan auto-discovers either file when it runs from the repo root, with the template expanded against the current directory tree on each run.

infracost scan also fetches the repo-level or org-level config from Infracost Cloud. Unlike Infracost Cloud runs, the CLI gives files in the repo priority. It uses the first of these that exists:

  1. infracost.yml in the repo root.
  2. infracost.yml.tmpl in the repo root.
  3. The repo-level config in Infracost Cloud, or if there isn't one, the org-level config.
  4. Auto-detect.

So the caution about path: . applies to the CLI too: an org-level config with a fixed path: . project changes what infracost scan finds in every repo that doesn't commit its own config.

# In your CI step, run a scan from the repo root.
# infracost.yml or infracost.yml.tmpl is picked up automatically.
infracost scan

Config file versions​

Every config file and template needs a version. The current version is "0.3", and every example on this page uses it. A file with no version is read as 0.2, so a top-level terraform block in it fails with an error. Always set version: "0.3".

Version "0.3" doesn't check the names of nested settings. A misspelled block (for example terrafrom:) or a misspelled key inside terraform: (for example var_file:) is accepted without an error and has no effect. If a setting doesn't seem to apply, check its spelling first.

Migrating from 0.1 and 0.2​

Config files and templates written for versions 0.1 and 0.2 still work, so you don't have to migrate them straight away. Those versions use flat, terraform_-prefixed keys. Version "0.3" moves Terraform settings into a nested terraform block. A "0.3" file rejects the old flat keys, and a 0.1 or 0.2 file rejects unknown keys, including the top-level terraform block. (A 0.1 or 0.2 file does accept the project-level terraform block, but don't rely on mixing the two styles.) To migrate, change the version and move each key as shown below.

0.1 / 0.2"0.3"
Top level
terraform_source_mapterraform: source_map
terraform_workspaceterraform: defaults: workspace
terraform_cloud_host, _org, _workspace, _tokenterraform: defaults: cloud: host, org, workspace, token
spacelift_api_key_endpoint, _id, _secretterraform: defaults: spacelift: api_key: endpoint, id, secret
cdk (list) and cdk_defaultscdk: apps and cdk: defaults
In each project
terraform_var_filesterraform: var_files
terraform_varsterraform: vars
terraform_workspaceterraform: workspace
terraform_cloud_host, _org, _workspace, _tokenterraform: cloud: host, org, workspace, token
spacelift_api_key_endpoint, _id, _secretterraform: spacelift: api_key: endpoint, id, secret
project_typetype
skip_autodetect, include_all_pathsRemove them. They were already ignored.

Everything else keeps its name and position, including currency, usage_file, autodetect, and the project keys name, path, type, env, usage_file, dependency_paths, exclude_paths and yor_config_path. For example, the same config in both formats:

version: "0.3"
terraform:
source_map:
- match: ^git::ssh://git@github.com/my-org/
replace: git::https://github.com/my-org/
projects:
- path: infra
name: dev
terraform:
var_files:
- ../environment/dev.tfvars
vars:
instance_count: 5
workspace: dev

Auto-detect parameters​

The following table describes the supported parameters for the autodetect block. Write autodetect: on a line of its own, with nothing after it, not even a comment or a trailing space. Otherwise the block is ignored without an error.

version: "0.3"
autodetect:
env_names:
- dev
- qual
- prod
exclude_dirs:
- legacy
ParameterDescription
env_names

Optional. Array of strings. Specifies environment names that should be used to group Terraform var files. Infracost uses these to detect and group projects by environments. For example:

env_names:
- dev
- prod
- staging

These also support wildcards. For example, the following will detect prod-us, prod-eu, dev-us and dev-eu as separate environments:

env_names:
- "prod-*"
- "dev-*"
exclude_dirs

Optional. Array of strings. Glob patterns for directories that should be excluded from project detection. Useful for ignoring outdated or test infrastructure. Each pattern is matched against a project's path relative to the repo root, and only matches that exact path: legacy excludes a project in legacy but not one in legacy/sub. To exclude a directory and everything under it, list both. For example:

exclude_dirs:
- legacy
- "legacy/**"
- tests
include_dirs

Optional. Array of strings. Glob patterns for directories that should be included in the project scan, ensuring these directories are detected. Patterns are matched the same way as exclude_dirs, and include_dirs wins if a directory matches both. If a repo contains any Terragrunt project, auto-detect skips plain Terraform root modules, because it assumes Terragrunt drives them. List those directories here to detect them as well. For example:

include_dirs:
- shared
- ".infra/**"
path_overrides

Optional. Array of objects. Allows custom path overrides with rules to include or exclude specific combinations of environments and directories from project detection.

path_overrides:
- path: "infra/base"
  only:
    - mgmt
- path: "infra/apps/**"
  exclude:
    - mgmt

With the above config and given a repo with the following directory structure:

├── envs
│   ├── mgmt.tfvars
│   ├── dev.tfvars
│   └── prod.tfvars
└── infra
  ├── base
  └── apps
      ├── search
      └── payments

Infracost will generate projects:

  • infra-base-mgmt
  • infra-apps-search-dev
  • infra-apps-search-prod
  • infra-apps-payments-dev
  • infra-apps-payments-prod
max_search_depth

Optional. Integer. Specifies the maximum directory depth to search for projects. Defaults to 14 if not provided.

link_tfvars_to_terragrunt

Optional. Boolean. Defaults to false. When true, Terraform var files found next to or below Terragrunt projects are linked to those projects, the same way they are for Terraform projects.

force_project_type

Deprecated. Use link_tfvars_to_terragrunt instead. Setting this to terraform is the same as link_tfvars_to_terragrunt: true, and any other value has no effect. It no longer changes the type of detected projects.

terraform_var_file_extensions

Optional. Array of strings. A list of suffixes that should be used to recognize Terraform var files, replacing the defaults (.tfvars, .auto.tfvars, .tfvars.json and .auto.tfvars.json). This is useful when there are non-standard Terraform var file names which use different extensions.

Static config file project parameters​

The following table describes the supported parameters for the projects block. Parameters written as terraform: var_files go inside a terraform block in the project. If you're using a 0.1 or 0.2 config, see Migrating from 0.1 and 0.2 for the older key names.

version: "0.3"
projects:
- path: infra
name: dev
terraform:
var_files:
- ../environment/dev.tfvars
ParameterDescription
pathRequired. String. Path to the Terraform directory. The path is relative to the working directory you run infracost from. A path can be repeated with different parameters, e.g. for multiple Terraform var files.
nameOptional. String. Defaults to code path, workspace or Terraform/Terragrunt module within a repo. Name of project to use in all outputs (pull request comment, Infracost Cloud and CLI).
typeOptional. String. The project type, for example terraform, terragrunt, cloudformation or kubernetes. If you leave it out, Infracost uses the type that auto-detect found for the same path, or inspects the directory itself.
terraform: var_files

Optional. Array of string. Variable files to use when parsing Terraform HCL code, similar to Terraform's -var-file flag. Files with the .auto.tfvars extension do not need to be added to the list as they are processed automatically by Infracost. The file paths are relative to the path of the project. For example:

terraform:
var_files:
  - global.tfvars
  - dev.tfvars
terraform: vars

Optional. Map of strings. Input variables to use when parsing the Terraform HCL code, similar to Terraform's -var flag. For example:

terraform:
vars:
  instance_count: 5
  artifact_version: foobar
dependency_paths

Optional. Only applicable for GitHub, Azure Repos and GitLab App users. Array of strings. Array of file or directory paths that should trigger project estimates. If this is specified, code changes to the path target will NOT trigger cost estimates unless the path is included in dependency_paths. All paths are relative to the working directory of your infracost.yml file. Supports glob patterns, for example:

dependency_paths:
- "config/**.json"
- default.yml
- "modules/**"
usage_fileOptional. String. Path to Infracost usage file that specifies values for usage-based resources. The path is relative to the repo root (the working directory you run infracost from), not to the project's path. If the file doesn't exist, it is skipped without an error, so check the path if usage values don't seem to apply.
exclude_paths

Optional. Array of strings. Array of directory paths to exclude from evaluation, relative to path of project. Supports glob patterns too, for example:

exclude_paths:
- projects/myproject
- "app/*/ignore_dir"
env

Optional. Map of strings. Environment variables that are passed to the project during processing. They are added to, and override, any environment variables set for your organization in Infracost Cloud. Values are used exactly as written: references such as ${MY_ENV_VAR} are not expanded. Environment variables that start with INFRACOST_ are global in scope (not per-project) and cannot be used inside this parameter. For example:

env:
INSTANCE_TYPE: t3.large
terraform: workspaceOptional. String. Used to set the Terraform workspace. Only set this for multi-workspace repos, otherwise it might result in the Terraform error "workspaces not supported".
terraform: cloud: workspaceOptional. String. For Terraform Cloud/Enterprise users. Used to set the Terraform Cloud workspace. Only set this if your local workspace name differs from your cloud workspace, and you do not already have a Terraform Cloud block defining the remote workspace name (e.g. using prefix).
terraform: cloud: orgOptional. String. For Terraform Cloud/Enterprise users. Used to set the Terraform Cloud organization. Only set this if you do not already have a Terraform Cloud block that defines your Terraform cloud organization name.
yor_config_pathOptional. String. For Yor users, set this to the path of your Yor config file in order to take into account Yor tag values when applying tagging policies. Alternatively, if you use the YOR_SIMPLE_TAGS environment variable, the Infracost CLI will automatically include those tags. Note that conditional logic in the Yor config file will not be considered, and all discovered tag groups/values will be applied. You can combine both of these methods, though if a tag appears in both places, the value from the YOR_SIMPLE_TAGS variable will be used.

Module source map​

The top-level terraform: source_map parameter rewrites Terraform module source URLs before Infracost downloads them. For example, use it to swap SSH Git URLs for HTTPS. Each rule has a match regular expression and a replace string, which can use capture groups such as ${1}. It applies to every Terraform and Terragrunt project in the config. In 0.1 and 0.2 configs it is called terraform_source_map.

version: "0.3"
terraform:
source_map:
- match: ^git::ssh://git@github.com/my-org/(.*)$
replace: git::https://github.com/my-org/${1}
- match: ^git::https://gitlab.example.com/platform/(.*)$
replace: git::https://gitlab.example.com/platform-mirror/${1}

Rules are checked in the order you write them, and only the first rule whose match matches a module source is applied. Later rules are not checked against that source or against the first rule's output. So:

  • Put specific rules before broad ones. A broad rule listed first catches every source it matches, and the specific rules after it never run.
  • Anchor patterns with ^ and make them as specific as possible.
  • Don't repeat a match string. If you do, only one rule is kept, in the position of the first one but with the replace of the last one.

This is different from the INFRACOST_TERRAFORM_SOURCE_MAP environment variable, which takes plain source=dest pairs rather than regular expressions. See Source map.

Advanced config template syntax​

Config file templates, like Helm templates, are built on top of Golang's text/template engine, offering an expressive way to write templates. Below we'll describe the template syntax and brief explanation of the main expressions and logic.

Syntax​

Templates use a pair of curly braces {{ }} to delimit actions, such as variables, if/else statements, and range iterations. Within the curly braces, Infracost can recognize and execute template actions.

For example, {{ $project.name }} would print the value of the $project.name, while

{{- if .Enabled }}
Enabled
{{- else }}
Disabled
{{- end }}

would execute conditional logic based on the value of the Enabled field in the current context.

if/else​

Conditional logic can be added to templates using the {{ if }}, {{ else if }}, and {{ else }} keywords. The logical operators and and or can also be used, for example

{{- if .testA }}
testA is true
{{- else if and .testB .testC }}
testB and testC is true
{{- else }}
Disabled
{{- end }}

This can be useful to conditionally include projects for Infracost to evaluate, for example:

{{- if ne $project.name "test" }}
- path: .
...
{{- end }}

adds a configuration entry for the current project if it does not equal "test".

range​

Templates can iterate over arrays and maps using the {{ range }} keyword. For example:

{{- range .Items }}
{{- .Name }}
{{- end }}

would print the value of the Name field for each item in the Items array in the current context. Within config file templates range expressions are normally combined with matchPaths calls to iterate over a subset of directories or files, for example:

{{- range $project := matchPaths "environment/:env/terraform.tfvars" }}
- path: .
name: {{ $project.env }}
{{- end }}

sets successive elements returned from matchPaths to $project, which can be accessed inside the range loop, e.g. $project.env

Global variables​

Templates have access to the following global variables:

  • .RepoName - The name of the repository being processed.
  • .Branch - The name of the current branch that the template is executed on.
  • .DetectedRootModules - The root modules detected by auto-detect. Each root module has the following attributes:
    • Path - The path to the root module.
    • Type - The project type, for example terraform or terragrunt.
    • Projects - A list of projects associated with the root module (see below for the attributes available within a project)
  • .DetectedProjects - The projects detected by auto-detect. This variable provides a simplified view of all detected projects with the following attributes:
    • Name - The name of the project.
    • Path - The path to the project, relative to the repo root.
    • Type - The project type, for example terraform, terragrunt, cloudformation or kubernetes.
    • TerraformVarFiles - A list of Terraform var files associated with the project, relative to the project's Path.
    • DependencyPaths - A list of dependency paths for the project.
    • Env - The environment name associated with the project.

With infracost scan, .Branch is the local Git branch and .RepoName is the repo name Infracost Cloud has for the repo's Git remote. Either is empty if it can't be found.

The following global variable is only set when Infracost Cloud runs on a pull request. It is empty for default branch runs and for infracost scan:

  • .BaseBranch - The name of the base branch that the pull request is being merged into (which is usually main or master).

    {{ if eq .BaseBranch "production" }}
    - path: terraform/infra/prod
    name: infra-prod
    {{ end }}

Functions​

Config file templates support a wide range of built-in functions to make it easy for you to write config files that work for your project structure. Below you'll find a list of supported functions with detailed examples.

Please be aware that the functions and examples provided are designed for a Unix-based system. If you are using Windows, make sure to adjust the path syntax accordingly. For instance, use backslashes \ in paths as per Windows system requirements.

Filepath functions​

Config file templates include the following functions to help you traverse your project structure:


matchPaths​

Returns a list of matches that in the project directory tree that match the pattern.

Arguments:​
namedescriptionexample
patterna path pattern to one or more files or directories in your project. Keys that you wish to extract must be prefixed with ':'"environment/:env/terraform.tfvars", "infra/:env/:app", "environment/:app/:env.tfvars", ":optional-parent?/:optional-child?/main.tf"
Returns:​

A collection of matches in the current project. Results are returned with a map of extracted keys from the pattern. In addition, each result has two additional properties:

  • _path - the full path of that the pattern matched on
  • _dir - the base directory that the pattern matched on

If you specify a "one or more" match, the var can be an array that will represent all the intermediate directories that match:

e.g. infra/:env/:subfolders+/tf.tfvars with a path like /infra/dev/one/two/three/tf.tfvars will have $match.subfolders be a list of "one" "two" "three", which you can then {{ join "-" $match.subfolders }} to become one-two-three

Example:​

Using the range expression to iterate over the results like so:

version: "0.3"

projects:
{{- range $project := matchPaths "environment/:env/terraform.tfvars" }}
- path: .
name: {{ $project.env }}
terraform:
var_files:
- {{ $project._path }}
{{- end }}

pathExists​

Returns true if the path exists within base.

Arguments​
namedescriptionexample
baseThe directory to search for the given file or directory. Use "." to start from the project root.".", "some/dir"
pathThe path of the file or directory to search for. This must be relative to the base path provided at argument one."dir/to/find", "file/to/find.txt"
Example​
version: "0.3"

projects:
{{- range $project := matchPaths "environment/:env/terraform.tfvars" }}
{{- if pathExists $project._dir "include.txt" }}
- path: .
name: {{ $project.env }}
{{- end }}
{{- end }}

isDir​

Returns true if the path is a directory.

Arguments​
namedescriptionexample
pathThe path to check, relative to the repo root".", "some/dir"
Example​
version: "0.3"

projects:
{{- range $project := matchPaths "environment/:env" }}
{{- if isDir $project._path }}
- path: {{ $project._path }}
name: {{ $project.env }}
{{- end }}
{{- end }}

readFile​

Reads the file at the given directory, this can then be printed into the template or passed to one of the parseYaml or parseJson functions to allow for data manipulation.

Arguments​
namedescriptionexample
pathThe path of the file, relative to the repo root. The template fails if the file doesn't exist or is outside the repo."some/file.json"

parseYaml​

Decode the contents of a string as a YAML structure.

Arguments​
namedescriptionexample
contentsThe YAML string to decode, this is normally obtained by loading a file using the readFile function.(readFile "some/file.yaml")
Example​
version: "0.3"
{{- $yaml := parseYaml (readFile "config/env.yaml") }}
projects:
- path: infra
name: my-infra
env:
{{- range $key, $value := $yaml.envs }}
{{ $key }}: {{ $value }}
{{- end }}

parseJson​

Decode the contents of a string as a JSON object.

Arguments​
namedescriptionexample
contentsThe JSON string to decode, this is normally obtained by loading a file using the readFile function.(readFile "some/file.json")
Example​
version: "0.3"
{{- $json := parseJson (readFile "config/env.json") }}
projects:
- path: infra
name: my-infra
env:
{{- range $key, $value := $json.envs }}
{{ $key }}: {{ $value }}
{{- end }}

relPath​

Returns the relative path of the target path from the given base path.

This is useful for providing the correct relative path for shared variable files that exist outside of the project path.

Arguments​
namedescriptionexample
baseThe base path that the resulting relative path is computed against".", "some/dir"
targetThe target path, relative to the repo root directory"global.tfvars"
Example​
version: "0.3"

projects:
{{- range $project := matchPaths "environment/:env" }}
- path: {{ $project._path }}
name: {{ $project.env }}
terraform:
var_files:
- {{ relPath $project._path "global.tfvars" }}
{{- end }}

base​

Returns the last element of path, for example:

  • base "full/path/here.txt" returns here.txt
  • base "full/path" returns path

ext​

Returns the file name extension used by path, for example:

  • ext "full/path/here.txt" returns .txt

stem​

Returns the last element of path with the extension removed, for example:

  • stem "full/path/here.txt" returns here

join​

Joins multiple elements of a list together into a string, with the given separator

  • join "-" (list "item1" "item2" "item3") returns item1-item2-item3

Control flow functions​

Config file templates support control flow functions including list, eq, ne and not. Templates can also use the control flow functions lt, le, gt, ge, and and or from the base text/template library. The documentation for these additional functions can be found here.

list​

Creates a list of items.

  • list "item1" "item2" "item3" returns [item1 item2 item3]

eq​

Returns the boolean truth of arg1 == arg2, for example:

  • eq $project.arg1 $project.arg2

ne​

Returns the boolean truth of arg1 != arg2, for example:

  • ne $project.arg1 $project.arg2

not​

Returns the boolean negation of its single argument, for example:

  • not (pathExists "." "path")

isProduction​

Returns true if the project name matches your organization's production project filters in Infracost Cloud. When no filters are configured, or when running infracost scan locally, it returns true. For example:

  • isProduction $project.Name

String Functions​

Config file templates support for the following string manipulation functions. Templates can also use the string functions print, printf and println from the base text/template library. The documentation for these additional functions can be found here.

lower​

Returns the lowercase version of the string, for example:

  • lower "FOO" returns foo

startsWith​

Tests whether the string begins with prefix, for example:

  • startsWith "mystring" "my" returns true
  • startsWith "mystring" "foo" returns false

endsWith​

Tests whether the string ends with suffix, for example:

  • endsWith "mystring" "string" returns true
  • endsWith "mystring" "foo" returns false

contains​

Reports whether the substring is within the subject, for example:

  • contains "mystringbar" "string" returns true
  • contains "mystringbar" "foo" returns false

splitList​

Splits a string into a list of substrings with the specified separator, for example:

  • splitList "," "a,b,c" returns [a b c]

trimPrefix​

Removes the specified prefix from a string.

  • trimPrefix "mystring" "my" returns string
  • trimPrefix "mystring" "foo" returns mystring

trimSuffix​

Removes the specified suffix from a string.

  • trimSuffix "mystring" "string" returns my
  • trimSuffix "mystring" "foo" returns mystring

replace​

Replaces all occurrences of old with new in the string.

  • replace "world" "universe" "hello world" returns hello universe
  • replace "foo" "bar" "foofoo" returns barbar

quote​

Surrounds the string with double quotes.

  • quote "hello world" returns "hello world"

squote​

Surrounds the string with single quotes.

  • squote "hello world" returns 'hello world'

Debugging​

debug​

Prints the value passed to it to standard error and returns true, without adding anything to the rendered config. This is useful when running infracost scan locally to see what a variable holds, for example:

  • {{- if debug $project }}{{ end }}

Examples​

Replicating auto-detect​

Start here if you want auto-detect's projects with extra settings added, and especially for an org-level config in Infracost Cloud. This template creates exactly the projects auto-detect would, with their var files and dependency paths, so every repo keeps its own projects. Add your settings to it, such as terraform: vars, env, an autodetect block or a module source map.

version: "0.3"

projects:
{{- range $project := .DetectedProjects }}
- path: {{ $project.Path }}
name: {{ $project.Name }}
type: {{ $project.Type }}
{{- if pathExists $project.Path "infracost-usage.yml" }}
usage_file: {{ $project.Path }}/infracost-usage.yml
{{- end }}
{{- if $project.DependencyPaths }}
dependency_paths:
{{- range $dep := $project.DependencyPaths }}
- {{ $dep }}
{{- end }}
{{- end }}
{{- if $project.TerraformVarFiles }}
terraform:
var_files:
{{- range $varFile := $project.TerraformVarFiles }}
- {{ $varFile }}
{{- end }}
{{- end }}
{{- end }}

If you only need to add top-level settings such as a module source map or an autodetect block, you can leave out the projects section completely. A template with no projects section keeps the auto-detected projects as they are.

Fixed projects for some repos, auto-detect for the rest​

An org-level config applies to every repo, so fixed project paths only suit repos that share a layout. This template gives repos laid out as root Terraform plus environments/<env>.tfvars a fixed set of environment projects, and only for environments whose var file exists. Every other repo gets auto-detect's projects, listed in the else branch so you can add settings to them, such as terraform: vars.

version: "0.3"

projects:
{{- $rootTF := matchPaths ":file.tf" }}
{{- if and $rootTF (pathExists "." "environments/dev.tfvars") }}
{{- range $env := list "dev" "prod" }}
{{- if pathExists "." (printf "environments/%s.tfvars" $env) }}
- path: .
name: {{ $env }}
terraform:
var_files:
- environments/{{ $env }}.tfvars
{{- end }}
{{- end }}
{{- else }}
{{- range $project := .DetectedProjects }}
- path: {{ $project.Path }}
name: {{ $project.Name }}
type: {{ $project.Type }}
{{- if $project.DependencyPaths }}
dependency_paths:
{{- range $dep := $project.DependencyPaths }}
- {{ $dep }}
{{- end }}
{{- end }}
{{- if $project.TerraformVarFiles }}
terraform:
var_files:
{{- range $varFile := $project.TerraformVarFiles }}
- {{ $varFile }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}

Change dev, prod and the environments/ folder to match your layout.

More examples​

Looping over projects with environments contained in a sub folder
version: "0.3"
projects:
{{- range $project := matchPaths "environment/:app/:env" }}
- path: {{ $project._dir }}
name: {{ $project.app }}-{{ $project.env }}
{{- end }}
Excluding certain projects
version: "0.3"
projects:
{{- range $project := matchPaths "environment/:env.tfvars" }}
{{- if ne $project.env "legacy"}}
- path: {{ $project._dir }}
name: {{ $project.env }}
terraform:
var_files:
- {{ relPath $project._dir $project._path }}
{{- end}}
{{- end }}
Only matching certain project
version: "0.3"
projects:
{{- range $project := matchPaths "environment/:env(prod|dev).tfvars" }}
- path: {{ $project._dir }}
name: {{ $project.env }}
terraform:
var_files:
- {{ relPath $project._dir $project._path }}
{{- end }}
Looping over multiple projects with a var file contained at the root level as well as project
version: "0.3"
projects:
{{- range $project := matchPaths ":name/:region/main.tf" }}
- path: {{ $project.name }}/{{ $project.region }}
name: {{ $project.name }}-{{ $project.region }}
terraform:
var_files:
- local.tfvars
{{- if pathExists "." "global.tfvars"}}
- {{ relPath $project._dir "global.tfvars" }}
{{- end}}
{{- end }}
Project with configuration defined in a non-Terraform file
version: "0.3"
projects:
{{- $envs := list "prod" "dev"}}
{{- range $project := matchPaths ":app/main.tf" }}
{{- range $env := $envs}}
- path: {{ $project._dir }}
name: {{ $project.app }}-{{ $env }}
{{- end }}
{{- end }}
Looping over projects with complex matchPaths matchers

Example folder structure:

├── dev
├── prod
├── test
└── foo

The following range in a template:

// Ensure a folder matches a list of names, ignore everything else
{{- range $match := matchPaths ":env(dev|prod|test)" }}

Will loop over: [{env: dev}, {env: prod}, {env: test}]


Example folder structure:

├── foo/
│ └── main.tf
└── bar/
├── dev/
│ └── main.tf
└── prod/
└── main.tf

The following range in a template:

// Match a nested folder if it exists
{{- range $match := matchPaths ":app/:env?/main.tf" }}

Will loop over: [{app: foo}, {app: bar, env: dev}, {app: bar, env: prod}]


Example folder structure:

├── foo/
│ ├── prod.tfvars
│ └── prod-euwest.tfvars
└── bar/
└── dev.tfvars

The following range in a template:

// Match a region in the tfvar name if it exists, and capture it
{{- range $match := matchPaths ":app/:env{-:region}?.tfvars" }}

Will loop over: [{app: foo, env: prod}, {app: foo, env: prod, region: euwest}, {app: bar, env: dev}]

Additional examples of different Infracost config files using the advanced config template and the auto-detect config and customizations can be found in the Infracost GitHub repo.

FAQ and Troubleshooting​

How do I know if Infracost is correctly detecting my projects?​

Run infracost scan --json (or infracost inspect --json after a scan) and review the project list in the output. If a project is missing or extra, adjust your autodetect block or switch to a static infracost.yml to pin the project list explicitly.

How can I troubleshoot issues with my config file?​

To troubleshoot issues with your Infracost config file:

  1. Enable debug logs: Set INFRACOST_CLI_LOG_LEVEL=debug to see more detailed logs when running Infracost. This can help identify problems with project detection or configuration.

    INFRACOST_CLI_LOG_LEVEL=debug infracost scan
  2. Check the expanded template: If you're using an infracost.yml.tmpl template, run infracost scan --json and check the resulting project list. To see what a template variable holds, use the debug function.

Why are costs not updating for some projects?​

If certain projects’ costs are not updating as expected, consider the following:

  1. Project detected: Is the project being correctly detected by the auto-detect functionality. If it's not, consider adding a custom config file.
  2. Dependency paths: Make sure the dependency_paths option is set correctly if you want to trigger cost estimates when specific files or directories are modified.

Getting help​

If you're still having trouble, feel free to reach out to the Infracost team on our community Slack channel, and we’ll help you troubleshoot.