Introduction
This guide demonstrates how to configure and use credentials for multiple AWS accounts within a single HCP Terraform workspace. This is useful when your infrastructure resources need to be managed across different AWS environments from one configuration.
The recommended approach is to use provider aliases to define multiple configurations for the same provider.
Prerequisites
- An HCP Terraform account and an existing workspace.
- Credentials for two or more AWS accounts.
Procedure
Define multiple aliased providers in your Terraform configuration. In this example, the configuration sets up two AWS providers,
nik1andnik2, each with its own set of credentials passed in via variables.terraform { cloud { organization = "your_hcp_terraform_org_name" workspaces { name = "your_hcp_terraform_workspace_name" } } } variable "nik1_access_key" { description = "AWS access key for the first account." type = string sensitive = true } variable "nik1_secret_key" { description = "AWS secret key for the first account." type = string sensitive = true } variable "nik2_access_key" { description = "AWS access key for the second account." type = string sensitive = true } variable "nik2_secret_key" { description = "AWS secret key for the second account." type = string sensitive = true } provider "aws" { alias = "nik1" region = "us-east-1" access_key = var.nik1_access_key secret_key = var.nik1_secret_key } provider "aws" { alias = "nik2" region = "us-east-1" access_key = var.nik2_access_key secret_key = var.nik2_secret_key } resource "aws_instance" "ec1" { ami = "ami-0fc61db8544a617ed" instance_type = "t2.micro" provider = aws.nik1 tags = { Name = "nik-1" } } resource "aws_instance" "ec2" { ami = "ami-09a5b0b7edf08843d" instance_type = "t2.micro" provider = aws.nik2 tags = { Name = "nik-2" } }- In your HCP Terraform workspace, navigate to the Variables tab.
- Create the corresponding variables (
nik1_access_key,nik1_secret_key, etc.) and assign the appropriate credential values for each AWS account. Ensure the variable names in HCP Terraform exactly match the names declared in your configuration.
After you configure the variables, you can run a plan and apply. Terraform will use the aliased providers to authenticate to the correct AWS account for each resource.