Throughout this module you have written resource "local_file" and resource "random_pet" without asking where those resource types come from. The answer is providers: the plugins that translate your declarative configuration into calls to a specific API. Terraform on its own knows nothing about AWS, about PostgreSQL or about local files; it knows how to build a graph, calculate differences and manage a state. All the real-world knowledge lives in the providers. This lesson closes module 2 by opening that box: what a provider is as a process, how you choose and pin its version, what the lock file guarantees, how several instances are configured to deploy to two regions and — very importantly — how you give it credentials without ever writing them in a .tf file.

  1. What a provider really is

A provider is a separate program. It is not a library linked inside Terraform: it is a binary that Terraform downloads, starts as a child process and talks to over gRPC through HashiCorp's plugin protocol.

flowchart TB
    subgraph CLI["Process: terraform (core)"]
        A["HCL parser"]
        B["Dependency graph"]
        C["Plan and apply engine"]
        D["State manager"]
    end

    subgraph P1["Process: terraform-provider-aws"]
        E["Resource schema"]
        F["CRUD: Create/Read/Update/Delete"]
    end

    subgraph P2["Process: terraform-provider-random"]
        G["Schema"]
        H["CRUD"]
    end

    C -->|"gRPC<br/>plugin protocol"| E
    C -->|"gRPC"| G
    F -->|"HTTPS<br/>REST API"| AWS["AWS API"]
    D --> ST[("terraform.tfstate")]

What each provider contributes:

Responsibility Example
Declaring its schema Which arguments aws_s3_bucket has, which are required, which force replacement
Implementing the CRUD How each type is created, read, updated and destroyed
Translating to the API Turning the HCL object into HTTP calls with their authentication
Normalising the response Turning the API's response into state attributes
Validating arguments Rejecting impossible values before calling the API

You can see them in action. During an apply, providers are real processes on your machine:

$ ps aux | grep terraform-provider
dev  24815  ... .terraform/providers/registry.terraform.io/hashicorp/local/2.5.2/linux_amd64/terraform-provider-local_v2.5.2_x5
dev  24816  ... .terraform/providers/registry.terraform.io/hashicorp/random/3.6.3/linux_amd64/terraform-provider-random_v3.6.3_x5

And you can inspect which provider each part of your configuration uses:

$ terraform providers

Providers required by configuration.
.
├── provider[registry.terraform.io/hashicorp/local] ~> 2.5
├── provider[registry.terraform.io/hashicorp/random] ~> 3.6
└── module.database
    └── provider[registry.terraform.io/hashicorp/random] >= 3.0.0

Providers required by state:

    provider[registry.terraform.io/hashicorp/local]
    provider[registry.terraform.io/hashicorp/random]

This output is very useful for answering two frequent questions: "which module is demanding this version?" and "which providers do I still need in order to destroy what is in the state?".

The resource type's prefix determines the provider: local_file → local, random_pet → random, aws_s3_bucket → aws. It is a convention, not a strict rule, but every serious provider follows it.

To see a provider's complete schema without leaving the terminal:

# Every resource type and its arguments, in JSON.
$ terraform providers schema -json | jq -r \
  '.provider_schemas["registry.terraform.io/hashicorp/local"].resource_schemas | keys[]'
local_file
local_sensitive_file

# The arguments of one specific resource.
$ terraform providers schema -json | jq -r \
  '.provider_schemas["registry.terraform.io/hashicorp/local"].resource_schemas.local_file.block.attributes | keys[]'
content
content_base64
filename
file_permission
id
...

  1. The Terraform Registry and the documentation

Providers are published in the Terraform Registry (registry.terraform.io). Learning to read their documentation is as important a skill as knowing HCL, because nobody memorises the arguments of 1,400 AWS resource types: you look them up.

The structure of a provider page:

Section What you will find
Overview The provider's configuration: arguments, authentication, minimal example
Resources Each resource, with arguments, attributes and examples
Data Sources Each data, with its filters and attributes
Guides Migration guides between major versions. Read them before upgrading
Version selector Top right: the documentation changes between versions

And the structure of a specific resource's page, with the vocabulary it uses:

  • Example Usage: the starting point. Copy it, adapt it, do not paste it blindly.
  • Argument Reference: what you write. Each entry says (Required) or (Optional), and the key phrase "Changing this forces a new resource to be created" is the one warning you about the -/+ in the plan.
  • Attribute Reference: what you can read, including the computed ones (id, arn).
  • Timeouts: how long Terraform waits before giving up. Adjustable with a timeouts block.
  • Import: how to adopt an existing object (the subject of Importing Resources).

A shortcut that saves a lot of time: the documentation for a specific version always lives at a predictable URL, registry.terraform.io/providers/<namespace>/<type>/<version>/docs. If your .terraform.lock.hcl pins 5.60.0, read that one, not the latest.

  1. Namespaces and source addresses

A provider's full address has three parts:

[<HOSTNAME>/]<NAMESPACE>/<TYPE>

registry.terraform.io/hashicorp/aws
└──── host (optional) ────┘ └namespace┘ └type┘

If you leave out the host, registry.terraform.io is assumed. That is why hashicorp/aws and registry.terraform.io/hashicorp/aws are the same thing.

Provider kind source example Who maintains it
HashiCorp official hashicorp/aws, hashicorp/random HashiCorp
Partner integrations/github, cloudflare/cloudflare The vendor, verified
Community carlpett/sops, bpg/proxmox Individuals or organisations
Private registry registry.ecomarket.example.com/plataforma/internal Your own company

An operational warning about community providers: a provider is a binary that runs on your machine with your credentials. Before adding a little-known one to ecomarket-infra, review the repository, the release cadence and who signs it. Terraform verifies the signatures of official and partner providers; community ones are validated by hash through the lock file, which is a weaker guarantee.

