Search code examples
amazon-web-servicesterraformmulti-factor-authentication

How do I configure AWS MFA for Terraform?


I want to perform MFA for Terraform so it's expected to ask the 6-digit token from my virtual MFA device for every terraform [command]. After reading the documentation: cli-roles terraform mfa I created a role:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::[ACCOUNT_ID]:user/testuser"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "Bool": {
          "aws:MultiFactorAuthPresent": "true"
        }
      }
    }
  ]
}

This user is forced to use MFA by default and I have a configured virtual MFA device for him.

~/.aws/credentials:

[default]
...

[terraform_role]
role_arn = arn:aws:iam::[ACCOUNT_ID]:role/terraform-test-role
source_profile = default
mfa_serial = arn:aws:iam::[ACCOUNT_ID]:mfa/testuser

in my Terraform environment I placed the following:

provider "aws" {
  profile = "terraform_role"
}

But when i run terraform plan it throws me an error:

Error refreshing state: 1 error(s) occurred:

* provider.aws: No valid credential sources found for AWS Provider.
  Please see https://terraform.io/docs/providers/aws/index.html for more information on
  providing credentials for the AWS Provider

Solution

  • The solution is to specify an assume_role statement:

    provider "aws" {
      profile = "default"
      assume_role {
        role_arn = "arn:aws:iam::[ACCOUNT_ID]:role/terraform-test-role"
      }
    }