Creating dynamic block in azurerm_api_management_api terraform - terraform

I am trying to create APIs with certain inputs dynamically into an APIM instance in azure. For that I have created a resource azurerm_api_management_api, to which I am going to pass the values like name, version, display name dynamically from a local.tf file. But when I tried, the error was
Error: Unsupported block type
│
│ on api-management\api_management_api.tf line 6, in resource "azurerm_api_management_api" "apim_api":
│ 6: dynamic apiValues{
│
│ Blocks of type "apiValues" are not expected here.
Here is the resource block.
resource "azurerm_api_management_api" "apim_api" {
revision = "1"
resource_group_name = var.resource_group_name
api_management_name = azurerm_api_management.apim.name
dynamic apiValues{
for_each = local.apiDetails
content{
name = apiValues.value.name
display_name = apiValues.value.display_name
path = ""
protocols = ["http","https"]
service_url = "http://spring-boot-redis.azurewebsites.net"
import {
content_format = "openapi-link"
content_value = "./SpringBootRedis.yaml"
}
}
}
}
locals.tf
locals {
apiDetails = [
{
name = "spring-boot-redis"
display_name = "Spring Boot Redis"
}
]
}
Is there any other way to achieve this? As I am planning to put this on an azure pipeline. So that I have to only take care of the API specification and names.

I am unsure why you are attempting to use a dynamic block for a block that does not exist according to the documentation. The error message agrees the block does not exist in the resource schema.
It appears what you are trying to achieve here is multiple resources with a value from a local.apiDetails:
resource "azurerm_api_management_api" "apim_api" {
for_each = local.apiDetails
revision = "1"
resource_group_name = var.resource_group_name
api_management_name = azurerm_api_management.apim.name
name = each.value.name
display_name = each.value.display_name
path = ""
protocols = ["http","https"]
service_url = "http://spring-boot-redis.azurewebsites.net"
import {
content_format = "openapi-link"
content_value = "./SpringBootRedis.yaml"
}
}
The documentation has more information.

Related

Why isn't terraform interpolation working?

So my goal is to have write a terraform code to deploy 3 resource groups in AZ dev, uat and prod with each having the following resources.
SQL Database
Key Vault
variable.tf
variable "resource_group_name" {
description = "deafault resource group"
type = list (string)
default = ["Test-dev","Test-uat","Test-prod"]
}
variable "storage_account_name" {
description = "name for storage account"
default = "test-storageact"
}
main.tf
resource "azurerm_resource_group" "resgrp" {
for_each = toset(var.resource_group_name)
name = "${var.resource_group_name}-rg-${each.value}"
location = var.location
tags = {
"Environment" = "${var.env}-${each.value}"
}
}
resource "azurerm_storage_account" "storageact" {
for_each = toset(var.resource_group_name)
name = "${var.storage_account_name}-${each.value}"
resource_group_name = azurerm_resource_group.resgrp["${each.value}"].location
location = azurerm_resource_group.resgrp["${each.value}"].name
account_tier = "Standard"
account_replication_type = "LRS"
tags = {
"Environment" = "${var.env}-${each.value}"
}
}
error message
│ Error: Invalid template interpolation value
│
│ on main.tf line 3, in resource "azurerm_resource_group" "resgrp":
│ 3: name = "${var.resource_group_name}-rg-${each.value}"
│ ├────────────────
│ │ var.resource_group_name is list of string with 3 elements
│
│ on main.tf line 6, in resource "azurerm_resource_group" "resgrp":
│ 6: "Environment" = "${var.env}-${each.value}"
│ ├────────────────
│ │ var.env is map of string with 3 elements
│
│ Cannot include the given value in a string template: string required.
╵
Operation failed: failed running terraform plan (exit 1)
please any help will be greatly appreciated.
i tried using type = map(string) in the variable but still gave me an error.
There are a few problems with the code.
var.resource_group_name is a list containing 3 string elements (by default), and thus the error: var.resource_group_name is list of string with 3 elements explains the problem, and is illustrated below.
The var.env is a map consisting of 3 elements and also being used as a string and fails for the same reason.
resource "azurerm_resource_group" "resgrp" {
for_each = toset(var.resource_group_name)
# var.resource_group_name is actually a list, but it's being
# used as a string here, which will fail.
name = "${var.resource_group_name}-rg-${each.value}"
location = var.location
tags = {
"Environment" = "${var.env}-${each.value}"
}
}
You probably instead want:
resource "azurerm_resource_group" "resgrp" {
for_each = toset(var.resource_group_name)
name = "${each.value}-rg"
location = var.location
tags = {
"Environment" = "${each.value}"
}
}
Additionally, as an alternative to the approach of putting multiple environments in a single resource construct, consider using modules to create reusable infrastructure for your resources and then calling each module for the environment that you're using, this is a best practice when implementing duplicate or near-duplicate infrastructure across multiple environments and allows you some flexibility with naming conventions and other parameters that would differ based upon the environment.
Rough example:
module "test-dev" {
source = "../modules/infrastructure"
environment = "Test-dev"
vm_count = 1
}
module "test-uat" {
source = "../modules/infrastructure"
environment = "Test-dev"
vm_count = 3
}
module "test-prod" {
source = "../modules/infrastructure"
environment = "Test-prod"
account_tier = "Premium"
vm_count = 6
}

Terraform - Can't access attributes on a primitive-typed value (string) when trying to add multiple disks

I'm a total newbie to Terraform and loving it so far. However, I'm a bit stuck with the below. I'm trying to add a disk to multiple machines using a dynamic block, but I'm getting the error 'Can't access attributes on a primitive-typed value (string)' whenever I run terraform plan. The config for my compute engine instance/disk looks like this:
resource "google_compute_instance" "vm_instance" {
count = 2
name = "test-instance${count.index + 1}"
machine_type = "e2-micro"
labels = {
"environment" = var.environment
}
boot_disk {
initialize_params {
image = var.image
}
}
network_interface {
# A default network is created for all GCP projects
network = "default"
}
lifecycle {
ignore_changes = [
resource_policies,
metadata,
attached_disk
]
}
}
resource "google_compute_disk" "default" {
for_each = toset(google_compute_instance.vm_instance.*.id)
name = each.value.name
type = "pd-ssd"
labels = {
environment = "dev"
}
physical_block_size_bytes = 4096
}
resource "google_compute_attached_disk" "default" {
for_each = google_compute_instance.vm_instance.*.id
disk = google_compute_disk.default[each.key].id
instance = each.key
}
It looks like the plan picks up two instances of the VM as expected, but Terraform is unable to access any of its attributes...
│ Error: Unsupported attribute
│
│ on main.tf line 50, in resource "google_compute_disk" "default":
│ 50: name = each.value.id
│ ├────────────────
│ │ each.value is "projects/blah/zones/europe-west2-a/instances/test-instance2"
Can anyone advise on where I'm going wrong, please? Thanks
If you use for_each over a set of string, you don't get access to properties, so this won't work.
resource "google_compute_disk" "default" {
for_each = toset(google_compute_instance.vm_instance.*.id)
name = each.value.name
# ...
}
If you want to use each of those id's, what you need is the set key.
resource "google_compute_disk" "default" {
for_each = toset(google_compute_instance.vm_instance.*.id)
name = each.key
# ...
}
Also, you're better off not using the Legacy Splat Expressions, and will find the code more intuitive I suspect formed something like this:
resource "google_compute_disk" "default" {
for_each = google_compute_instance.vm_instance
name = each.value.id
# ...
}

Terraform Data source is not picking subnet or resource group properly

I started writing terraform to automate the iac for provisioning VMs in Azure. However I wrote the entire code but am unable to use the existing subnet/vnet/resource group properly.
main.tf
# Configure the Microsoft Azure Provider
provider "azurerm" {
# The "feature" block is required for AzureRM provider 2.x.
# If you're using version 1.x, the "features" block is not allowed.
#version = "~>2.20.0"
features {}
subscription_id = var.subscription_id
tenant_id = var.tenant_id
client_id = var.client_id
client_secret = var.client_secret
}
#terraform {
# backend "azurerm" {
# snapshot = true
#}
#}
# Refer to resource group
data "azurerm_resource_group" "nwrk_group" {
name = var.nwrk_resource_group
}
data "azurerm_resource_group" "resource_group" {
name = var.resource_group
}
# Refer to a subnet
data "azurerm_subnet" "subnet" {
name = var.nwrk_subnet_name
virtual_network_name = var.nwrk_name
resource_group_name = data.azurerm_resource_group.nwrk_group.name
}
# Refer to Network Security Group and rule
data "azurerm_network_security_group" "nwrk_security_group" {
name = var.nwrk_security_grp
resource_group_name = data.azurerm_resource_group.nwrk_group.name
}
module "vm" {
source = "../modules/windows_vm"
node = var.node
node_username = var.node_username
node_password = var.node_password
tags = var.tags
deployment_environment = var.deployment_environment
nwrk_group_location = data.azurerm_resource_group.resource_group.location
nwrk_group_name = data.azurerm_resource_group.resource_group.name
subnet_id = data.azurerm_subnet.subnet.id
nwrk_security_group_id = data.azurerm_network_security_group.nwrk_security_group.id
resource_group_location = data.azurerm_resource_group.resource_group.location
resource_group_name = data.azurerm_resource_group.resource_group.name
}
terraform.tfvars
tags = {
project = "SEPS_Terraform"
environment = "test_tfm"
}
deployment_environment = "DEV"
node_username = "saz76test"
node_password = "SA82nd2"
nwrk_subnet_name = "SUBNET_45_0"
node = {
general_info = {
name = "gateway.test.com"
private_ip = "153.78.51.92"
vm_template = "Standard_B2s"
disk_type = "StandardSSD_LRS"
nwrk_resource_group = "SWS_LAB_36_192"
nwrk_name = "SUB_VNET_36_192"
nwrk_security_group = "N-Untrusted"
nwrk_subnet_name = "SUB_51_0"
}
os_image = {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2019-DataCenter"
version = "latest"
}
storage_disk = {
type = "StandardSSD_LRS"
size = 256
}
}
variables.tf
variable "subscription_id" {
type = string
description = "Azure subscription id to provision infra."
}
variable "tenant_id" {
type = string
description = "Azure subscription tenant id"
}
variable "client_id" {
type = string
description = "App id to authenticate to azure."
}
variable "client_secret" {
type = string
description = "App password to authenticate to azure"
}
variable "resource_group" {
type = string
description = "Resource group in which resources will be added other than network resources"
}
variable "nwrk_resource_group" {
type = string
description = "Resource group for network resources"
}
variable "nwrk_name" {
type = string
description = "VPC network name where the network resources belong to"
}
variable "nwrk_subnet_name" {
type = string
description = "Subnet of the VPC network"
}
variable "nwrk_security_grp" {
type = string
description = "Security group to which the network belong to"
}
variable "tags" {
type = map(string)
description = "Tags to attach to resources"
}
variable "deployment_environment" {
type = string
description = "Environment these VMs belong to"
}
variable "node" {
type = map(map(string))
description = "web node with specifications."
}
variable "node_username" {
type = string
description = "Login username for node"
}
variable "node_password" {
type = string
description = "Login password for node"
}
module_code:
# Create network interface
resource "azurerm_network_interface" "nic" {
name = "${var.node["general_info"]["name"]}_nic"
location = var.nwrk_group_location
resource_group_name = var.nwrk_group_name
ip_configuration {
name = "${var.node["general_info"]["name"]}_nicConfiguration"
subnet_id = var.subnet_id
private_ip_address_allocation = "Static"
private_ip_address = var.node["general_info"]["private_ip"]
}
tags = var.tags
}
# Connect the security group to the network interface
resource "azurerm_network_interface_security_group_association" "example" {
network_interface_id = azurerm_network_interface.nic.id
network_security_group_id = var.nwrk_security_group_id
}
resource "azurerm_windows_virtual_machine" "vm" {
name = var.node["general_info"]["name"]
location = var.resource_group_location
resource_group_name = var.resource_group_name
network_interface_ids = [azurerm_network_interface.nic.id]
size = var.node["general_info"]["vm_template"]
computer_name = var.node["general_info"]["name"]
admin_username = var.node_username
admin_password = var.node_password
os_disk {
name = "${var.node["general_info"]["name"]}-osDisk"
caching = "ReadWrite"
storage_account_type = var.node["general_info"]["disk_type"]
}
source_image_reference {
publisher = var.node["os_image"]["publisher"]
offer = var.node["os_image"]["offer"]
sku = var.node["os_image"]["sku"]
version = var.node["os_image"]["version"]
}
tags = var.tags
}
output "vm_id" {
value = azurerm_windows_virtual_machine.vm.id
}
output "vm_name" {
value = azurerm_windows_virtual_machine.vm.name
}
output "vm_ip_address" {
value = azurerm_network_interface.nic.private_ip_address
}
My code is above one which am trying to execute init working but plan is failing to do. Can someone please help me on this what I am missing. ?? The error is getting like it.
Error :
Warning: Value for undeclared variable
│
│ The root module does not declare a variable named "nwrk_security_group" but a value was found in file "subscription.tfvars". If you meant to use
│ this value, add a "variable" block to the configuration.
│
│ To silence these warnings, use TF_VAR_... environment variables to provide certain "global" settings to all configurations in your organization.
│ To reduce the verbosity of these warnings, use the -compact-warnings option.
╵
╷
│ Warning: Resource targeting is in effect
│
│ You are creating a plan with the -target option, which means that the result of this plan may not represent all of the changes requested by the
│ current configuration.
│
│ The -target option is not for routine use, and is provided only for exceptional situations such as recovering from errors or mistakes, or when
│ Terraform specifically suggests to use it as part of an error message.
╵
╷
│ Error: Error: Subnet "SUBNET_45_0" (Virtual Network "SUB_VNET_36_192" / Resource Group "SWS_LAB_36_192") was not found
│
│ with data.azurerm_subnet.subnet,
│ on main.tf line 31, in data "azurerm_subnet" "subnet":
│ 31: data "azurerm_subnet" "subnet" {
│
╵
╷
│ Error: Error: Network Security Group "NSG" (Resource Group "SWS_LAB_36_192") was not found
│
│ with data.azurerm_network_security_group.nwrk_security_group,
│ on main.tf line 38, in data "azurerm_network_security_group" "nwrk_security_group":
│ 38: data "azurerm_network_security_group" "nwrk_security_group" {
Subscription.tfvars
subscription_id = "fdssssssssssssss"
client_id = "sdsdsdsdsdsdsdsdsdsdsdsd"
client_secret = ".dssssssssssssssssss
tenant_id = "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf"
resource_group = "SWS_LAB_36_192"
nwrk_resource_group = "SWS_LAB_36_192"
nwrk_name = "SUB_VNET_36_192"
nwrk_security_group = "N-Untrusted"
There could potentially be many different problems because I am not sure what the outlook of the root module and child modules are, but as per the error you are getting, it seems that the value defined for the variable in the subscription.tfvars is not being declared anywhere and the one that is supposed to be declared is missing, the data source does not return anything, hence there is the error from the child module as well. Currently it is defined as:
variable "nwrk_security_grp" {
type = string
description = "Security group to which the network belong to"
}
If you take a look at the values in subscription.tfvars, there is no nwrk_security_grp, but there is a nwrk_security_group. One option to fix this would probably be to change the name of the variable in the variables.tf:
variable "nwrk_security_group" {
type = string
description = "Security group to which the network belong to"
}
In that case, you would have to adapt the data source to use the new variable name:
data "azurerm_network_security_group" "nwrk_security_group" {
name = var.nwrk_security_group
resource_group_name = data.azurerm_resource_group.nwrk_group.name
}
Alternatively (and probably easier), you can change the name of the variable you are assigning the value to in subscription.tfvars:
nwrk_security_grp = "N-Untrusted" # it was nwrk_security_group
What I would strongly suggest going forward is to keep the naming convention for the variables the same because this way you will get into a lot of issues.

Is there a way to refer to nested variable in Terraform script?

I have a terraform script, which tries to refer to the attribute in the same resource. I need to pass "azurerm_container_group.aci_caddy.fqdn" to the container instance inside the container group.
resource "azurerm_container_group" "aci_caddy" {
resource_group_name = "aci_caddy"
location = local.location
name = "aci_caddy"
os_type = "Linux"
dns_name_label = "aci-caddykang"
container {
name = "app"
image = "apptest:latest"
cpu = "0.5"
memory = "0.5"
environment_variables = {
SITE_ADDRESS = "${azurerm_container_group.aci_caddy.fqdn}"
}
}
}
but, I got the error message.
│ Error: Self-referential block
│
│ on aci-caddy-main.tf line 29, in resource "azurerm_container_group" "aci_caddy":
│ 29: SITE_ADDRESS = "${azurerm_container_group.aci_caddy.fqdn}"
│
│ Configuration for azurerm_container_group.aci_caddy may not refer to itself.
Is there a way to accomplish it? Thanks.
you should be able to export SITE_ADDRESS using your dns_name_label. So, instead of hardcoding dns_name_label. You can create a variable in Terraform
variable "dns_label" {
type = string
}
And then refer to this variable in your container group resource.
resource "azurerm_container_group" "aci_caddy" {
resource_group_name = "aci_caddy"
location = local.location
name = "aci_caddy"
os_type = "Linux"
dns_name_label = var.dns_label
container {
name = "app"
image = "apptest:latest"
cpu = "0.5"
memory = "0.5"
environment_variables = {
SITE_ADDRESS = "${var.dns_label}-westus.azurecontainer.io"
}
}
}
If you want to further improve this, you can figure out how you can get the region/location from a azurerm provider data source. I am not exposed to azure provider, so couldn't find this quickly. But I know for a fact that FQDN is derived using your dns_name_label and .azurecontainer.io.
You cant reference resource within itself: azurerm_container_group.aci_caddy.fqdn because it hasn't yet been created. You have to create new variable or local value for your SITE_ADDRESS.

Finding Ways to Merge Resource Tags

Hello Terraform Experts,
I inherited some old Terraform code for deploying resources to Azure. One of the main components that I see in most of the modules is to merge the Resource Group tags with additional tags that go on individual resources. The Resource Group tags are outputs as a map of tags. For example:
output "resource_group_tags_map" {
value = { for r in azurerm_resource_group.this : r.name => r.tags }
description = "map of rg tags."
}
and then a resource like vnets merges the RG tags with additional specific tags for the vnet given the name of the RG in a variable.
# merge Resource Group tags with Tags for VNET
# this is going to break if we change RGs
locals {
tags = merge(var.net_additional_tags, data.azurerm_resource_group.this.tags)
This works just fine if we can set the resource group in a single variable. It assumes that the resource(s) being deployed will go into one RG. However, this is not the case anymore and we somehow need to build in a way for any RG to be chosen when deploying a resource. The code below shows how the original concept works.
locals {
tags = merge(var.net_additional_tags, data.azurerm_resource_group.this.tags)
# - Virtual Network
# -
resource "azurerm_virtual_network" "this" {
for_each = var.virtual_networks
name = each.value["name"]
location = data.azurerm_resource_group.this.location
resource_group_name = var.resource_group_name
address_space = each.value["address_space"]
dns_servers = lookup(each.value, "dns_servers", null)
tags = local.tags
}
looking for help therefore to work around this. Say we create 100 vnets and each one of them goes into a different RG, we couldn't create 100 different resource group variables to capture that as it would become too cumbersome.
Here is my example with Key Vault
resource "azurerm_key_vault" "this" {
for_each = var.key_vaults
name = each.value["name"]
location = each.value["location"]
resource_group_name = each.value["resource_group_name"]
sku_name = each.value["sku_name"]
access_policy = var.access_policies
enabled_for_deployment = each.value["enabled_for_deployment"]
enabled_for_disk_encryption = each.value["enabled_for_disk_encryption"]
enabled_for_template_deployment = each.value["enabled_for_template_deployment"]
enable_rbac_authorization = each.value["enable_rbac_authorization"]
purge_protection_enabled = each.value["purge_protection_enabled"]
soft_delete_retention_days = each.value["soft_delete_retention_days"]
tags = merge(each.value["tags"], )
In the tags argument, we need to somehow merge the tags entered for this instance of Key Vault with the resource group tags that the user chose to place the key vault in. I thought of something like this, but clearly the syntax is wrong.
merge(each.value["tags"], data.azurerm_resource_group[each.key][each.value["resource_group_name"].tags)
Thanks for your input.
UPDATE:
│ Error: Invalid index
│
│ on Modules\keyvault\main.tf line 54, in resource "azurerm_key_vault" "this":
│ 54: tags = merge(each.value["tags"], data.azurerm_resource_group.this["${each.value.resource_group_name}"].tags)
│ ├────────────────
│ │ data.azurerm_resource_group.this is object with 1 attribute "keyvault1"
│ │ each.value.resource_group_name is "Terraform1"
│
│ The given key does not identify an element in this collection value.
Solution code posted below using a map and locals.
SOLUTION
Variables.tf
variable "key_vaults" {
description = "Key Vaults and their properties."
type = map(object({
name = string
location = string
resource_group_name = string
sku_name = string
tenant_id = string
enabled_for_deployment = bool
enabled_for_disk_encryption = bool
enabled_for_template_deployment = bool
enable_rbac_authorization = bool
purge_protection_enabled = bool
soft_delete_retention_days = number
tags = map(string)
}))
default = {}
}
# soft_delete_retention_days numeric value can be between 7 and 90. 90 is default
Main.tf for KeyVault module
data "azurerm_resource_group" "this" {
# read from local variable, index is resource_group_name
for_each = local.rgs_map
name = each.value.name
}
# use data azurerm_client_config to get tenant_id, not from config
data "azurerm_client_config" "current" {}
# -
# - Setup key vault
# - transform variables to locals to make sure the correct index will be used: resource group name and key vault name
locals {
rgs_map = {
for n in var.key_vaults :
n.resource_group_name => {
name = n.resource_group_name
}
}
kvs_map = {
for n in var.key_vaults :
n.name => {
name = n.name
location = n.location
resource_group_name = n.resource_group_name
sku_name = n.sku_name
tenant_id = data.azurerm_client_config.current.tenant_id # n.tenant_id
enabled_for_deployment = n.enabled_for_deployment
enabled_for_disk_encryption = n.enabled_for_disk_encryption
enabled_for_template_deployment = n.enabled_for_template_deployment
enable_rbac_authorization = n.enable_rbac_authorization
purge_protection_enabled = n.purge_protection_enabled
soft_delete_retention_days = n.soft_delete_retention_days
tags = merge(n.tags, data.azurerm_resource_group.this["${n.resource_group_name}"].tags)
}
}
}
resource "azurerm_key_vault" "this" {
for_each = local.kvs_map # use local variable, other wise keyvault1 will be used in stead of kv-eastus2-01 as index
name = each.value["name"]
location = each.value["location"]
resource_group_name = each.value["resource_group_name"]
sku_name = each.value["sku_name"]
tenant_id = each.value["tenant_id"]
enabled_for_deployment = each.value["enabled_for_deployment"]
enabled_for_disk_encryption = each.value["enabled_for_disk_encryption"]
enabled_for_template_deployment = each.value["enabled_for_template_deployment"]
enable_rbac_authorization = each.value["enable_rbac_authorization"]
purge_protection_enabled = each.value["purge_protection_enabled"]
soft_delete_retention_days = each.value["soft_delete_retention_days"]
tags = each.value["tags"]
}

Resources