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



如何将现有的AWS资源导入Terraform状态,因为该资源存在于不同的帐户中?

terraform import module.mymodule.aws_iam_policy.policy arn:aws:iam::123456789012:policy/mypolicy

给出以下错误:

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.

该资源是使用名为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
}

如何导入跨帐户资源?

更新:使用-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.

如果您有另一个帐户的凭据,则可以使用多个提供程序配置。

# This is used by default
provider "aws" {
region = "us-east-1"
access_key = "my-access-key"
secret_key = "my-secret-key"
}
provider "aws" {
alias  = "another_account"
region = "us-east-1"
access_key = "another-account-access-key"
secret_key = "another-account-secret-key"
}
# To use the other configuration
resource "aws_instance" "foo" {
provider = aws.another_account
# ...
}

文件如下:https://developer.hashicorp.com/terraform/language/providers/configuration#alias-多供应商配置

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

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

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

我在尝试导入AWS acm证书时遇到了同样的错误。

作为第一步,在导入资源之前,您需要在根模块(或其他相关模块(中创建其配置:

resource "aws_acm_certificate" "cert" {
# (resource arguments)
}

或者你会得到以下错误:

错误:资源地址"aws_acm_certificate.cert";中不存在配置。

然后您可以通过提供相关arn:来导入资源

$ terraform import aws_acm_certificate.cert <certificate-arn>

就像评论中提到的@ydaetskcoR一样,如果你使用v0.12.10+,你不需要承担第二个帐户的角色。

但是Terraform确实需要第二个帐户的访问凭据,所以请确保您提供相关帐户的凭据(而不是源帐户凭据(,否则您将像我一样在
Error: Cannot import non-existent remote object
上停留几个小时(:

相关内容

  • 没有找到相关文章

最新更新