在子AWS账户中创建Terraform资源

时间:2020-03-16 23:01:33

标签: amazon-web-services terraform

我的目标是创建一个Terraform模块,该模块创建一个子AWS帐户,并在该帐户内创建一组资源(例如,AWS Config规则)。

使用以下aws_organizations_account定义创建帐户:

resource "aws_organizations_account" "account" {
  name  = "my_new_account"
  email = "john@doe.org"
}

示例aws_config_config_rule类似于:

resource "aws_config_config_rule" "s3_versioning" {
  name        = "my-config-rule"
  description = "Verify versioning is enabled on S3 Buckets."

  source {
    owner             = "AWS"
    source_identifier = "S3_BUCKET_VERSIONING_ENABLED"
  }

  scope {
    compliance_resource_types = ["AWS::S3::Bucket"]
  }
}

但是,这样做是在主帐户而不是新创建的子帐户中创建AWS Config规则。

如何定义适用于子帐户的配置规则?

1 个答案:

答案 0 :(得分:1)

因此,我实际上可以通过在模块中定义一个新的提供程序来实现这一点,该提供程序假定在新创建的帐户内使用OrganizationAccountAccessRole

这是一个例子:

// Define new account
resource "aws_organizations_account" "my_new_account" {
  name  = "my_new_account"
  email = "john@doe.org"
}

provider "aws" {
  /* other provider config */
  assume_role {
    // Assume the organization access role
    role_arn = "arn:aws:iam::${aws_organizations_account.my_new_account.id}:role/OrganizationAccountAccessRole"
  }
  alias = "my_new_account"
}

resource "aws_config_config_rule" "s3_versioning" {
  // Tell resource to use the new provider
  provider = aws.my_new_account

  name        = "my-config-rule"
  description = "Verify versioning is enabled on S3 Buckets."

  source {
    owner             = "AWS"
    source_identifier = "S3_BUCKET_VERSIONING_ENABLED"
  }

  scope {
    compliance_resource_types = ["AWS::S3::Bucket"]
  }
}

但是,应该注意的是,在模块内部定义提供程序会导致一些怪癖,特别是一旦您找到该模块的来源您就无法删除此模块。如果这样做,则会抛出一个Error: Provider configuration not present,因为您还将删除提供程序定义。

但是,如果您不打算删除这些帐户(或者可以在需要时手动进行此操作),那么这应该很好!