Configuring Providers
Knowing the provider's address is half the job. You also have to tell it where to work, which account to use, and sometimes run it twice with different settings.
The rule
Declare it in required_providers, set it in a provider block, keep secrets out.
There are two separate pieces.
1. Declare which provider the configuration needs, inside the terraform block:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}The key aws is the provider's local name. Resource types that start with aws_ use it automatically.
2. Configure it with a provider block:
provider "aws" {
region = "ap-south-1"
}Which settings exist depends on the provider; for AWS, region is the main one. A provider block with no alias is the default configuration.
Aliases give you more than one configuration of the same provider, for example a second region:
provider "aws" {
alias = "virginia"
region = "us-east-1"
}
resource "aws_acm_certificate" "site" {
provider = aws.virginia
domain_name = "crumb.example"
}provider = aws.virginia (no quotes) picks the aliased one. Every other aws_ resource still uses the default.
A few providers need no settings at all; leave out their provider block and Terraform uses an empty default configuration. Many settings can also come from the environment: the AWS provider reads AWS_REGION if region is not set in the block, which is handy when one pipeline deploys to several regions.
Credentials do not belong in .tf files, which end up in Git. Providers read them from the environment: for AWS, AWS_PROFILE, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, the shared credentials file, or a role attached to the machine running Terraform.
The shortcut
For any provider question, ask "Declare, configure, or credential?" The answer tells you which place to look: required_providers, the provider block, or the environment.
Declare
Add
aws = { source = "hashicorp/aws" }underrequired_providers.
The trap: pasting an access key into the provider block "just to test". It gets committed, and leaked cloud keys are abused within minutes.
Drills
Answer fast — trust the rule.
Where do you state that a configuration needs the hashicorp/aws provider?
How does one resource use an aliased provider named virginia?
A config has a default aws provider and an aliased one. A resource sets no provider. Which does it use?
Where should AWS access keys come from?
Remember
- Declare in
required_providers, configure inprovider, credential from the environment. - Shortcut: ask "declare, configure, or credential?"
- Trap: keys in
.tffiles get committed and leaked.