Private mirrors. In environments with no internet access or with supply-chain controls, a mirror is configured in ~/.terraformrc (the file you created in module 1):

# ~/.terraformrc — EcoMarket's provider cache and mirror
plugin_cache_dir = "$HOME/.terraform.d/plugin-cache"

provider_installation {
  # Every provider is downloaded from the internal mirror...
  network_mirror {
    url = "https://mirror-terraform.ecomarket.example.com/"
  }

  # ...except the ones listed here, which go to the public registry.
  direct {
    exclude = ["registry.terraform.io/*/*"]
  }
}

There is also filesystem_mirror (a local directory holding the binaries) and dev_overrides, which points at a locally compiled provider you are developing. dev_overrides disables the lock file and makes init warn you: never leave it switched on in a machine that deploys for real.

  1. required_providers and version constraints

The required_providers block, inside terraform, declares which providers this configuration needs and with which versions:

terraform {
  required_providers {
    # "local" is the LOCAL NAME: it is what resources and provider
    # blocks inside this configuration refer to.
    local = {
      source  = "hashicorp/local"
      version = "~> 2.5"
    }

    random = {
      source  = "hashicorp/random"
      version = "~> 3.6"
    }

    tls = {
      source  = "hashicorp/tls"
      version = "~> 4.0"
    }

    http = {
      source  = "hashicorp/http"
      version = "~> 3.4"
    }
  }
}

The local name (the key) usually matches the type, but it does not have to. It comes in handy when two different providers share a name:

terraform {
  required_providers {
    # Two providers called "http" from different sources.
    http = {
      source = "hashicorp/http"
    }
    http_alternative = {
      source = "another-org/http"
    }
  }
}

The version constraint operators:

Operator Meaning Example Versions allowed
(none) or = Exactly that one = 5.60.0 5.60.0 only
!= Any except that one != 5.61.0 All but 5.61.0
> >= Greater / greater or equal >= 5.0.0 5.0.0 and above
< <= Less / less or equal < 6.0.0 Up to 5.x
~> "Pessimistic": allows the last component to move ~> 3.6 >= 3.6.0, < 4.0.0
~> with three components Patches only ~> 3.6.1 >= 3.6.1, < 3.7.0
Range Several conditions separated by commas >= 5.0.0, < 6.0.0 The whole of 5.x

The ~> operator deserves attention because its behaviour depends on how many components you write, and it is the number one source of confusion:

version = "~> 3"       # >= 3.0.0, < 4.0.0   (allows minor and patch changes)
version = "~> 3.6"     # >= 3.6.0, < 4.0.0   (the same: the last component is the minor)
version = "~> 3.6.1"   # >= 3.6.1, < 3.7.0   (patches only)

Which constraint to use, case by case:

Situation Recommended constraint Why
EcoMarket's root module ~> 5.60 Allows patches and improvements, blocks breaking changes
A published reusable module >= 5.0.0, < 6.0.0 Permissive: the consumer decides the exact point
A provider with an unstable track record ~> 2.3.1 Patches only
Debugging a specific failure = 5.60.0 Absolute reproducibility, temporarily
No constraint Never The plan can change from one day to the next

An important nuance about modules: Terraform intersects all the constraints from all the modules. If your root asks for ~> 5.60 and a child module asks for < 5.50, no version satisfies both and init fails:

$ terraform init
╷
│ Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider
│ hashicorp/aws: no available releases match the given constraints
│ ~> 5.60, < 5.50
╵

That is why reusable modules must declare broad constraints: a narrow constraint in a child module blocks every one of its consumers.

  1. required_version versus provider versions

These are two different things that get confused constantly:

required_version required_providers { version }
What it versions The Terraform binary Each provider plugin
Where it is declared Directly in terraform {} Inside required_providers
Who installs it You, or tfenv terraform init, automatically
Recorded in .terraform-version (by convention) .terraform.lock.hcl
When it is breached An error before anything is done An error at init
terraform {
  # BINARY version. EcoMarket pinned 1.9.8 in .terraform-version
  # with tfenv during module 1.
  required_version = ">= 1.9.0, < 2.0.0"

  required_providers {
    # PLUGIN versions.
    local = { source = "hashicorp/local", version = "~> 2.5" }
  }
}

And this is what the binary version error looks like:

$ terraform plan
╷
│ Error: Unsupported Terraform Core version
│
│   on versions.tf line 2, in terraform:
│    2:   required_version = ">= 1.9.0, < 2.0.0"
│
│ This configuration does not support Terraform version 1.5.7. To proceed,
│ either choose another supported Terraform version or update this version
│ constraint.
╵

The fact that it appears before any operation is precisely the point: it fails fast and with a clear message, instead of failing halfway through an apply because of a function that version does not know.

  1. .terraform.lock.hcl: the version contract

You saw it in module 1; now it is time to understand it properly. The lock file records exactly which version and which binary was used, so that the whole team and the CI run the same thing.

# .terraform.lock.hcl
# This file is maintained automatically by "terraform init".
# Manual edits may be lost in future updates.

provider "registry.terraform.io/hashicorp/local" {
  # The EXACT version that was installed.
  version = "2.5.2"

  # The constraint that was in the configuration when it was resolved.
  constraints = "~> 2.5"

  hashes = [
    # h1: hash of the complete package for THIS platform.
    "h1:JlMZD6nYqJ8sSrFfEAH0Vk/SL8WLZRmFaMUF9PJK5wM=",
    # zh: hashes from the checksum file signed by the author.
    # There is one per published platform.
    "zh:136299545178ce281c56f36965bf91c35407c11897f7082b3b983d86cb79b511",
    "zh:3b4486858aa9cb8163378722b642c57c529b6c64bfbfc9461d940a84cd66ebea",
    "zh:4855ee628ead6d9b4a4a2a3e15e9fe7ac1a60d7c0e02b1b5a83a5f5a8f7e1f8b",
  ]
}
Field What it means If it is missing or does not match
version The installed version init will install this one, not another
constraints The constraint in force when it was resolved Informational
h1: Hash of your platform's package init fails if the downloaded binary does not match
zh: Signed hashes for every platform init fails on a platform with no hash of its own

