Aws provider can't assume role but AWS CLI can

aws provider can’t assume role but AWS CLI can

I want to manage my AWS Organization with Terraform CLI and then create some
resources in sub-accounts of my org.

I signed in to AWS with my root credentials and created an IAM user with the
AdministratorAccess policy, then I created access keys for this IAM user and put
them as the default and only profile in my ~/.aws/credentials. These are the
only credentials available on the system and Terraform is using them.

I then have this terraform code to set up my organization and sub-accounts and
then assume the role to create stuff in the sub-account:

terraform {
  required_version = ">= 0.15"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "3.40.0"
    }
  }
}
provider "aws" {
  region  = var.region
  profile = "default"
  alias   = "root"
  default_tags { [...] }
}
resource "aws_organizations_organization" "organization" {
  feature_set = "ALL"
  provider    = aws.root
}
resource "aws_organizations_account" "devel" {
  name      = "acme-devel"
  email     = "aws_devel@acme.org"
  role_name = "Admin"
  provider  = aws.root
}
provider "aws" {
  profile = var.credentials_profile_root
  assume_role {
    role_arn     = "arn:aws:iam::${aws_organizations_account.devel.id}:role/Admin"
    session_name = "Terraform_devel"
  }
  alias  = "devel"
  region = var.region
  default_tags { [...] }
}
resource "aws_s3_bucket" "acme_test001" {
  bucket        = "acme-whatever-test001"
  acl           = "private"
  provider = aws.devel
}

I am always getting this error:
Error: error configuring Terraform AWS Provider: IAM Role (arn:aws:iam::XXXXXXX:role/Admin) cannot be assumed.

But if cut’n’paste the ARN to the CLI it works:

aws sts assume-role --role-session-name CLI_Tests --role-arn arn:aws:iam::XXXX:role/Admin

I cannot understand what is terraform doing different than the cli and why it is failing.

I’m using Terraform v0.15.4 with AWS provider v3.40.0 on macOS 10.14 and aws-cli/2.2.4.

Any help would be appreciated.

Answering my own question, it was a silly problem that I failed to see :slight_smile:

When creating a new aws_organizations_account it will start out with only the default regions enabled and I was trying to use var.region = "eu-south-1" which isn’t one of them.

After logging in the AWS Console and enabling the region my code started to work correctly.

I’m now looking into how to enable my non-default region with terraform.