Movatterモバイル変換


[0]ホーム

URL:


HashiConf 2025Don't miss the live stream of HashiConf Day 2 happening now View live stream

Create a Terraform CLI configuration file

This topic describes how create a configuration file to customize the behavior of the Terraform CLI.

Introduction

The CLI configuration file configures per-user settings for CLI behaviors,which apply across all Terraform working directories. This is separate fromyour infrastructure configuration.You can define custom configurations in file called.terraformrc orterraform.rcdepending on the host operating system as explained below.

Locations

The configuration can be placed in a single file whose location dependson the host operating system:

  • On Windows, the file must be namedterraform.rc and placedin the relevant user's%APPDATA% directory. The physical locationof this directory depends on your Windows version and system configuration;use$env:APPDATA in PowerShell to find its location on your system.
  • On all other systems, the file must be named.terraformrc (notethe leading period) and placed directly in the home directoryof the relevant user.

On Windows, beware of Windows Explorer's default behavior of hiding filenameextensions. Terraform will not recognize a file namedterraform.rc.txt as aCLI configuration file, even though Windows Explorer maydisplay its nameas justterraform.rc. Usedir from PowerShell or Command Prompt toconfirm the filename.

The location of the Terraform CLI configuration file can also be specifiedusing theTF_CLI_CONFIG_FILEenvironment variable.Any such file should follow the naming pattern*.tfrc.

Configuration File Syntax

The configuration file uses the sameHCL syntax as.tf files, but withdifferent attributes and blocks. The following example illustrates thegeneral syntax; see the following section for information on the meaningof each of these settings:

plugin_cache_dir= "$HOME/.terraform.d/plugin-cache"disable_checkpoint= true

Available Settings

The following settings can be set in the CLI configuration file:

Credentials

HCP Terraform provides a number of remote networkservices for use with Terraform, andTerraform Enterprise allows hosting thoseservices inside your own infrastructure. For example, these systems offer bothremote operations and aprivate module registry.

When interacting with Terraform-specific network services, Terraform expectsto find API tokens in CLI configuration files incredentials blocks:

credentials "app.terraform.io" {  token= "xxxxxx.atlasv1.zzzzzzzzzzzzz"}

If you are running the Terraform CLI interactively on a computer with a web browser, you can usetheterraform login commandto get credentials and automatically save them in the CLI configuration. Ifnot, you can manually writecredentials blocks.

You can have multiplecredentials blocks if you regularly use services frommultiple hosts. Many users will configure only one, for eitherHCP Terraform (atapp.terraform.io) or for their organization's ownTerraform Enterprise host. Eachcredentials block contains atoken argumentgiving the API token to use for that host.

Important: If you are using HCP Terraform or Terraform Enterprise,the token provided must be either auser tokenor ateam token;organization tokens cannot be used for command-line Terraform actions.

Note: The credentials hostname must match the hostname in your modulesources and/or backend configuration. If your Terraform Enterprise instanceis available at multiple hostnames, use only one of them consistently.HCP Terraform responds to API calls at both its current hostnameapp.terraform.io, and its historical hostnameatlas.hashicorp.com.

Environment Variable Credentials

Note: Environment variable credentials are supported in Terraform v1.2.0 and later.

If you would prefer not to store your API tokens directly in the CLI configuration, you may usea host-specific environment variable. Environment variable names should have the prefixTF_TOKEN_ added to the domain name, with periods encoded as underscores. For example, thevalue of a variable namedTF_TOKEN_app_terraform_io will be used as a bearer authorizationtoken when the CLI makes service requests to the hostnameapp.terraform.io.

You must convert domain names containing non-ASCII characters to theirpunycode equivalentwith an ACE prefix. For example, token credentials for 例えば.com must be set in a variablecalledTF_TOKEN_xn--r8j3dr99h_com.

Hyphens are also valid within host names but usually invalid as variable names andmay be encoded as double underscores. For example, you can set a token for the domain namecafé.fr asTF_TOKEN_xn--caf-dma.fr,TF_TOKEN_xn--caf-dma_fr, orTF_TOKEN_xn____caf__dma_fr.If multiple variables evaluate to the same hostname, Terraform will choose the one defined lastin the operating system's variable table.

Credentials Helpers

You can configure acredentials_helper to instruct Terraform to use a different credentials storage mechanism.

credentials_helper "example" {  args= []}

credentials_helper is a configuration block that can appear at most oncein the CLI configuration. Its label ("example" above) is the name of thecredentials helper to use. Theargs argument is optional and allows passingadditional arguments to the helper program, for example if it needs to beconfigured with the address of a remote host to access for credentials.

