# Providers and version pinning

What a provider is, how to find one on the Terraform Registry, configure it with regions and aliases, and pin its version so every machine builds the same thing.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 3. About 25 minutes, beginner. Source: https://devops.rajeev.pro/courses/terraform/03-providers

## What you will learn

- Explain what a provider does and how Terraform core uses it
- Find a provider and its documentation on the Terraform Registry
- Write required_providers with a source and a version constraint
- Configure a provider, pass credentials safely and use an alias for a second region
- Read version constraints such as ~> 2.9 and choose one

> **Lab status.** **Verified lab:** terraform init and terraform providers with pinned providers. Run on Terraform 1.17.1; the output shown is real. <br />**Code walkthrough:** the AWS provider block, default_tags and the second-region alias: explained, not run. <br />**Cloud lab:** the alias example needs an AWS account to apply.

Terraform itself can't create a single server or file. Everything it manages goes through a
**provider**, a plugin that knows one platform's API. This lesson shows where providers come from,
how to configure them, and how to pin their versions so your laptop, your teammate's laptop and the
CI runner all build the same thing.

## What a provider is

> **Figure.** Terraform core reads the .tf files and the state, builds the dependency graph and decides what to create, update, replace or destroy, then calls providers to do each action. Three providers: hashicorp/aws calls AWS APIs for EC2, S3, IAM and VPC; hashicorp/local writes files on disk; hashicorp/random makes random values. terraform init downloads them from the Terraform Registry, which has over 5,000 providers in official, partner and community tiers, at the version set in required_providers.
>
> Core plans and orders the work; each provider turns actions into API calls for its platform.

When you run `terraform apply`:

1. **Terraform core** reads your `.tf` files and the state, and builds a dependency graph.
2. For each resource, it asks that resource's **provider** to plan the change: create, update,
   replace or nothing.
3. On apply, core tells the provider "create this", and the provider makes the real API call (for
   AWS, `RunInstances` to start an EC2 instance) and returns the result.

Providers are separate programs, released on their own schedule. The AWS provider adds new AWS
services every week without any change to Terraform itself.

## The Terraform Registry

**registry.terraform.io** lists thousands of providers. Each has a **source address** of the form
`namespace/name`, for example `hashicorp/aws`, `hashicorp/random` or `cloudflare/cloudflare`. Each
also has a **tier**:

| Tier      | Published by                                        | Example                                     |
| --------- | --------------------------------------------------- | ------------------------------------------- |
| Official  | HashiCorp                                           | `hashicorp/aws`, `hashicorp/local`          |
| Partner   | The technology's own company, verified by HashiCorp | `cloudflare/cloudflare`, `datadog/datadog`  |
| Community | Anyone                                              | Niche tools; check activity and maintainers |

Every provider page has documentation for each resource and data source: its arguments (inputs),
its attributes (outputs), and examples. You'll spend more time on these pages than anywhere else.
Search for the resource, copy the example, then remove what you don't need.

## Configuring providers

Two blocks are involved. `required_providers` (inside `terraform {}`) says **which** provider and
**which versions**. The `provider` block says **how** to configure it:

```hcl
# versions.tf
terraform {
  required_version = ">= 1.11"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.7"
    }
  }
}

# providers.tf
provider "aws" {
  region = "ap-south-1"

  default_tags {
    tags = {
      project    = "shop"
      managed_by = "terraform"
    }
  }
}
```

`default_tags` is an AWS-provider feature that adds the same tags to every resource it creates, so
nobody forgets the owner tag. Providers like `random` and `local` need no configuration at all.

### Credentials stay out of the code

Never put access keys in a provider block. Providers read the standard places their platform's
tools use. For AWS, that's environment variables (`AWS_PROFILE`, `AWS_REGION`), the shared config in
`~/.aws/`, SSO sessions, or an IAM role when running in AWS or in CI through OIDC (the CI/CD lesson
covers it). Keys in `.tf` files end up in Git history and in the state file.

### Several configurations with alias

One configuration can use the same provider twice, for example to put a TLS certificate in
`us-east-1` (CloudFront requires it there) while everything else is in Mumbai:

```hcl
provider "aws" {
  region = "ap-south-1"
}

provider "aws" {
  alias  = "us_east_1"
  region = "us-east-1"
}

resource "aws_acm_certificate" "cdn" {
  provider          = aws.us_east_1 # use the aliased configuration
  domain_name       = "shop.example.com"
  validation_method = "DNS"
}
```

Resources without a `provider` argument use the default (un-aliased) configuration.

## Version pinning

