How do I configure AWS MFA for Terraform?

10,178

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"
  }
}
Share:
10,178
Alexander Nekrasov
Author by

Alexander Nekrasov

DevOps engineer at DataRobot

Updated on June 05, 2022

Comments

  • Alexander Nekrasov
    Alexander Nekrasov almost 2 years

    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