Importing an Existing AWS Organization's Root OU into Terraform

Photo by Matt Ridley on Unsplash

Importing an Existing AWS Organization's Root OU into Terraform

·

2 min read

Importing an Existing AWS Organization's Root OU into Terraform

There are often times when we already have an AWS Organization that was either created manually, by CloudFormation, or by any other means and we need to manage these existing resources using Terraform. In such a scenario, the Terraform import command comes in really handy.

I was recently working on importing an AWS Organizations structure into Terraform and this was the first resource (The existing AWS Organization) that I defined in my organizations.tf file:

resource "aws_organizations_organization" "org" {

    feature_set = "ALL"

}

After doing a terraform init, I imported the above resource to the Terraform state by running the following command:

terraform import aws_organizations_organization.org o-a1b2c3d4e5

# where `o-a1b2c3d4e5` would be the name of the AWS Organization that I wanted to import.

The import was successful. Next, I thought about importing the root OU into the state by adding an aws_organizations_organizational_unit resource to my organization.tf config file and then doing an import on the OU. However, it turns out that you cannot import the root OU this way.

You need to import the Organization Management account in Terraform which contains the root OU as an attribute. This would be the aws_organizations_account resource which I hadn't created in the first place. Therefore, I went back to my organizations.tf file and added the following resource:

resource "aws_organizations_account" "management" {

    name = "FRIENDLY_ACCOUNT_NAME"
    email = "EMAIL_ASSOCIATED_WITH_THE_ORG_MANAGEMENT_ACCOUNT"
    parent_id = "r-abcd" 

}
# Where r-abcd is the root OU's ID assigned to the parent_id attribute

Next, I ran the terraform import command:

terraform import aws_organizations_account.management 123456789012

# Where 123456789012 is the Organization Management Account's ID

And voila! The import was successful. The terraform state command now showed the root OU ID as an account attribute:

terraform state show aws_organizations_account.management
# aws_organizations_account.management:
resource "aws_organizations_account" "management" {
    arn              = "arn:aws:organizations::123456789012:account/o-a1b2c3d4e5/123456789012"
    email            = "EMAIL_ASSOCIATED_WITH_THE_ORG_MANAGEMENT_ACCOUNT"
    id               = "123456789012"
    joined_method    = "INVITED"
    joined_timestamp = "2022-01-15T04:38:03Z"
    name             = "FRIENDLY_ACCOUNT_NAME"
    parent_id        = "r-abcd"
    status           = "ACTIVE"
    tags             = {}
    tags_all         = {}
}

Now I could go ahead and start adding and importing all the remaining Organization resources to Terraform!