A configured credentials helper will be consulted only to retrieve credentialsfor hosts that arenot explicitly configured in acredentials block asdescribed in the previous section.Conversely, this means you can override the credentials returned by the helperfor a specific hostname by writing acredentials block alongside thecredentials_helper block.

Terraform does not include any credentials helpers in the main distribution.To learn how to write and install your own credentials helpers to integratewith existing in-house credentials management systems, seethe guide to Credentials Helper internals.

Credentials Source Priority Order

Credentials found in an environment variable for a particular service hostas described above will be preferred over those in CLI config as set byterraform login.If neither are set, any configured credentials helper will be consulted.

Note: For users ofterraform-credentials-helper, this priority has been effectively reversed following therelease of Terraform 1.2. Previously, credentials found within CLI config or set byterraform login were preferred toTF_TOKEN_* variables.

Provider Installation

The default way to install provider plugins is from a provider registry. Theorigin registry for a provider is encoded in the provider's source address,likeregistry.terraform.io/hashicorp/aws. For convenience in the common case,Terraform allows omitting the hostname portion for providers onregistry.terraform.io, so you can write shorter public provider addresses likehashicorp/aws.

Downloading a plugin directly from its origin registry is not alwaysappropriate, though. For example, the system where you are running Terraformmay not be able to access an origin registry due to firewall restrictionswithin your organization or your locality.

To allow using Terraform providers in these situations, there are somealternative options for making provider plugins available to Terraform whichwe'll describe in the following sections.

Explicit Installation Method Configuration

Aprovider_installation block in the CLI configuration allows overridingTerraform's default installation behaviors, so you can force Terraform to usea local mirror for some or all of the providers you intend to use.

The general structure of aprovider_installation block is as follows:

provider_installation {  filesystem_mirror {    path= "/usr/share/terraform/providers"    include= ["example.com/*/*"]  }  direct {    exclude= ["example.com/*/*"]  }}

Each of the nested blocks inside theprovider_installation block specifiesone installation method. Each installation method can take bothincludeandexclude patterns that specify which providers a particular installationmethod can be used for. In the example above, we specify that any providerwhose origin registry is atexample.com can be installed only from thefilesystem mirror at/usr/share/terraform/providers, while all otherproviders can be installed only directly from their origin registries.