Providers change. A new major version can rename arguments or change defaults, and an unpinned
project can behave differently on Monday than it did on Friday. A **version constraint** sets which
versions are allowed:

| Constraint         | Allows                           | Typical use                             |
| ------------------ | -------------------------------- | --------------------------------------- |
| `"= 2.9.1"`        | exactly 2.9.1                    | Rarely; blocks even security fixes      |
| `">= 2.9"`         | 2.9 and anything newer, even 3.x | Libraries that must stay flexible       |
| `"~> 2.9"`         | `>= 2.9`, `< 3.0`                | **The usual choice for providers**      |
| `"~> 2.9.0"`       | `>= 2.9.0`, `< 2.10.0`           | Only patch releases                     |
| `">= 1.11, < 2.0"` | a range                          | `required_version` for Terraform itself |

`~>` is the "pessimistic" operator: only the **rightmost** number you wrote may increase. Pair the
constraint with the **lock file** from the next lesson, which records the exact version that was
chosen. The constraint says what's allowed; the lock file says what's actually used.

Check what a project needs with `terraform providers`, which printed this in the lab:

```sh
$ terraform providers

Providers required by configuration:
.
├── provider[registry.terraform.io/hashicorp/random] ~> 3.7
└── provider[registry.terraform.io/hashicorp/local] ~> 2.9
```

`registry.terraform.io/hashicorp/random` is the full source address; you write the short form
`hashicorp/random` and Terraform fills in the registry host.

> **In production.** Pin every provider with `~>` on the major version, and pin Terraform with `required_version`. Upgrade on purpose: bump the constraint in a pull request, run `terraform init -upgrade` and read the plan carefully, especially after a major provider release, which can come with an upgrade guide.

## Mission: Write a pinned versions.tf

Create a versions.tf that requires Terraform 1.11 or newer and pins hashicorp/local to 2.x and hashicorp/random to 3.x using the pessimistic operator. Run terraform init and terraform providers, and confirm the installed versions fall inside your constraints.

- You need: An empty folder
- You'll have: versions.tf

```sh
$ terraform init | grep Installed
$ terraform providers
$ grep -A2 'provider "registry' .terraform.lock.hcl
```

On the lab, init installed `hashicorp/random v3.9.1` for `~> 3.7` and `hashicorp/local v2.9.1` for
`~> 2.9`. Newer patch or minor versions are fine, as long as the major version matches your
constraint.

## Try it

- Open registry.terraform.io, find the hashicorp/random provider and read the docs for random_pet.
- Add the random provider to required_providers with `version = "~> 3.7"` and run `terraform init`.
- Run `terraform providers` and read the tree it prints.
- Change the constraint to `= 3.0.0`, run `terraform init -upgrade`, and note the version installed.
- Do the mini mission and keep `versions.tf`.

## Quiz

1. What does a provider do?
   - It stores Terraform state
   - **It is a plugin that knows one platform's API, so Terraform core can create, read, update and delete its resources** (answer)
   - It formats HCL files
   Why: Terraform core plans and orders work; providers such as hashicorp/aws or hashicorp/local translate each action into API calls.

2. Which versions does `version = "~> 2.9"` allow?
   - Only 2.9.0
   - **2.9 and later 2.x versions, but not 3.0** (answer)
   - Any version
   Why: The pessimistic constraint ~> 2.9 allows the rightmost number to grow, so >= 2.9 and < 3.0. Write ~> 2.9.0 to allow only 2.9.x patches.

3. You need resources in two AWS regions from one configuration. What do you use?
   - Two terraform blocks
   - **A second provider block with an alias, and provider = aws.<alias> on those resources** (answer)
   - Two state files only
   Why: Each provider configuration can have an alias. Resources pick a non-default one with the provider meta-argument.

4. Where should AWS credentials come from?
   - Typed into the provider block in main.tf
   - **The environment, such as AWS_PROFILE, SSO, or a CI role via OIDC; never committed to code** (answer)
   - A variable with a default value
   Why: Providers read standard credential sources. Credentials in .tf files end up in Git and in state.

## Resources

- [Providers overview](https://developer.hashicorp.com/terraform/language/providers) (HashiCorp)
- [Provider requirements (required_providers)](https://developer.hashicorp.com/terraform/language/providers/requirements) (HashiCorp)
- [Version constraints](https://developer.hashicorp.com/terraform/language/expressions/version-constraints) (HashiCorp)
- [Provider configuration and aliases](https://developer.hashicorp.com/terraform/language/providers/configuration) (HashiCorp)
- [Terraform Registry](https://registry.terraform.io/browse/providers) (HashiCorp)
