I currently having a working script to build Windows servers in Azure using the for_each expression against a variable map. At the moment I’m using a variable for the keyvault secret but this is then used by all the vm’s being created. How can I pass different keyvault secrets to each VM I’m building.
Inside my module I have the following. I’m passing the value of the keyvault secret via the var.winserver.pw. I’ve created additional keyvault secrets but don’t know how I would reference these when using a variable map. Any suggestions.
resource "azurerm_windows_virtual_machine" "winservertest" {
for_each = var.vm_map
name = each.value.name
resource_group_name = var.m_resource_group_name
location = var.m_location
size = each.value.size
admin_username = var.m_admin_username
admin_password = var.winserver-test-pw
patch_mode = "Manual"
enable_automatic_updates = false
network_interface_ids = [
azurerm_network_interface.nic-multi-vms-01[each.key].id
]
2
Answers
You are already doing it with the network
vms-01[each.key]
just like that we can change your pw to a map and do the samevar.winserver-test-pw[each.key]
your variable might have to change slightly to match the same keys asvm_map
that is all …Here is an example we can test using random pet names
that output will be:
To do this, you need to write your Terraform configuration in a way that can automatically get the right secret for each VM.
To enhance the user experience of your requirement, I generated random passwords and stored them in the vault as secrets. Since secrets are sensitive information, I retrieved them from the vault using data modules and applied them to the VM configuration.
My demo terraform configuration:
Output:
Here we can see that we have two unique secret passwords available in the vault, which help in creating two VMs.
If you have your own predefined passwords stored in Azure KeyVault and to pass them to the VMs as passwords using Terraform
Remove or comment out the
random_password
andazurerm_key_vault_secret
resources for generating random passwords. Instead, use thedata "azurerm_key_vault_secret"
data source to fetch the existing secretsand update the
VM configuration module
withThe rest of the configuration will remain the same.