I’m trying to import multiple AWS IAM policies and IAM roles to my tfstate files using a shell script to automate the import mechanism. It works fine when I tries to import the IAM roles, but when I tries to import an IAM policy it seems that the imported state overwrite the previous import results and I always comes to:
Error: Invalid index
│
│ on /project/iam_role.tf line 14, in resource "aws_iam_role" "roles":
│ 14: aws_iam_policy.policies["S3FullWithoutDelete"].arn,
│ ├────────────────
│ │ aws_iam_policy.policies is object with 1 attribute "IAMEnableMFA"
│
│ The given key does not identify an element in this collection value.
# There are other similar errors after the import, omitted for brevity
Here is an example of the command that I’m trying to run.
terraform import 'aws_iam_policy.policies["IAMEnableMFA"]' arn:aws:iam::XXXXXXXXXXXX:policy/IAMEnableMFA
Here is the iam_policy.tf file configuration.
resource "aws_iam_policy" "policies" {
for_each = {
"Billing-Organizations" = "billing_organizations.json"
"BillReadOnly" = "bill_readonly.json"
"AccountAndTaxsettings" = "account_and_tax.json"
"S3FullWithoutDelete" = "s3_full_without_delete.json"
"ConsolidatedBillingForMOCB" = "consolidated_billing_for_mocb.json"
"Organizations" = "organizations.json"
"CostExplorerAPI" = "cost_explorer_api.json"
"Invite_Account_To_Organization" = "invite_account_to_organization.json"
"IAMEnableMFA" = "iam_enabled_mfa.json"
"OrganizationsReadOnly" = "organizations_read_only.json"
"Modify_EC2_RI" = "modify_ec2_ri.json"
"billing-upload-s3-cur" = "billing_upload_s3_cur.json"
}
name = each.key
policy = file("${path.module}/policy/${each.value}")
tags = var.resource_tags
}
And this is the iam_role.tf file configuration.
resource "aws_iam_role" "roles" {
for_each = {
"ADFS-Billing" = {
"file" = "adfs_billing.json"
"policy_arns" = [
aws_iam_policy.policies["Billing-Organizations"].arn,
aws_iam_policy.policies["Modify_EC2_RI"].arn,
data.aws_iam_policy.policies["IAMFullAccess"].arn,
data.aws_iam_policy.policies["Billing"].arn,
data.aws_iam_policy.policies["ReadOnlyAccess"].arn,
data.aws_iam_policy.policies["AWSSupportAccess"].arn,
data.aws_iam_policy.policies["AWSCloudTrail_FullAccess"].arn,
data.aws_iam_policy.policies["AWSBillingConductorFullAccess"].arn,
aws_iam_policy.policies["S3FullWithoutDelete"].arn,
aws_iam_policy.policies["AccountAndTaxsettings"].arn
]
}
# There are other similar items, but omitted for brevity
}
name = each.key
assume_role_policy = file("${path.module}/trust_relationships/${each.value["file"]}")
managed_policy_arns = each.value["policy_arns"]
tags = var.resource_tags
}
How can I import all of these policies to my tfstate file properly?