Terraform:如何导入AWS跨账户资源?

Joh*_*ohn 9 amazon-web-services terraform terraform-provider-aws

如何将现有 AWS 资源导入 Terraform 状态(该资源存在于不同账户中)?

terraform import module.mymodule.aws_iam_policy.policy arn:aws:iam::123456789012:policy/mypolicy
Run Code Online (Sandbox Code Playgroud)

给出以下错误:

Error: Cannot import non-existent remote object

While attempting to import an existing object to aws_iam_policy.policy, the
provider detected that no object exists with the given id. Only pre-existing
objects can be imported; check that the id is correct and that it is
associated with the provider's configured region or endpoint, or use
"terraform apply" to create a new remote object for this resource.
Run Code Online (Sandbox Code Playgroud)

该资源是使用在名为 的模块中定义的不同配置程序在一个帐户中创建的mymodule

module "mymodule" {
    // ... define variables for the module
}

// within the module
provider "aws" {
  alias = "cross-account"
  region = "eu-west-2"
  assume_role {
    role_arn = var.provider_role_arn
  }
}

resource "aws_iam_policy" "policy" {
  provider = "aws.cross-account"
  name        = var.policy-name
  path        = var.policy-path
  description = var.policy-description

  policy = var.policy-document
}
Run Code Online (Sandbox Code Playgroud)

如何导入跨账户资源?

更新:使用该-provider标志,我得到一个不同的错误:

Error: Provider configuration not present

To work with module.mymodule.aws_iam_policy.policy (import
id "arn:aws:iam::123456789012:policy/somepolicytoimport") its original provider
configuration at provider.aws.cross-account is required, but it has been
removed. This occurs when a provider configuration is removed while objects
created by that provider still exist in the state. Re-add the provider
configuration to destroy
module.mymodule.aws_iam_policy.policy (import id
"arn:aws:iam::123456789012:policy/somepolicytoimport"), after which you can remove
the provider configuration again.
Run Code Online (Sandbox Code Playgroud)

Lam*_*nus 0

我认为您必须承担第二个帐户的角色,如下所示。

provider "aws" {
  assume_role {
    role_arn     = "arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME"
    session_name = "SESSION_NAME"
    external_id  = "EXTERNAL_ID"
  }
}
Run Code Online (Sandbox Code Playgroud)

[1]: https: //www.terraform.io/docs/providers/aws/index.html

  • 他们已经有了假设角色位设置。您刚刚添加了 2 个可选字段来承担您根本不需要的角色,并且仅用于标识 CloudTrail 中的会话。 (2认同)