The commands you need:

# 1. Install respecting the lock (the normal case).
$ terraform init

# 2. Upgrade to the newest version the constraints allow,
#    and rewrite the lock file.
$ terraform init -upgrade
- Finding hashicorp/local versions matching "~> 2.5"...
- Installing hashicorp/local v2.5.3...
- Installed hashicorp/local v2.5.3 (signed by HashiCorp)

Terraform has made some changes to the provider dependency selections recorded
in the .terraform.lock.hcl file. Review those changes and commit them to your
version control system if they represent changes you intended to make.

# 3. Add the hashes for OTHER platforms to the lock.
$ terraform providers lock \
    -platform=linux_amd64 \
    -platform=darwin_arm64 \
    -platform=windows_amd64

Command 3 solves a very real problem at EcoMarket: the team develops on macOS with Apple Silicon (darwin_arm64) and the pipeline runs on Linux (linux_amd64). If the lock file only holds the macOS hash, the CI's init fails:

$ terraform init
╷
│ Error: Failed to install provider
│
│ Error while installing hashicorp/local v2.5.2: the current package for
│ registry.terraform.io/hashicorp/local 2.5.2 doesn't match any of the
│ checksums previously recorded in the dependency lock file.
╵

Running terraform providers lock -platform=... once, with every platform the team uses, and committing the result removes this class of incident for good.

Rules about the lock file:

  1. It is committed to Git, always. Your module 1 .gitignore already respects that.
  2. It is not edited by hand. The header comment says so.
  3. Changes to it are reviewed as code. A provider upgrade is a potential change of behaviour: it deserves a pull request of its own.
  4. If Inconsistent dependency lock file appears, the cause is usually that somebody changed a constraint without running init. The fix: terraform init -upgrade and commit the file.

  1. Configuring a provider

The provider block adjusts how a provider instance behaves. Its arguments are defined by each provider, not by Terraform.

# ILLUSTRATIVE AWS example: it will actually be deployed in module 5.
# provider "aws" {
#   region = var.region   # eu-west-1
#
#   # Tags applied automatically to ALL resources that accept them.
#   # It saves repeating tags = local.common_tags on every resource.
#   default_tags {
#     tags = local.common_tags
#   }
#
#   # Retries on transient API errors.
#   max_retries = 5
#
#   # A check that we are in the right account: if the profile points
#   # at another account, the plan fails instead of creating resources
#   # in the wrong place. It is an excellent safeguard.
#   allowed_account_ids = ["123456789012"]
# }

Rules of the provider block:

  • It is optional if the provider needs no configuration. local and random do not; we declared them in module 1 for documentation clarity.
  • There can only be one block without alias per provider: that is the default instance.
  • Its arguments can use variables and locals, but not references to resources or data sources managed in the same configuration. Terraform needs to configure the providers before building the graph; a circular dependency there would be impossible to resolve.
provider "aws" {
  region = var.region                      # correct: a variable

  # assume_role {
  #   role_arn = aws_iam_role.deployment.arn  # ERROR: a resource of this config
  # }
}

  1. alias and multiple instances

When you need two configurations of the same provider — two regions, two accounts, two clusters — you declare an extra instance with alias.

The EcoMarket case: two regions

# ILLUSTRATIVE AWS example (module 5).
# ---------------------------------------------------------------------------
# provider "aws" {
#   region = "eu-west-1"          # DEFAULT instance, no alias
#   default_tags { tags = local.common_tags }
# }
#
# provider "aws" {
#   alias  = "replica"
#   region = "eu-central-1"       # secondary instance: Frankfurt
#   default_tags { tags = local.common_tags }
# }
#
# # The main images bucket, in Ireland.
# resource "aws_s3_bucket" "images" {
#   bucket = "${local.prefix}-images-${random_id.suffix_hex.hex}"
# }
#
# # The disaster recovery replica, in Frankfurt.
# resource "aws_s3_bucket" "images_replica" {
#   provider = aws.replica        # NO quotes
#   bucket   = "${local.prefix}-images-dr-${random_id.suffix_hex.hex}"
# }
#
# # A data source can pick an instance too.
# data "aws_region" "replica" {
#   provider = aws.replica
# }

The same mechanism, runnable without a cloud account

The mechanism is identical with any provider. Let us build it with tls and local, which you can run right now. EcoMarket needs two self-signed certificate pairs for testing: one for the web front end and one for internal communications.

# versions.tf
terraform {
  required_version = ">= 1.9.0"

  required_providers {
    tls = {
      source  = "hashicorp/tls"
      version = "~> 4.0"
    }
    local = {
      source  = "hashicorp/local"
      version = "~> 2.5"
    }
  }
}
# providers.tf

# DEFAULT instance of the local provider.
provider "local" {}

# A second instance, with an alias. The "local" provider has no configuration
# arguments, so both instances behave the same: what we are demonstrating
# here is the selection MECHANISM, which is exactly the one you will
# use with two AWS regions in module 5.
provider "local" {
  alias = "audit"
}

# The tls provider does accept configuration (a proxy block), which
# makes it possible, for example, to have one instance going out through
# the corporate proxy and another that does not.
provider "tls" {}

provider "tls" {
  alias = "corporate"

  # proxy {
  #   url = "https://proxy.ecomarket.example.com:8080"
  # }
}
# main.tf
locals {
  prefix = "${var.project}-${var.environment}"
}

