Terraform Cloud + OIDC AWS + assume role

160 views Asked by At

I have 2 AWS accounts in my organization:

  • root (main account)
  • dev (account belongs to the organization)

I'm using GitHub + Terraform Cloud (with VCS) to deploy my infrastructure.

I have all deployments done to the root AWS account through Terraform Cloud and OIDC connection which works great (so my OIDC connection is setup properly).

The problem starts when I would like to create some resources in the dev account through assume role using root account.

In my dev account I have a proper role called dev-admin:

which has trust policy like this:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::{AWS_ROOT_ACCOUNT_ID}:root"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

and permissions:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "*",
            "Resource": "*"
        }
    ]
}

My terraform code which I would like to deploy and use looks like:

terraform {
  required_version = "1.6.6"

  backend "remote" {
    hostname     = "app.terraform.io"
    organization = "my-org"

    workspaces {
      name = "some-name"
    }
  }

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.31.0"
    }
  }
}

provider "aws" {
  allowed_account_ids = ["{AWS_ROOT_ACCOUNT_ID}"]
  region              = "us-east-1"
}

provider "aws" {
  allowed_account_ids = ["{AWS_DEV_ACCOUNT_ID}"]
  region              = "eu-central-1"
  alias               = "dev"

  assume_role {
    role_arn = "arn:aws:iam::{AWS_DEV_ACCOUNT_ID}:role/dev-admin"
  }
}

data "aws_caller_identity" "dev" {
  provider = aws.dev
}

output "ops_account_id" {
  value = data.aws_caller_identity.dev.account_id
}

Whenever I publish this code to the my repo and Terraform Cloud detect changes and try execute this code then I'm geting:

Error: Cannot assume IAM Role with provider["registry.terraform.io/hashicorp/aws"].dev on main.tf line 32, in provider "aws":

IAM Role (arn:aws:iam::{AWS_DEV_ACCOUNT_ID}:role/dev-admin) cannot be assumed.

There are a number of possible causes of this - the most common are: The credentials used in order to assume the role are invalid The credentials do not have appropriate permission to assume the role The role ARN is not valid

Error: operation error STS: AssumeRole, https response error StatusCode: 403, RequestID: 12570870-2b42-45e9-a1ce-a07157dc17ca, api error AccessDenied: User: arn:aws:sts::{AWS_ROOT_ACCOUNT_ID}:assumed-role/terraform-cloud-oidc/terraform-run-ZsGi3xVXjuYKiKC4 is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::{AWS_DEV_ACCOUNT_ID}:role/dev-admin

Any ideas how it can be solved?

0

There are 0 answers