Assuming Multiple roles

Hi All, I was wondering what is the best approach to build Terraform code, when assuming multiple roles with MFA.

My scenario is I log in as a restricted role initially, but to carryout other tasks it may need me to assume 3 different roles using MFA. So for example logging into separate account for Transit Gateway to share resources to a new vpc etc

What is the best approach here.

Hi @fozzy77,

If possible I’d typically recommend decomposing your configurations by what credentials they need, so that you can apply each one separately with its own appropriate set of credentials and avoid the complexity of dealing with multiple authentication profiles in a single configuration.

However, if you need do to use all of these separate roles in the same Terraform configuration, in that case I think you’d be best served by defining several credential profiles in your credentials file, and then declaring multiple aliased AWS provider configurations that each use a different profile, like this:

provider "aws" {
  alias = "example1"

  profile = "example1"
  region  = "us-east-1"
}
provider "aws" {
  alias = "example2"

  profile = "example2"
  region  = "us-east-1"
}
provider "aws" {
  alias = "example3"

  profile = "example3"
  region  = "us-east-1"
}

In a situation like this when all of your provider configurations are aliased (that is, there is no default provider configuration defined) you will then need to specify for each resource which provider configuration it should belong to, like this:

resource "aws_instance" "example" {
  provider = aws.example3

  # ...
}

This compromise allows keeping the full details of how to authenticate to AWS outside of the Terraform configuration, which is a best practice because then you can potentially use the same Terraform configuration in different ways from different locations, though it does have the downside of coupling the configuration to a particular set of profile names which you must then standardize on across all systems where you’ll be applying this configuration.

Hi and thanks for this, is this the same as assuming roles, in my scenario i log on with an MFA token then assume roles between different accounts once logged in can you achieve this with terraform.

Ie login with account using a prompt for a token, then within the code the roles within each account can be assumed for ie account specific tasks

Sorry if I am Reiterating just trying to fatham it out outside of gui login process