【问题标题】:Is there a way to import iam-roles in terraform?有没有办法在 terraform 中导入 iam-roles?
【发布时间】:2020-08-27 17:17:18
【问题描述】:

我想将现有的 aws 资源 iam-role 'DEVOPS' 导入我的 terraform 管理。

虽然资源存在,但我收到以下错误 -

错误:无法导入不存在的远程对象

尝试将现有对象导入到 aws_iam_role.okta_devops_role,提供者检测到不存在对象 使用给定的 id。只能导入预先存在的对象;检查 id 是正确的,并且它与提供者的配置区域相关联 或端点,或使用“terraform apply”为此创建一个新的远程对象 资源。

我在 main.tf 中创建了空资源 -> aws_iam_role.devops_role

【问题讨论】:

  • 发布您尝试运行的命令很有帮助,以便我们查看是否存在语法错误...
  • 我认为错误来自您的 tf 资源名称,该名称与您的角色名称不同。你有aws_iam_role.okta_devops_role,你应该可以按照@eatsfood 所说的进行导入。我相信它会类似于 terraform import aws_iam_role.okta_devops_role DEVOPS 假设 DEVOPS 是您要导入的角色的名称

标签: terraform terraform-provider-aws


【解决方案1】:

无法导入不是通过 terraform 配置的现有资源。

由于 terraform 确实通过 terraform 状态文件引用资源并检测配置漂移

不过,你可以尝试一下:-

https://github.com/GoogleCloudPlatform/terraformer#use-with-aws

【讨论】:

  • 这是不正确的。 Terraform 确实具有导入功能。
【解决方案2】:

您应该能够通过执行以下操作来导入现有的 IAM 角色资源:

  1. main.tf 中为资源创建存根,如下所示:
resource "aws_iam_role" "DEVOPS" {
  # stub
}
  1. 运行导入命令:
terraform import aws_iam_role.DEVOPS DEVOPS
  1. 完成后,显示资源并更新您的资源存根 在第 1 步中创建:
terraform show

这是link to the documentation

【讨论】:

    【解决方案3】:

    只是作为一种补充解决方案。如果您在模块中定义了aws_iam_role,您可能需要在terraform import 命令中添加两个前缀。从模块中找到正确资源名称的一种方法是使用terraform plan 命令。

    例如,模块内的 aws_iam_role 资源

    resource "aws_iam_role" "reports_role" {
      name = "${var.environment}_reports_role"
    
      inline_policy {
        name = "${var.environment}_s3_access_policy"
        policy = templatefile("${path.module}/templates/s3_access_policy.json", {
          bucket_name = var.bucket_name
        })
      }
    }
    

    尝试为dev 覆盖(环境)部署它时出现以下错误:

    ╷│错误:创建IAM角色时出错(prod_reports_role): EntityAlreadyExists:名称为 prod_reports_role 的角色已存在。 │ 状态码:409,请求id:********************* │ │ 与 module.aws_role.aws_iam_role.reports_role,│ on ../../modules/authorization/roles/role.tf 第 1 行,在资源中 “aws_iam_role”“reports_role”:│1:资源“aws_iam_role” "reports_role" { │ ╵

    使用terraform plan 命令后,我可以看到它的名称并导入它。如您所见,我必须在aws_iam_role.reports_role 之前添加module.aws_role

    terraform import module.aws_role.aws_iam_role.reports_role dev_reports_role
    

    【讨论】:

      猜你喜欢
      • 2020-09-22
      • 1970-01-01
      • 2022-01-25
      • 2015-08-20
      • 1970-01-01
      • 2021-11-12
      • 2016-12-09
      • 2021-12-23
      • 2022-01-15
      相关资源
      最近更新 更多