If you set bothinclude andexclude for a particular installationmethod, the exclusion patterns take priority. For example, includingregistry.terraform.io/hashicorp/* but also excludingregistry.terraform.io/hashicorp/dns will make that installation method applyto everything in thehashicorp namespace with the exception ofhashicorp/dns.

As with provider source addresses in the main configuration, you can omittheregistry.terraform.io/ prefix for providers distributed through thepublic Terraform registry, even when using wildcards. For example,registry.terraform.io/hashicorp/* andhashicorp/* are equivalent.*/* is a shorthand forregistry.terraform.io/*/*, not for*/*/*.

The following are the two supported installation method types:

  • direct: request information about the provider directly from its originregistry and download over the network from the location that registryindicates. This method expects no additional arguments.

  • filesystem_mirror: consult a directory on the local disk for copies ofproviders. This method requires the additional argumentpath to indicatewhich directory to look in.

    Terraform expects the given directory to contain a nested directory structurewhere the path segments together provide metadata about the availableproviders. The following two directory structures are supported:

    • Packed layout:HOSTNAME/NAMESPACE/TYPE/terraform-provider-TYPE_VERSION_TARGET.zipis the distribution zip file obtained from the provider's origin registry.
    • Unpacked layout:HOSTNAME/NAMESPACE/TYPE/VERSION/TARGET is a directorycontaining the result of extracting the provider's distribution zip file.

    In both layouts, theVERSION is a string like2.0.0 and theTARGETspecifies a particular target platform using a format likedarwin_amd64,linux_arm,windows_amd64, etc.

    If you use the unpacked layout, Terraform will attempt to create a symboliclink to the mirror directory when installing the provider, rather thancreating a deep copy of the directory. The packed layout prevents thisbecause Terraform must extract the zip file during installation.

    You can include multiplefilesystem_mirror blocks in order to specifyseveral different directories to search.

  • network_mirror: consult a particular HTTPS server for copies of providers,regardless of which registry host they belong to. This method requires theadditional argumenturl to indicate the mirror base URL, which shoulduse thehttps: scheme and end with a trailing slash.

    Terraform expects the given URL to be a base URL for an implementation ofthe provider network mirror protocol,which is designed to be relatively easy to implement using typical staticwebsite hosting mechanisms.

Warning: Don't configurenetwork_mirror URLs that you do not trust.Provider mirror servers are subject to TLS certificate checks to verifyidentity, but a network mirror with a TLS certificate can potentially servemodified copies of upstream providers with malicious content.

Terraform will try all of the specified methods whose include and excludepatterns match a given provider, and select the newest version available acrossall of those methods that matches the version constraint given in eachTerraform configuration. If you have a local mirror of a particular providerand intend Terraform to use that local mirror exclusively, you must eitherremove thedirect installation method altogether or use itsexcludeargument to disable its use for specific providers.

Implied Local Mirror Directories

If your CLI configuration does not include aprovider_installation block atall, Terraform produces animplied configuration. The implied configurationincludes a selection offilesystem_mirror methods and then thedirectmethod.

The set of directories Terraform can select as filesystem mirrors depends onthe operating system where you are running Terraform:

  • Windows:%APPDATA%/terraform.d/plugins and%APPDATA%/HashiCorp/Terraform/plugins
  • Mac OS X:$HOME/.terraform.d/plugins,~/Library/Application Support/io.terraform/plugins, and/Library/Application Support/io.terraform/plugins
  • Linux and other Unix-like systems:$HOME/.terraform.d/plugins andterraform/plugins located within a validXDG Base Directorydata directory such as$XDG_DATA_HOME/terraform/plugins.Without any XDG environment variables set, Terraform will use~/.local/share/terraform/plugins,/usr/local/share/terraform/plugins, and/usr/share/terraform/plugins.

If aterraform.d/plugins directory exists in the current working directorythen Terraform will also include that directory, regardless of your operatingsystem. This behavior changes when you use the-chdir option with theinit command. In that case, Terraform checks for theterraform.d/plugins directory in the launch directory and not in the directory you specified with-chdir.

Terraform will check each of the paths above to see if it exists, and if sotreat it as a filesystem mirror. The directory structure inside each one musttherefore match one of the two structures described forfilesystem_mirrorblocks inExplicit Installation Method Configuration.

In addition to the zero or more impliedfilesystem_mirror blocks, Terraformalso creates an implieddirect block. Terraform will scan all of thefilesystem mirror directories to see which providers are placed there andautomatically exclude all of those providers from the implieddirect block.(This automaticexclude behavior applies only toimplicitdirect blocks;if you use explicitprovider_installation you will need to write the intendedexclusions out yourself.)

Provider Plugin Cache

By default,terraform init downloads plugins into a subdirectory of theworking directory so that each working directory is self-contained. As aconsequence, if you have multiple configurations that use the same providerthen a separate copy of its plugin will be downloaded for each configuration.

Given that provider plugins can be quite large (on the order of hundreds ofmegabytes), this default behavior can be inconvenient for those with slowor metered Internet connections. Therefore Terraform optionally allows theuse of a local directory as a shared plugin cache, which then allows eachdistinct plugin binary to be downloaded only once.

To enable the plugin cache, use theplugin_cache_dir setting inthe CLI configuration file. For example:

plugin_cache_dir= "$HOME/.terraform.d/plugin-cache"

This directory must already exist before Terraform will cache plugins;Terraform will not create the directory itself.

Please note that on Windows it is necessary to use forward slash separators(/) rather than the conventional backslash (\) since the configurationfile parser considers a backslash to begin an escape sequence.

Setting this in the configuration file is the recommended approach for apersistent setting. Alternatively, theTF_PLUGIN_CACHE_DIR environmentvariable can be used to enable caching or to override an existing cachedirectory within a particular shell session:

export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"

When a plugin cache directory is enabled, theterraform init command willstill use the configured or implied installation methods to obtain metadataabout which plugins are available, but once a suitable version has beenselected it will first check to see if the chosen plugin is already availablein the cache directory. If so, Terraform will use the previously-downloadedcopy.

If the selected plugin is not already in the cache, Terraform will downloadit into the cache first and then copy it from there into the correct locationunder your current working directory. When possible Terraform will usesymbolic links to avoid storing a separate copy of a cached plugin in multipledirectories.

The plugin cache directorymust not also be one of the configured or impliedfilesystem mirror directories, since the cache management logic conflicts withthe filesystem mirror logic when operating on the same directory.

Terraform will never itself delete a plugin from the plugin cache once it hasbeen placed there. Over time, as plugins are upgraded, the cache directory maygrow to contain several unused versions which you must delete manually.

Note: The plugin cache directory is not guaranteed to be concurrencysafe. The provider installer's behavior in environments with multipleterraforminit calls is undefined.

Allowing the Provider Plugin Cache to break the dependency lock file

Note: The option described in is for unusual and exceptional situationsonly. Do not set this option unless you are sure you need it and you fullyunderstand the consequences of enabling it.

By default Terraform will use packages from the global cache directory onlyif they match at least one of the checksums recorded in thedependency lock filefor that provider. This ensures that Terraform can alwaysgenerate a complete and correct dependency lock file entry the first time youuse a new provider in a particular configuration.

However, we know that in some special situations teams have been unable to usethe dependency lock file as intended, and so they don't include it in theirversion control as recommended and instead let Terraform re-generate it eachtime it installs providers.

For those teams that don't preserve the dependency lock file in their versioncontrol systems between runs, Terraform allows an additional CLI Configurationsetting which tells Terraform to always treat a package in the cache directoryas valid even if there isn't already an entry in the dependency lock fileto confirm it:

plugin_cache_may_break_dependency_lock_file= true

Alternatively, you can set the environment variableTF_PLUGIN_CACHE_MAY_BREAK_DEPENDENCY_LOCK_FILE to any value other than theempty string or0, which is equivalent to the above setting.

Setting this option gives Terraform CLI permission to create an incompletedependency lock file entry for a provider if that would allow Terraform touse the cache to install that provider. In that situation the dependency lockfile will be valid for use on the current system but may not be valid for use onanother computer with a different operating system or CPU architecture, becauseit will include only a checksum of the package in the global cache.

We recommend that most users leave this option unset, in which case Terraformwill always install a provider from upstream the first time you use it witha particular configuration, but can then re-use the cache entry on later runsonce the dependency lock file records valid checksums for the provider package.

Note: The Terraform team intends to improve the dependency lock filemechanism in future versions so that it will be usable in more situations. Atthat time this option will become silently ignored. If your workflow relies onthe use of this option, please open a GitHub issue to share details about yoursituation so that we can consider how to support it without breaking thedependency lock file.

Development Overrides for Provider Developers

Note: Development overrides work only in Terraform v0.14 and later.Using adev_overrides block in your CLI configuration will cause Terraformv0.13 to reject the configuration as invalid.

Normally Terraform verifies version selections and checksums for providersin order to help ensure that all operations are made with the intended versionof a provider, and that authors can gradually upgrade to newer provider versionsin a controlled manner.

These version and checksum rules are inconvenient when developing a providerthough, because we often want to try a test configuration against a developmentbuild of a provider that doesn't even have an associated version number yet,and doesn't have an official set of checksums listed in a provider registry.

As a convenience for provider development, Terraform supports a specialadditional blockdev_overrides inprovider_installation blocks. The contentsof this block effectively override all of the other configured installationmethods, so a block of this type must always appear first in the sequence:

provider_installation {  # Use /home/developer/tmp/terraform-null as an overridden package directory  # for the hashicorp/null provider. This disables the version and checksum  # verifications for this provider and forces Terraform to look for the  # null provider plugin in the given directory.  dev_overrides {    "hashicorp/null" ="/home/developer/tmp/terraform-null"  }  # For all other providers, install them directly from their origin provider  # registries as normal. If you omit this, Terraform will _only_ use  # the dev_overrides block, and so no other providers will be available.  direct {}}

With development overrides in effect, theterraform init command will stillattempt to select a suitable published version of your provider to install andrecord inthe dependency lock filefor future use, but other commands liketerraform apply will disregard the lock file's entry forhashicorp/null andwill use the given directory instead. Once your new changes are included in apublished release of the provider, you can useterraform init -upgrade toselect the new version in the dependency lock file and remove your developmentoverride.

The override path for a particular provider should be a directory similar towhat would be included in a.zip file when distributing the provider. Atminimum that includes an executable file named with a prefix liketerraform-provider-null, wherenull is the provider type. If your providermakes use of other files in its distribution package then you can copy thosefiles into the override directory too.

You may wish to enable a development override only for shell sessions whereyou are actively working on provider development. If so, you can write alocal CLI configuration file with content like the above in your developmentdirectory, perhaps calleddev.tfrc for the sake of example, and then use theTF_CLI_CONFIG_FILE environment variable to instruct Terraform to use thatlocalized CLI configuration instead of the default one:

export TF_CLI_CONFIG_FILE=/home/developer/tmp/dev.tfrc

Development overrides are not intended for general use as a way to haveTerraform look for providers on the local filesystem. If you wish to putcopies ofreleased providers in your local filesystem, seeImplied Local Mirror DirectoriesorExplicit Installation Method Configurationinstead.

This development overrides mechanism is intended as a pragmatic way to enablesmoother provider development. The details of how it behaves, how toconfigure it, and how it interacts with the dependency lock file may all evolvein future Terraform releases, including possible breaking changes. We thereforerecommend using development overrides only temporarily during providerdevelopment work.

Removed Settings

The following settings are supported in Terraform 0.12 and earlier but areno longer recommended for use:

  • providers - a configuration block that allows specifying the locations ofspecific plugins for each named provider. This mechanism is deprecatedbecause it is unable to specify a version number and source for each provider.SeeProvider Installation above for the replacementof this setting in Terraform 0.13 and later.
Edit this page on GitHub

[8]ページ先頭

©2009-2025 Movatter.jp