[NoBrainer] Import existing Microsoft Entra ID security groups into terraform state

In a project I’m currently working, some Microsoft Entra ID security groups were created manually via the Azure portal. However all other application/solution related resources got created by infrastructure as code (IaC) – concretely terraform. As the security groups already contained members, I didn’t want to destroy and recreate them with terraform. For such cases terraform has an import feature which allows you to import existing resources into terraform state.

Versions
– terraform: 1.6.6
– hashicorp/azuread: 2.47.0

To do so, proceeded as follows.

Get object ID(s) and description(s) of the existing groups

To get the object ID(s) of the Microsoft Entra ID security groups to be imported into terraform state, first log in to the Azure portal.

  • Switch to the desired directory (Azure tenant)
  • Search for Microsoft Entra ID in the search bar on the top
  • Navigate to Groups in the menu on the left
  • Search the group(s) to be imported by name
  • Open group details by clicking on its name
  • Navigate to Properties in the menu on the left
  • Copy the Object Id and Group description

Add resource(s) for existing group(s) to terraform code

Next, the Microsoft Entra ID security group(s) to be imported need to be added as resources to terraform code.

resource "azuread_group" "test-group" {
  display_name            = "Test group"
  description             = "Microsoft Entra ID security group for testing purposes"
  prevent_duplicate_names = true
  security_enabled        = true
  lifecycle {
    # apart from setting initially; do not flag changes in members and owners as state change
    ignore_changes = [members, owners]
  }
}

To avoid that terraform (when applied) changes the owner and removes the existing members, lifecycle property ignore_changes is set to [members, owners].

Import existing group(s) to terraform state

Now the existing group(s) can be imported to the terraform state as follows.

  1. Open PowerShell
  2. Login to Azure by executing the following command
    az login -t [tenant id]
  3. Run terraform init
  4. Run import command (see Resource: azuread_group – Import)
    terraform import azuread_group.test-group 6387cbeb-5e2f-4e11-ab75-12536d4b96a7

That’s it. After the import command succeeded, the Microsoft Entra ID is managed by terraform.

Leave a Reply

Powered by WordPress.com.

Up ↑

Discover more from blog.rufer.be

Subscribe now to keep reading and get access to the full archive.

Continue reading