# --- Web front end certificate: default tls instance ---
resource "tls_private_key" "web" {
  algorithm = "RSA"
  rsa_bits  = 2048
}

resource "tls_self_signed_cert" "web" {
  private_key_pem = tls_private_key.web.private_key_pem

  subject {
    common_name  = "${local.prefix}.ecomarket.example.com"
    organization = "EcoMarket (test environment)"
  }

  validity_period_hours = 720 # 30 days
  allowed_uses          = ["key_encipherment", "digital_signature", "server_auth"]
}

# --- Internal certificate: "corporate" tls instance ---
resource "tls_private_key" "internal" {
  provider = tls.corporate

  algorithm = "ECDSA"
  ecdsa_curve = "P256"
}

resource "tls_self_signed_cert" "internal" {
  provider = tls.corporate

  private_key_pem = tls_private_key.internal.private_key_pem

  subject {
    common_name  = "internal.${local.prefix}.ecomarket.example.com"
    organization = "EcoMarket (internal)"
  }

  validity_period_hours = 720
  allowed_uses          = ["key_encipherment", "digital_signature", "server_auth"]
}

# --- Writing files with the two local instances ---
resource "local_file" "web_cert" {
  # Default instance of local.
  filename        = "${path.module}/certs/${local.prefix}-web.pem"
  content         = tls_self_signed_cert.web.cert_pem
  file_permission = "0644"
}

resource "local_sensitive_file" "web_key" {
  # local_sensitive_file hides the content in the plan and creates the file
  # with 0600 permissions by default. It is the right resource for keys.
  filename = "${path.module}/certs/${local.prefix}-web-key.pem"
  content  = tls_private_key.web.private_key_pem
}

resource "local_file" "audit_log" {
  provider = local.audit

  filename        = "${path.module}/audit/${local.prefix}-certificates.json"
  file_permission = "0640"

  content = jsonencode({
    environment = var.environment
    certificates = {
      web = {
        cn          = tls_self_signed_cert.web.subject[0].common_name
        algorithm   = tls_private_key.web.algorithm
        valid_until = tls_self_signed_cert.web.validity_end_time
      }
      internal = {
        cn        = tls_self_signed_cert.internal.subject[0].common_name
        algorithm = tls_private_key.internal.algorithm
      }
    }
  })
}
$ terraform init && terraform apply -auto-approve
tls_private_key.web: Creating...
tls_private_key.internal: Creating...
tls_self_signed_cert.web: Creating...
tls_self_signed_cert.internal: Creating...
local_file.web_cert: Creating...
local_sensitive_file.web_key: Creating...
local_file.audit_log: Creating...

Apply complete! Resources: 7 added, 0 changed, 0 destroyed.

$ ls certs audit
audit/ecomarket-dev-certificates.json
certs/ecomarket-dev-web-key.pem
certs/ecomarket-dev-web.pem

