Search code examples
amazon-web-servicesterraformterraform-provider-aws

Terraform to get AWS data from Account A and use it in Account B


I'm using two sets of terraform scripts which creates application infrastructure in AWS on Account A and codepipeline in Account B, TF scripts that creates codepipeline in Account B will need some configuration parameters(ALB, ECS..etc) from Account A which is already setup, I'm familiar on getting data if everything is hosted on the same AWS account, Is it possible to retrieve the data of one account from other using Terraform? Is there any documentation for this scenario?


Solution

  • Yes, it is possible. Since the question is rather generic I can only provide generic information.

    In general, for cross-account access, cross-account IAM roles are used. This is a good practice, not a requirement. AWS doc info about the roles:

    Based on these, in Account A you would have to setup an assumable role with a trust relationship allowing Account B to assume the role. In Account B, the IAM user that is used for terraform would need to have IAM permissions to assume the role.

    Having the role setup, in terraform you would use aws provider that would assume_role, e.g. from docs:

    provider "aws" {
    
      alias  = "assumed_role_provider"
    
      assume_role {
        role_arn     = "arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME"
        session_name = "SESSION_NAME"
        external_id  = "EXTERNAL_ID"
      }
    }
    

    Then to use the provider you would use its alias for resources or data sources, e.g. from docs:

    resource "aws_instance" "foo" {
      provider = aws.assumed_role_provider
    
      # ...
    }