0
votes

in my Azure account a have some resources. Resource groups, app services, storage accounts... I've created these resources by using the Azure portal or Powershell. Then i've written a terraform script to add other resources and update some of the existing ones. In particular i'm interested in updating the app service. I want to add some settings and a managed identity to it. What happens is that terraform says: "look, there is already an app service with the name you specified". I tried to use "terraform import" to bind the existing app service to my terrafom state file, but doing so i loose the settings that i've put in the terraform file.

How can i solve this problem? Thank you.

1

1 Answers

1
votes

terraform import is the way to go. If you have any existing settings in your file: Just remove them until you have fully imported the app service.

Full tutorial - with a resource group instead of an app service, but the principle is the same: https://azurecitadel.com/automation/terraform/lab6/#lab-importing-resources

  • Create a resource group:
Grab the ID for the azure resource: id=$(az group show --name deleteme --query id --output tsv)

Create an empty stanza for the resource in a new import.tf file

resource "azurerm_resource_group" "deleteme" {}
  • Run the import command:
terraform import azurerm_resource_group.deleteme $id
terraform-labs$ terraform import azurerm_resource_group.deleteme $id
Acquiring state lock. This may take a few moments...
azurerm_resource_group.deleteme: Importing from ID "/subscriptions/2d31be49-d999-4415-bb65-8aec2c90ba62/resourceGroups/deleteme"...
azurerm_resource_group.deleteme: Import complete!
  Imported azurerm_resource_group (ID: /subscriptions/2d31be49-d999-4415-bb65-8aec2c90ba62/resourceGroups/deleteme)
azurerm_resource_group.deleteme: Refreshing state... (ID: /subscriptions/2d31be49-d999-4415-bb65-8aec2c90ba62/resourceGroups/deleteme)

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.
  • Run terraform plan and you should see some errors as our block is not populated
  • Run terraform state show azurerm_resource_group.deleteme
id       = /subscriptions/2d31be49-d999-4415-bb65-8aec2c90ba62/resourceGroups/deleteme
location = westeurope
name     = deleteme
tags.%   = 0
  • Add in the name argument, and the location using the loc variable
  • Rerun terraform plan and it should show no errors and no planned changes
  • The resource is now fully imported and safely under the control of Terraform.