# The private key was created with restrictive permissions automatically.
$ stat -c '%a %n' certs/*
600 certs/ecomarket-dev-web-key.pem
644 certs/ecomarket-dev-web.pem

Security warning: even though these keys are self-signed and for testing, they sit in plain text in terraform.tfstate. The certs/ files and the state must be in .gitignore. For real certificates, the proper approach is a dedicated service (ACM, Let's Encrypt through a specific provider, Vault) and an encrypted backend, as we will see in Remote State and in Security Best Practices.

Rules for aliases:

  1. The instance without alias is the default one; every resource that says nothing uses it.
  2. provider = tls.corporate is written without quotes: it is a reference, not a string.
  3. The provider meta-argument goes at the top of the resource body, next to count or for_each.
  4. An alias that does not exist produces the error reference to undefined provider.
  5. You can have a configuration with aliases only, with no default instance, but then every resource of that provider must say which one it uses.

  1. Providers and modules

This section is an overview; the complete design of modules is module 4.

Automatic inheritance

A child module inherits the default instances of its providers from the module that calls it, with nothing to declare:

module "storage" {
  source = "./modules/storage"

  prefix = local.prefix
  # It automatically inherits the default instances of local, random, tls...
}

Passing aliased instances explicitly

Aliases are not inherited: they have to be passed with the providers meta-argument:

module "primary_storage" {
  source = "./modules/storage"
  prefix = local.prefix
  # No "providers": it inherits the default instances.
}

module "replica_storage" {
  source = "./modules/storage"
  prefix = "${local.prefix}-dr"

  # The map says: "inside this module, whatever is called aws
  # will actually be the parent's aws.replica instance".
  providers = {
    aws = aws.replica
  }
}

The same mechanism, runnable with our example:

module "certificate_audit" {
  source = "./modules/audit"

  providers = {
    local = local.audit
    tls   = tls.corporate
  }
}

A module can also receive several instances at once, by declaring it like this:

# In the child module: modules/replication/versions.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.0.0"
      # The module DECLARES that it needs two instances with these names.
      configuration_aliases = [aws.primary, aws.secondary]
    }
  }
}
# In the parent module
module "replication" {
  source = "./modules/replication"

  providers = {
    aws.primary   = aws           # the default instance
    aws.secondary = aws.replica   # the aliased instance
  }
}

Why you do NOT configure a provider inside a reusable module

This is one of Terraform's most important design rules, and the reason is concrete:

# modules/storage/main.tf
# DO NOT DO THIS in a module meant to be reused!
provider "aws" {
  region = "eu-west-1"
}

resource "aws_s3_bucket" "data" {
  bucket = var.name
}

What it breaks:

Problem Consequence
The consumer loses control It cannot deploy the module to another region or with other credentials
count or for_each on the module become impossible Terraform forbids it outright when the module brings its own provider
Removing the module gets complicated Destroying the resources needs the provider configuration, which disappears along with the module
Duplicated, inconsistent configuration Each module defines its own region, its own retries, its own tags

The error you will see if you try it with for_each:

╷
│ Error: Module is incompatible with count, for_each, and depends_on
│
│ The module at module.storage is a legacy module which contains its own
│ local provider configurations, and so calls to it may not use the count,
│ for_each, or depends_on arguments.
╵

The rule: provider blocks live only in the root module. Reusable modules declare what they need in required_providers (with configuration_aliases if they need several instances) and receive the configurations from the parent.

  1. Authentication and credentials

Every provider has its own mechanism, but they all follow the same precedence pattern: arguments in the provider block → environment variables → credential files → machine identity.

The golden rule, with no exceptions:

Never write credentials in a .tf file, in a committed .tfvars or on the command line. A .tf ends up in Git; a secret in Git is a compromised secret, even if you delete the commit afterwards.

# ❌ NEVER. This will end up in the repository.
# provider "aws" {
#   region     = "eu-west-1"
#   access_key = "AKIAIOSFODNN7EXAMPLE"
#   secret_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
# }

# ✅ Correct: the provider never mentions credentials.
# provider "aws" {
#   region = var.region
# }

The acceptable approaches, from least to most recommended:

Mechanism How it is used When
Environment variables AWS_ACCESS_KEY_ID, ARM_CLIENT_SECRET, GOOGLE_CREDENTIALS Locally and in simple CI
Credentials file ~/.aws/credentials, ~/.azure/, gcloud auth Local development
Profiles profile = "ecomarket-dev" in the provider block Several accounts on the same machine
Role assumption An assume_role block with role_arn Separating accounts per environment
Machine identity Instance role, managed identity, workload identity Self-hosted servers and runners
OIDC / federation The CI obtains an ephemeral token through a trust relationship The best option for CI/CD

Annotated examples:

# 1. Environment variables (cloud providers, illustrative).
$ export AWS_ACCESS_KEY_ID="..."
$ export AWS_SECRET_ACCESS_KEY="..."
$ export AWS_REGION="eu-west-1"

# 2. A named profile, defined in ~/.aws/credentials.
$ export AWS_PROFILE=ecomarket-dev
$ terraform plan

# 3. Terraform variables for APPLICATION secrets
#    (not cloud ones), from the team's secrets manager.
$ export TF_VAR_db_password="$(pass show ecomarket/dev/postgres)"
# 4. Profile and role assumption declared in the provider (ILLUSTRATIVE, module 5).
# provider "aws" {
#   region  = var.region
#   profile = var.aws_profile        # the profile name, NOT credentials
#
#   assume_role {
#     role_arn     = "arn:aws:iam::123456789012:role/ecomarket-terraform"
#     session_name = "terraform-${var.environment}"
#   }
# }

Hygiene checks for the ecomarket-infra repository:

# Before every commit: look for credential patterns.
$ git diff --cached | grep -iE 'access_key|secret|password|BEGIN .* PRIVATE KEY'

# Better still: an automatic scanner as a pre-commit hook.
$ gitleaks protect --staged --verbose

And the reminder that links to module 3: even if you put no credentials in the code, the state can contain them anyway, because many resources store generated passwords or private keys. The real protection is an encrypted remote backend with access control, which is what comes next. The full treatment is in Security Best Practices.

  1. Useful providers beyond the cloud

Terraform is not only for cloud infrastructure. These providers solve everyday problems, and you have already used several of them:

Provider source What it is for Needs an account?
random hashicorp/random Suffixes, passwords, UUIDs kept stable in the state No
local hashicorp/local Creating and reading files on disk No
tls hashicorp/tls Keys, CSRs and self-signed certificates No
http hashicorp/http Querying REST APIs from a data source No
null hashicorp/null The legacy null_resource (use terraform_data) No
time hashicorp/time Waits, scheduled rotation, stable timestamps No
external hashicorp/external Running a program that returns JSON No
archive hashicorp/archive Packing files into a ZIP (serverless functions) No
dns hashicorp/dns DNS records via RFC 2136 A DNS server
kubernetes hashicorp/kubernetes Objects in a Kubernetes cluster A cluster
helm hashicorp/helm Installing Helm charts A cluster
github integrations/github Repositories, teams, protected branches, secrets A token
docker kreuzwerker/docker Local or remote images and containers Docker
postgresql cyrilgdn/postgresql Databases, roles and permissions inside PostgreSQL A server
vault hashicorp/vault Reading and writing secrets in HashiCorp Vault Vault

The time provider deserves a mention because it elegantly solves the idempotence problem you saw in the previous lesson with timestamp():

terraform {
  required_providers {
    time = {
      source  = "hashicorp/time"
      version = "~> 0.11"
    }
  }
}

resource "time_static" "created" {
  # Captures the timestamp ONCE ONLY, when it is created, and stores it
  # in the state. On subsequent plans it does NOT change, so it
  # generates no noise. It is the correct alternative to timestamp().
}

resource "time_rotating" "cert_rotation" {
  # This resource is "replaced" every 30 days, which lets you chain
  # the automatic rotation of a secret or a certificate.
  rotation_days = 30
}

resource "local_file" "inventory" {
  filename = "${path.module}/${local.prefix}-inventory.json"
  content = jsonencode({
    environment = var.environment
    created_at  = time_static.created.rfc3339 # stable between runs
    rotation_id = time_rotating.cert_rotation.id
  })
}

One idea worth internalising: any system with an API can have a provider. The ecomarket-infra repository will end up managing, on top of the cloud, the team's GitHub repositories, the PostgreSQL roles and the monitoring alerts, all through the same plan / apply flow.

  1. When a provider changes major version

Sooner or later AWS will publish version 6.0 and your ~> 5.60 constraint will stop bringing anything new. A major version means breaking changes: removed arguments, renamed resources, different behaviours.

The safe procedure, applied to EcoMarket:

flowchart TD
    A["1. Read the migration guide<br/>in the Registry (Guides section)"] --> B["2. A new branch in ecomarket-infra"]
    B --> C["3. Widen the constraint<br/>~> 5.60  →  ~> 6.0"]
    C --> D["4. terraform init -upgrade"]
    D --> E["5. terraform plan in DEV<br/>and read it in full"]
    E --> F{"Does the plan propose<br/>unexpected changes?"}
    F -->|Yes| G["Adjust the configuration<br/>following the guide"]
    G --> E
    F -->|No| H["6. apply in dev → staging → prod"]
    H --> I["7. Commit .terraform.lock.hcl"]

In detail:

# 1. A dedicated branch: a provider upgrade is a change, not a formality.
$ git checkout -b upgrade-aws-provider-6

# 2. Widen the constraint in versions.tf
#    version = "~> 5.60"  ->  version = "~> 6.0"

# 3. Update the plugins and the lock file.
$ terraform init -upgrade
- Finding hashicorp/aws versions matching "~> 6.0"...
- Installing hashicorp/aws v6.0.1...

# 4. Add the hashes for every platform the team uses.
$ terraform providers lock -platform=linux_amd64 -platform=darwin_arm64

# 5. ALWAYS plan in the least critical environment first.
$ terraform plan -var-file=dev.tfvars

What to look for in that plan, in order of seriousness:

Sign Seriousness What to do
must be replaced on a resource holding data Critical Stop. Check the guide; there is usually a moved or a new argument
Warning: Argument is deprecated Medium Migrate to the new argument now, before it disappears
Error: Unsupported argument High The argument was removed: the guide names the replacement
Changes to default values (~) Medium Check whether the new value is acceptable
0 to add, 0 to change, 0 to destroy None A clean upgrade

Practical tips:

  • Upgrade one provider at a time. If you change AWS and Kubernetes together and something breaks, you will not know which one did it.
  • Skip one major version at a time. From 4 to 6 by way of 5, not in one jump.
  • Do not move past a major version without reading the guide. They are long, but they are written for exactly what is about to happen to you.
  • Keep prevent_destroy on the critical resources during the migration. If the upgrade proposes destroying the prod database, that safety catch will stop the entire plan before anyone types yes.
  • Automate the notification, not the application. A tool such as Dependabot or Renovate can open the pull request with the version bump; reviewing the plan remains a human job.

Common Mistakes and Tips

  • Leaving out version in required_providers. It means "whatever is newest": your plan can change simply because somebody published a new version. Always pin a constraint.
  • Confusing ~> 3.6 with ~> 3.6.0. The first allows anything up to 3.x; the second, only patches of 3.6. It is the most expensive misunderstanding in constraints.
  • Not committing .terraform.lock.hcl. Each person and the CI will install different versions, and differences will appear that are impossible to reproduce.
  • Forgetting terraform providers lock -platform=... on mixed teams. The Linux CI will fail with a checksum error that says nothing about the real cause.
  • Writing provider = "aws.replica" with quotes. It is a reference, not a string.
  • Declaring two provider blocks without alias for the same provider. Error: Duplicate provider configuration. There can be only one default instance.
  • Configuring a provider inside a reusable module. It disables count, for_each and depends_on on calls to that module, and complicates removing it.
  • Assuming aliases are inherited by modules. They are not: you have to pass them with providers = { ... }.
  • Referencing a resource from a provider's configuration. It is not possible: providers are configured before the graph is built.
  • Credentials in a .tf or in a committed .tfvars. It is the most common kind of leak. Environment variables, profiles or roles; never literals.
  • Leaving dev_overrides active in ~/.terraformrc. It disables the lock file and makes you use an unverified provider in real deployments.
  • Tip: run terraform providers when you do not understand where a version constraint comes from. It will tell you which module imposes it.
  • Tip: add allowed_account_ids (or its equivalent in your cloud) to the provider block. It is one line that prevents the worst kind of incident: deploying to the wrong account.
  • Tip: treat provider upgrades as code changes, with their branch, their pull request and their reviewed plan. The lock file is part of the diff.

Exercises

Exercise 1: version constraints and the lock file

Working on EcoMarket's infra directory:

  1. Change the hashicorp/local constraint from ~> 2.5 to = 2.5.1, run terraform init -upgrade and observe what changes in .terraform.lock.hcl.
  2. Go back to ~> 2.5, run terraform init -upgrade and compare.
  3. Try an impossible constraint, ~> 2.5, < 2.0, and note the exact error.
  4. Run terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64 and count how many zh: lines and how many h1: lines there now are for each provider. Explain the difference between the two kinds of hash.
  5. Answer this: why must the lock file be committed to Git while the .terraform/ directory must not?

Exercise 2: two provider instances, runnable

Build an exercise-providers directory from scratch that:

  1. Uses hashicorp/tls and hashicorp/local with suitable ~> constraints.
  2. Declares two local instances: the default one and one with alias = "audit".
  3. Generates two different private keys, a 2048-bit RSA one for the front end and an ECDSA P-256 one for internal communication, with their 30-day self-signed certificates.
  4. Writes the certificates into certs/ with the default instance and a JSON log into audit/ with the audit instance, using local_sensitive_file for anything that is a private key.
  5. Publishes an output with the identity (not cert_pem; use the common name and the expiry date) of both certificates.
  6. Check the permissions of the generated files with ls -l and explain why local_sensitive_file is preferable to local_file for keys.

Exercise 3: diagnosing a broken provider configuration

A colleague has written this and it does not work. Find five distinct problems, explain the error each one produces and fix them:

# versions.tf
terraform {
  required_version = ">= 1.9.0"

  required_providers {
    local = {
      source = "hashicorp/local"
    }
    tls = {
      source  = "hashicorp/tls"
      version = "~> 4.0.0"
    }
  }
}

# providers.tf
provider "local" {}

provider "local" {
  alias = "audit"
}

provider "local" {}

# modules/audit/main.tf  (a reusable module)
provider "local" {
  alias = "internal"
}

resource "local_file" "log" {
  provider = "local.internal"
  filename = "${path.module}/log.txt"
  content  = "ok"
}

# main.tf
module "audit" {
  source   = "./modules/audit"
  for_each = toset(["dev", "prod"])
}

Solutions

Solution 1:

With = 2.5.1:

$ terraform init -upgrade
- Finding hashicorp/local versions matching "2.5.1"...
- Installing hashicorp/local v2.5.1...

$ grep -A3 'hashicorp/local' .terraform.lock.hcl
provider "registry.terraform.io/hashicorp/local" {
  version     = "2.5.1"
  constraints = "2.5.1"
  hashes = [

Two fields change: version (the installed version) and constraints (the constraint in force when it was resolved), plus the hashes, because they belong to that specific version's package.

Going back to ~> 2.5:

$ terraform init -upgrade
- Installing hashicorp/local v2.5.2...

$ grep -A3 'hashicorp/local' .terraform.lock.hcl
provider "registry.terraform.io/hashicorp/local" {
  version     = "2.5.2"
  constraints = "~> 2.5"

Terraform picks the highest compatible version, not the one that was there before.

With the impossible constraint:

$ terraform init
╷
│ Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider
│ hashicorp/local: no available releases match the given constraints
│ ~> 2.5, < 2.0
╵

After the multi-platform providers lock, there is one h1: and one zh: per platform (plus the zh: of the checksum file). The difference:

Hash What it covers When it is used
h1: The unpacked package for one specific platform Local verification after the download
zh: The ZIP file exactly as the author published it, with the GPG signature Verifying the origin and integrity of the official package

Point 5: .terraform.lock.hcl is committed because it is the team's reproducible contract: it defines which versions and which exact binaries are used, and changes to it must be reviewed. .terraform/ is not committed because it holds binaries of tens or hundreds of megabytes, specific to one platform and regenerable at any moment with terraform init. It is the same distinction as between package-lock.json and node_modules/.

Solution 2:

# versions.tf
terraform {
  required_version = ">= 1.9.0"

  required_providers {
    tls   = { source = "hashicorp/tls", version = "~> 4.0" }
    local = { source = "hashicorp/local", version = "~> 2.5" }
  }
}
# providers.tf
provider "local" {}

provider "local" {
  alias = "audit"
}

provider "tls" {}
# main.tf
locals {
  prefix = "ecomarket-dev"
}

# --- Web front end: RSA 2048 ---
resource "tls_private_key" "web" {
  algorithm = "RSA"
  rsa_bits  = 2048
}

resource "tls_self_signed_cert" "web" {
  private_key_pem = tls_private_key.web.private_key_pem

  subject {
    common_name  = "${local.prefix}.ecomarket.example.com"
    organization = "EcoMarket (testing)"
  }

  validity_period_hours = 720
  allowed_uses          = ["key_encipherment", "digital_signature", "server_auth"]
}

# --- Internal: ECDSA P-256 ---
resource "tls_private_key" "internal" {
  algorithm   = "ECDSA"
  ecdsa_curve = "P256"
}

resource "tls_self_signed_cert" "internal" {
  private_key_pem = tls_private_key.internal.private_key_pem

  subject {
    common_name  = "internal.${local.prefix}.ecomarket.example.com"
    organization = "EcoMarket (internal)"
  }

  validity_period_hours = 720
  allowed_uses          = ["key_encipherment", "digital_signature", "server_auth"]
}

# --- Files: default instance of local ---
resource "local_file" "web_cert" {
  filename        = "${path.module}/certs/${local.prefix}-web.pem"
  content         = tls_self_signed_cert.web.cert_pem
  file_permission = "0644"
}

resource "local_file" "internal_cert" {
  filename        = "${path.module}/certs/${local.prefix}-internal.pem"
  content         = tls_self_signed_cert.internal.cert_pem
  file_permission = "0644"
}

resource "local_sensitive_file" "web_key" {
  filename = "${path.module}/certs/${local.prefix}-web-key.pem"
  content  = tls_private_key.web.private_key_pem
}

resource "local_sensitive_file" "internal_key" {
  filename = "${path.module}/certs/${local.prefix}-internal-key.pem"
  content  = tls_private_key.internal.private_key_pem
}

# --- Audit log: the aliased instance ---
resource "local_file" "audit" {
  provider = local.audit

  filename        = "${path.module}/audit/${local.prefix}-certificates.json"
  file_permission = "0640"

  content = jsonencode({
    generated_by = "terraform"
    certificates = [
      {
        use         = "web"
        cn          = tls_self_signed_cert.web.subject[0].common_name
        algorithm   = tls_private_key.web.algorithm
        valid_until = tls_self_signed_cert.web.validity_end_time
      },
      {
        use         = "internal"
        cn          = tls_self_signed_cert.internal.subject[0].common_name
        algorithm   = tls_private_key.internal.algorithm
        valid_until = tls_self_signed_cert.internal.validity_end_time
      },
    ]
  })
}
# outputs.tf
output "certificates" {
  description = "Summary of the generated certificates."
  value = {
    web = {
      cn          = tls_self_signed_cert.web.subject[0].common_name
      valid_until = tls_self_signed_cert.web.validity_end_time
    }
    internal = {
      cn          = tls_self_signed_cert.internal.subject[0].common_name
      valid_until = tls_self_signed_cert.internal.validity_end_time
    }
  }
}
$ terraform init && terraform apply -auto-approve
Apply complete! Resources: 9 added, 0 changed, 0 destroyed.

$ ls -l certs audit
audit:
-rw-r----- 1 dev dev  512 ecomarket-dev-certificates.json

certs:
-rw-r--r-- 1 dev dev 1204 ecomarket-dev-internal.pem
-rw------- 1 dev dev  227 ecomarket-dev-internal-key.pem
-rw-r--r-- 1 dev dev 1428 ecomarket-dev-web.pem
-rw------- 1 dev dev 1704 ecomarket-dev-web-key.pem

Why local_sensitive_file is preferable for keys, for two cumulative reasons:

  1. Permissions: it creates the file with 0600 by default, instead of 0777 (which local_file reduces to 0644 if you say so). Only the owner can read it.
  2. The plan: its content argument is marked as sensitive, so the content never appears in the output of plan or apply. With local_file, the complete private key would be printed to the terminal and into the CI logs.

What it does not solve: the key is still in plain text in terraform.tfstate, as warned in section 8.

Solution 3:

The five problems:

  1. local with no version constraint. It is not a runtime error, but it breaks the basic rule: terraform init will install the newest available version, and behaviour can change without anyone touching the code.
local = {
  source  = "hashicorp/local"
  version = "~> 2.5"
}
  1. Two provider "local" {} blocks without an alias.
╷
│ Error: Duplicate provider configuration
│
│ A default (non-aliased) provider configuration for "local" was already given
│ at providers.tf:2,1-17. If multiple configurations are required, set the
│ "alias" argument for alternative configurations.
╵

The fix: delete the third block. There can be only one default instance.

  1. A provider block inside a reusable module. It turns the module into a legacy one and prevents using count, for_each and depends_on when calling it. The module must declare configuration_aliases and receive the instance from the parent:
# modules/audit/versions.tf
terraform {
  required_providers {
    local = {
      source                = "hashicorp/local"
      version               = ">= 2.0.0"
      configuration_aliases = [local.internal]
    }
  }
}
  1. provider = "local.internal" in quotes.
╷
│ Error: Invalid provider configuration reference
│
│ A provider configuration reference must not be given in quotes.
╵

The fix: provider = local.internal.

  1. for_each on a module that brings its own provider.
╷
│ Error: Module is incompatible with count, for_each, and depends_on
╵

It is solved by fixing problem 3. Once the module configures no providers, the call works by passing the instance explicitly:

# corrected main.tf
provider "local" {}

provider "local" {
  alias = "audit"
}

module "audit" {
  source   = "./modules/audit"
  for_each = toset(["dev", "prod"])

  environment = each.key

  providers = {
    # On the left, the name the module expects (its configuration_alias).
    # On the right, the parent module's real instance.
    local.internal = local.audit
  }
}

Notice that the corrected module decides nothing about the provider: it merely declares that it needs an instance called local.internal, and the parent chooses which one to pass. That inversion of control is what makes it possible to reuse the same module across two environments, two regions or two accounts.

Conclusion

With this lesson you have completed Terraform's configuration language:

  • A provider is a separate process that Terraform starts and talks to over gRPC; it supplies the resources' schema, their CRUD and the translation to the real API. terraform providers and terraform providers schema -json let you inspect all of it from the terminal.
  • The Registry is the source of truth for the documentation: Argument Reference for what you write, Attribute Reference for what you read, and the Guides before any major upgrade.
  • The source address has the form [host/]namespace/type; there are official, partner, community and private providers, and mirrors make it possible to operate without direct internet access.
  • Version constraints (=, !=, >=, <, ~>, ranges) are intersected across all modules; ~> 3.6 allows anything up to 3.x and ~> 3.6.1 only patches. required_version versions the binary; required_providers versions the plugins.
  • .terraform.lock.hcl is the team's reproducible contract: it is committed, never edited, updated with -upgrade and prepared for several platforms with terraform providers lock -platform=....
  • The provider block configures one instance and accepts variables, but not references to resources; alias creates extra instances that resources select with provider = name.alias, without quotes.
  • Modules inherit the default instances and receive the aliased ones through providers = { ... } and configuration_aliases; a reusable module never configures its own providers.
  • Credentials travel through environment variables, profiles, assumed roles or OIDC federation, never inside a .tf; and even then, the state can contain secrets.
  • Beyond the cloud there are providers for TLS, HTTP, time, Kubernetes, GitHub, Docker or PostgreSQL, and the same plan/apply flow works for all of them.
  • A major version upgrade is done on a branch, reading the guide, with init -upgrade, planning first in dev and reviewing every must be replaced.

With that you close the whole of module 2. EcoMarket now has a repository that speaks HCL fluently: well-chosen expressions and types, an interface of validated variables and documented outputs, resources that multiply with for_each without dangerous reindexing, protected lifecycles and providers pinned to versions that reproduce on every machine in the team. But there is one piece you have used in every plan without ever looking it in the eye: that terraform.tfstate file sitting on your laptop, in plain text, with no backup and with nothing stopping two people writing to it at the same time. While it stays there, EcoMarket cannot work as a team or deploy from a pipeline. In module 3, State Management, we will go after it: we will start with Understanding State to learn what it holds and why it is indispensable; we will carry on with State Files and their JSON anatomy alongside the terraform state commands; we will take the decisive step in Remote State, moving EcoMarket's state to a shared, encrypted backend; we will add concurrency safety in State Locking; and we will close with Declarative Refactoring, the moved and removed blocks that solve precisely the problem we left open in the previous lesson: migrating from count to for_each without destroying a single thing.

© Copyright 2026. All rights reserved