Check the following:
Code:
resource "azurerm_api_management_subscription" "example" {
api_management_name = data.azurerm_api_management.example.name
resource_group_name = data.azurerm_api_management.example.resource_group_name
user_id = data.azurerm_api_management_user.example.id
product_id = data.azurerm_api_management_product.example.id
display_name = "Parser API"
state = "active"
primary_key = var.subscription_key
depends_on = [
azurerm_api_management_user.xxx,
]
}
Here while creating the variable subscription_key , mark it sensitive
so that it is protected as such and not exposed anywhere.
variable "subscription_key" {
type = string
default = "3xxxxxxxxf"
sensitive = true
}
and this value even can be stored in keyvault
to reference as it is secure way and use life cycle to prevent destroy, as everytime when terraform is applied , the key won’t be destroyed and regenerated
lifecycle {
prevent_destroy = true
}
Note: But this applies to whole resource
so specify primary_key within the ignore_changes list, which ignore changes only to the primary key and will not try to destroy during changes to configuration.
Code:
resource "azurerm_key_vault" "org" {
name = "kkkkexamplekeyvault"
location = data.azurerm_resource_group.example.location
resource_group_name = data.azurerm_resource_group.example.name
tenant_id = data.azurerm_client_config.current.tenant_id
sku_name = "premium"
soft_delete_retention_days = 7
access_policy {
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = data.azurerm_client_config.current.object_id
key_permissions = [
"Get",
"Create",
"Delete",
"List",
"Recover",
"Restore",
"UnwrapKey",
"WrapKey",
"List"
]
secret_permissions = [
"Get",
"List",
"Set",
"Delete",
"Recover",
"Restore",
]
}
}
resource "azurerm_key_vault_secret" "org" {
name = "subsckey"
value = "xxxx"
key_vault_id = azurerm_key_vault.org.id
}
resource "azurerm_api_management_subscription" "example" {
api_management_name = azurerm_api_management.example.name
resource_group_name = data.azurerm_resource_group.example.name
display_name = "exampleapi"
state = "active"
// primary_key = var.subscription_key
primary_key= azurerm_key_vault_secret.org.value
lifecycle {
// prevent_destroy = true
ignore_changes = [
primary_key
]
}
depends_on = [
azurerm_api_management_user.zxc,
]
}
Reference : How to ignore change of an attribute in block -StackOverflow