how to import multiple version of aws_secretsmanager_secret_version into terraform state?

37 Views Asked by At

I have CI CD pipeline where I was trying to import 2 versions into aws_secretsmanager_secret_version.example resource as shown below,

import {
  to = aws_secretsmanager_secret_version.example
  id = "arn:aws:secretsmanager:us-east-1:123456789012:secret:example-123456|xxxxx-xxxxxxx-xxxxxxx-xxxxx"
}

import {
  to = aws_secretsmanager_secret_version.example
  id = "arn:aws:secretsmanager:us-east-1:123456789012:secret:example-123456|yyyyy-yyyyyyy-yyyyyyy-yyyyy"
}

Error:

│ Error: Duplicate import configuration for "aws_secretsmanager_secret_version.example" │ │ on main.tf line 6: │ 6: import { │ │ An import block for the resource │ "aws_secretsmanager_secret_version.example" │ was already declared at main.tf:1,1-7. A resource can have only one import │ block.

1

There are 1 best solutions below

1
Marko E On BEST ANSWER

Two versions can be imported into two different resource. For example, the first one can be called version_x and the second one version_y:

import {
  to = aws_secretsmanager_secret_version.version_x
  id = "arn:aws:secretsmanager:us-east-1:123456789012:secret:example-123456|xxxxx-xxxxxxx-xxxxxxx-xxxxx"
}

import {
  to = aws_secretsmanager_secret_version.version_y
  id = "arn:aws:secretsmanager:us-east-1:123456789012:secret:example-123456|yyyyy-yyyyyyy-yyyyyyy-yyyyy"
}

Import block also allows using for_each, so you could try with that as well instead of having two resource blocks. An example:

locals {
  secret_versions = {
    "version_x" = "xxxxx-xxxxxxx-xxxxxxx-xxxxx"
    "version_y" = "yyyyy-yyyyyyy-yyyyyyy-yyyyy"
  }
}

import {
  for_each = local.secret_versions
  to       = aws_secretsmanager_secret_version.example[each.key]
  id       = "arn:aws:secretsmanager:us-east-1:123456789012:secret:example-123456|${each.value}"
}

resource "aws_secretsmanager_secret_version" "example" {
  for_each = local.secret_versions
  .
  .
  .
}

It should work with terraform versions >=1.7.x.