Deploying to multiple AWS accounts with Terraform?

前端 未结 2 1587
遥遥无期
遥遥无期 2020-11-28 12:52

I\'ve been looking for a way to be able to deploy to multiple AWS accounts simultaneously in Terraform and coming up dry. AWS has the concept of doing this with Stacks but I

2条回答
  •  隐瞒了意图╮
    2020-11-28 13:22

    You can define multiple provider aliases which can be used to run actions in different regions or even different AWS accounts.

    So to perform some actions in your default region (or be prompted for it if not defined in environment variables/~/.aws/configure/etc) and also in US East 1 you'd have something like this:

    provider "aws" {
      # ...
    }
    
    # Cloudfront ACM certs must exist in US-East-1
    provider "aws" {
      alias  = "cloudfront-acm-certs"
      region = "us-east-1"
    }
    

    You'd then refer to them like so:

    data "aws_acm_certificate" "ssl_certificate" {
      provider    = "aws.cloudfront-acm-certs"
      ...
    }
    
    resource "aws_cloudfront_distribution" "cloudfront" {
      ...
      viewer_certificate {
        acm_certificate_arn = "${data.aws_acm_certificate.ssl_certificate.arn}"
        ...
      }
    }
    

    So if you want to do things across multiple accounts at the same time then you could assume a role in the other account with something like this:

    provider "aws" {
      # ...
    }
    
    # Assume a role in the DNS account so we can add records in the zone that lives there
    provider "aws" {
      alias   = "dns"
      assume_role {
        role_arn     = "arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME"
        session_name = "SESSION_NAME"
        external_id  = "EXTERNAL_ID"
      }
    }
    

    And refer to it like so:

    data "aws_route53_zone" "selected" {
      provider     = "aws.dns"
      name         = "test.com."
    }
    
    resource "aws_route53_record" "www" {
      provider = "aws.dns"
      zone_id  = "${data.aws_route53_zone.selected.zone_id}"
      name     = "www.${data.aws_route53_zone.selected.name}"
      ...
    }
    

    Alternatively you can provide credentials for different AWS accounts in a number of other ways such as hardcoding them in the provider or using different Terraform variables, AWS SDK specific environment variables or by using a configured profile.

提交回复
热议问题