Azure Automation Account: Setup Update management for Azure VMs - azure

I have created a Windows VM in Azure and configured the diagnostics settings pointing to a log analytics workspace.
Below is the VM module
resource "azurerm_windows_virtual_machine" "Lz_VM" {
name = "vm-${var.subscription_type}-${var.vm_type}-${var.instance_number}"
resource_group_name = var.resource_group_name
location = var.location
# size = "Standard_F2"
size = "Standard_B2S"
admin_username = var.username
admin_password = var.password
provision_vm_agent = true
allow_extension_operations = true
network_interface_ids = [azurerm_network_interface.vm-nic.id]
encryption_at_host_enabled = var.enabled_for_disk_encryption == true ? false : var.encryption_at_host_enabled
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
# disk_encryption_set_id = var.disk_encryption_key_set_id
}
source_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2016-Datacenter"
version = "latest"
}
identity {
type = "SystemAssigned"
}
tags = var.tags
}
# This extension is needed for other extensions
resource "azurerm_virtual_machine_extension" "daa-agent" {
name = "DependencyAgentWindows"
virtual_machine_id = azurerm_windows_virtual_machine.Lz_VM.id
publisher = "Microsoft.Azure.Monitoring.DependencyAgent"
type = "DependencyAgentWindows"
type_handler_version = "9.10"
automatic_upgrade_enabled = true
auto_upgrade_minor_version = true
}
# Add logging and monitoring extensions
resource "azurerm_virtual_machine_extension" "monitor-agent" {
depends_on = [ azurerm_virtual_machine_extension.daa-agent ]
name = "AzureMonitorWindowsAgent"
virtual_machine_id = azurerm_windows_virtual_machine.Lz_VM.id
publisher = "Microsoft.Azure.Monitor"
type = "AzureMonitorWindowsAgent"
type_handler_version = "1.5"
automatic_upgrade_enabled = true
auto_upgrade_minor_version = true
}
resource "azurerm_virtual_machine_extension" "omsagentwin" {
name = "OmsAgentForWindows"
virtual_machine_id = azurerm_windows_virtual_machine.Lz_VM.id
publisher = "Microsoft.EnterpriseCloud.Monitoring"
type = "MicrosoftMonitoringAgent"
type_handler_version = "1.0"
auto_upgrade_minor_version = true
settings = <<SETTINGS
{
"workspaceId": "${var.log_analytics_workspaceid}",
"azureResourceId": "${azurerm_windows_virtual_machine.Lz_VM.id}",
"stopOnMultipleConnections": "false"
}
SETTINGS
protected_settings = <<PROTECTED_SETTINGS
{
"workspaceKey": "${var.log_analytics_workspace_key}"
}
PROTECTED_SETTINGS
}
resource "azurerm_virtual_machine_extension" "gc" {
name = "AzurePolicyforWindows"
virtual_machine_id = azurerm_windows_virtual_machine.Lz_VM.id
publisher = "Microsoft.GuestConfiguration"
type = "ConfigurationforWindows"
type_handler_version = "1.0"
auto_upgrade_minor_version = true
}
resource "azurerm_virtual_machine_extension" "disk-encryption" {
count = var.enabled_for_disk_encryption == true ? 1 : 0
name = "de-vm-${var.subscription_type}-${var.vm_type}-${var.instance_number}"
virtual_machine_id = azurerm_windows_virtual_machine.Lz_VM.id
publisher = "Microsoft.Azure.Security"
type = "AzureDiskEncryption"
type_handler_version = 2.2
auto_upgrade_minor_version = true
settings = <<SETTINGS
{
"EncryptionOperation": "EnableEncryption",
"KeyVaultURL": "${var.keyvaultURL}",
"KeyVaultResourceId": "${var.keyvaultResourceId}",
"KeyEncryptionKeyURL": "${format("%skeys/des-key/%s", var.keyvaultURL,var.disk_encryption_key_version)}",
"KekVaultResourceId": "${var.keyvaultResourceId}",
"KeyEncryptionAlgorithm": "RSA-OAEP",
"VolumeType": "All"
}
SETTINGS
}
module "vm_diagnostic_settings" {
source = "../diagnostic_settings"
diagnostics_settings_name = "vm-${var.subscription_type}-${var.vm_type}-diagnostics"
resource_id = resource.azurerm_windows_virtual_machine.Lz_VM.id
law_id = var.log_analytics_workspace_id
logs_to_exclude = []
metrics_to_exclude = []
retention_days = "7"
}
Log Analytics workspace has the following solution
resource "azurerm_log_analytics_solution" "update_solution" {
solution_name = "Updates"
resource_group_name = module.create_rg.rg_name
location = var.location
workspace_resource_id = module.log_analytics_workspace.id
workspace_name = module.log_analytics_workspace.workspace_name
plan {
publisher = "Microsoft"
product = "OMSGallery/Updates"
}
}
and below is the Automation account code
resource "azurerm_automation_account" "automation_account" {
name = "${var.name}-${var.instance_number}"
location = var.location
resource_group_name = var.rg_name
sku_name = var.sku
# tags = var.tags //Facing the issue : Too many tags
}
resource "azurerm_log_analytics_linked_service" "link_automation_account_with_log_analytics" {
count = var.link_log_analytics == true ? 1 : 0
resource_group_name = var.rg_name
workspace_id = var.log_analytics_id
read_access_id = azurerm_automation_account.automation_account.id
depends_on = [azurerm_automation_account.automation_account]
}
#Creates the schedule for updates
resource "azurerm_automation_schedule" "weekly-updates" {
name = "Weekly-Sunday-6am"
resource_group_name = var.rg_name
automation_account_name = azurerm_automation_account.automation_account.name
frequency = "Week"
interval = 1
timezone = "America/Chicago"
start_time = "2023-01-15T18:00:15+02:00"
description = "Standard schedule for updates"
week_days = ["Sunday"]
depends_on = [azurerm_automation_account.automation_account]
}
Looks like the Automation Schedule don't have any runbooks associated.
Is that all I need to enable the Update management for Azure VMs in Automation Account? As per this article - https://claranet.medium.com/azure-update-management-solutions-overview-d167e17289df, I need something like azurerm_template_deployment which I don't understand.

I tried to reproduce the same as per your requirement and was able to achieve the desired results as follows:
Use the provided resource to link a runbook to a schedule:
"azurerm_automation_job_schedule"
I made a few changes and attached the script below:
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "3.39.1"
}
}
}
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "example" {
name = "xxxresourcegroup"
location = "<location>"
}
resource "azurerm_virtual_network" "example" {
name = "xxxxxxnetwork"
address_space = ["10.0.0.0/16"]
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
}
resource "azurerm_subnet" "example" {
name = "xxxxx"
resource_group_name = azurerm_resource_group.example.name
virtual_network_name = azurerm_virtual_network.example.name
address_prefixes = ["10.0.2.0/24"]
}
resource "azurerm_network_interface" "example" {
name = "xxxxxnic"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
ip_configuration {
name = "xxxxxsubnetname"
subnet_id = azurerm_subnet.example.id
private_ip_address_allocation = "Dynamic"
}
}
resource "azurerm_windows_virtual_machine" "example" {
name = "xxxxxexample"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
size = "Standard_F2"
admin_username = "<user>"
admin_password = "<password>"
network_interface_ids = [
azurerm_network_interface.example.id,
]
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
}
source_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2019-Datacenter"
version = "latest"
}
}
resource "azurerm_virtual_machine_extension" "daa-agent" {
name = "DependencyAgentWindows"
virtual_machine_id = azurerm_windows_virtual_machine.example.id
publisher = "Microsoft.Azure.Monitoring.DependencyAgent"
type = "DependencyAgentWindows"
type_handler_version = "9.10"
automatic_upgrade_enabled = true
auto_upgrade_minor_version = true
}
resource "azurerm_virtual_machine_extension" "monitor-agent" {
depends_on = [ azurerm_virtual_machine_extension.daa-agent ]
name = "AzureMonitorWindowsAgent"
virtual_machine_id = azurerm_windows_virtual_machine.example.id
publisher = "Microsoft.Azure.Monitor"
type = "AzureMonitorWindowsAgent"
type_handler_version = "1.5"
automatic_upgrade_enabled = true
auto_upgrade_minor_version = true
}
resource "azurerm_automation_account" "example" {
name = "xxxxxautomation"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
sku_name = "Basic"
tags = {
environment = "development"
}
}
resource "azurerm_automation_runbook" "example" {
name = "xxxxx"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
automation_account_name = azurerm_automation_account.example.name
description = "Run runbook"
runbook_type = "<runbooktype>"
publish_content_link {
uri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/c4935ffb69246a6058eb24f54640f53f69d3ac9f/101-automation-runbook-getvms/Runbooks/Get-AzureVMTutorial.ps1" //As per MsDoc example
}
}
resource "azurerm_log_analytics_workspace" "example" {
name = "xxxxxx"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
sku = sku
retention_in_days = 30 //userdefined
}
resource "azurerm_log_analytics_solution" "example" {
solution_name = "xxxxx"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
workspace_resource_id = azurerm_log_analytics_workspace.example.id
workspace_name = azurerm_log_analytics_workspace.example.name
plan {
publisher = "Microsoft"
product = "OMSGallery/xxxxxsolution"
}
}
resource "azurerm_log_analytics_linked_service" "example" {
resource_group_name = azurerm_resource_group.example.name
workspace_id = azurerm_log_analytics_workspace.example.id
read_access_id = azurerm_automation_account.example.id
depends_on = [azurerm_automation_account.example]
}
resource "azurerm_automation_job_schedule" "example" {
resource_group_name = azurerm_resource_group.example.name
automation_account_name = azurerm_automation_account.example.name
runbook_name = azurerm_automation_runbook.example.name
schedule_name = azurerm_automation_schedule.example.name
depends_on = [azurerm_automation_runbook.example,azurerm_automation_schedule.example]
}
resource "azurerm_automation_schedule" "example" {
name = "xxxxxx-automation-schedule"
resource_group_name = azurerm_resource_group.example.name
automation_account_name = azurerm_automation_account.example.name
frequency = "Week" // as per requirement
interval = 1
timezone = "UTC" //default timeZone
week_days = ["Saturday"]
description = "Perform each Saturday in UTC."
depends_on = [
azurerm_automation_account.example,
azurerm_automation_runbook.example
]
}
terraform init:
terraform plan:
terraform apply:
Linked runbook to a schedule successfully after deployment:
Update management updated with the defined log analytics workspace:
Refer for more information: terraform registry examples

Related

Azure VM: AzureADJoined is "No" even after enabling the AADLoginForWindows extension

I have created a VM in Azure as mentioned below
resource "azurerm_windows_virtual_machine" "virtual_machine_hub" {
name = "vm-hub"
resource_group_name = azurerm_resource_group.ipz12-dat-np-connection-rg.name
location = azurerm_resource_group.ipz12-dat-np-connection-rg.location
size = "Standard_B8ms"
admin_username = "xxxxx"
admin_password = "xxxxx"
network_interface_ids = [
azurerm_network_interface.virtual_machine_hub_nic.id
]
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
}
source_image_reference {
publisher = "MicrosoftWindowsDesktop"
offer = "Windows-10"
sku = "21h1-pro"
version = "latest"
}
depends_on = [
azurerm_network_interface.virtual_machine_hub_nic
]
}
and enabled the AADLoginForWindows extension
resource "azurerm_virtual_machine_extension" "virtual_machine_hub_ext" {
name = "AADLoginForWindows"
virtual_machine_id = azurerm_windows_virtual_machine.virtual_machine_hub.id
type = "AADLoginForWindows"
type_handler_version = "1.0"
auto_upgrade_minor_version = true
publisher = "Microsoft.Azure.ActiveDirectory"
depends_on = [
azurerm_windows_virtual_machine.virtual_machine_hub
] }
however "dsregcmd /status" command shows that it is not connected with Azure AD domain like AzureADJoined is "No"
In order to register the VM in Azure AD, I don't feel that I have the appropriate permissions. If that's the case, what level of permission is required? and what am I missing?
Note: I have manually joined Azure AD like mentioned below
As discussed here, it is described that aadj private extension also to be created for a virtual machine under path:
HKLM\SOFTWARE\Microsoft\RDInfraAgent\AADJPrivate
So, another Custom script extension was added to add the key AADJPRIVATE for the VM.
Followed this template given by #Ansuman Bal in SO thread for Azure AD VM join and made a few changes to achieve the expected results as per your requirements.
vi main.tf:
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "3.37.0"
}
}
}
provider "azurerm" {
features {}
}
provider "azuread" {}
data "azuread_group" "aad_group" {
display_name = "<ADGroup>"
security_enabled = true
}
data "azurerm_role_definition" "vm_user_login" {
name = "<VM User Login>"
}
resource "azurerm_role_assignment" "vm_user_role" {
scope = azurerm_resource_group.rg-xxx.id
role_definition_id = data.azurerm_role_definition.vm_user_login.id
principal_id = data.azuread_group.aad_group.id
}
data "azurerm_role_definition" "desktop_user" {
name = "xxxxxx User"
}
resource "azurerm_role_assignment" "desktop_role" {
scope = azurerm_virtual_desktop_application_group.desktopapp.id
role_definition_id = data.azurerm_role_definition.desktop_user.id
principal_id = data.azuread_group.aad_group.id
}
resource "azurerm_resource_group" "eg-RG" {
name = "xxxxxtest"
location = "West Europe"
}
resource "azurerm_virtual_network" "vnet" {
name = "xxxx-vnet"
location = azurerm_resource_group.eg-RG.location
resource_group_name = azurerm_resource_group.eg-RG.name
address_space = ["10.0.0.0/16"]
}
resource "azurerm_subnet" "xxxxdefaultSubnet" {
name = "xxxxxsubnet"
resource_group_name = azurerm_resource_group.eg-RG.name
virtual_network_name = azurerm_virtual_network.vnet.name
address_prefixes = ["10.0.0.0/24"]
}
resource "azurerm_network_security_group" "nsg" {
name = "xxxx-nsg"
location = azurerm_resource_group.eg-RG.location
resource_group_name = azurerm_resource_group.eg-RG.name
security_rule {
name = "allow-rdp"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = 3389
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
resource "azurerm_subnet_network_security_group_association" "nsg_association" {
subnet_id = azurerm_subnet.xxxxdefaultSubnet.id
network_security_group_ID = azurerm_network_security_group.<nsg>.id
}
resource "time_rotating" Gen_token" {
rotation_days = 30
}
resource "azurerm_virtual_desktop_host_pool" "new-hp" {
location = azurerm_resource_group.eg-RG.location
resource_group_name = azurerm_resource_group.eg-RG.name
name = "xxxxxhostpool"
friendly_name = "samplepool"
validate_environment = true
start_vm_on_connect = true
custom_rdp_properties = "audiocapturemode:i:1;audiomode:i:0;targetisaadjoined:i:1;"
description = "host-poool demo"
type = "Pooled"
maximum_sessions_allowed = 10
load_balancer_type = "DepthFirst"
}
resource "azurerm_virtual_desktop_host_pool_registration_info" "reginfo" {
hostpool_id = azurerm_virtual_desktop_host_pool.new-hp.id
expiration_date = time_rotating.avd_token.rotation_rfc3339
}
resource "azurerm_virtual_desktop_application_group" "desktopapp" {
name = "xxxx-Desktop"
location = azurerm_resource_group.eg-RG.location
resource_group_name = azurerm_resource_group.eg-RG.name
type = "Desktop"
host_pool_id = azurerm_virtual_desktop_host_pool.new-hp.id
friendly_name = "xxxxx"
description = "xxxxapplications"
}
resource "azurerm_virtual_desktop_workspace" "workspace" {
name = "xxxxxx-WORKSPACE"
location = azurerm_resource_group.eg-RG.location
resource_group_name = azurerm_resource_group.eg-RG.name
friendly_name = "xxxxxxx"
description = "Purporse"
}
resource "azurerm_virtual_desktop_workspace_application_group_association" "sampleworkspaceremoteapp" {
workspace_id = azurerm_virtual_desktop_workspace.workspace.id
application_group_id = azurerm_virtual_desktop_application_group.desktopapp.id
}
resource "azurerm_network_interface" "xxxx_nic" {
count=2
name = "xxxx-${count.index}"
location = azurerm_resource_group.eg-RG.location
resource_group_name = azurerm_resource_group.eg-RG.name
ip_configuration {
name = "internal"
subnet_id = azurerm_subnet.xxxxxdefaultSubnet.id
private_ip_address_allocation = "Dynamic"
}
}
resource "azurerm_windows_virtual_machine" "sessionhost" {
depends_on = [
azurerm_network_interface.sessionhost_nic
]
count=2
name = "xxxvm-${count.index}"
resource_group_name = azurerm_resource_group.eg-RG.name
location = azurerm_resource_group.eg-RG.location
size = "Standard_B2MS"
admin_username = "useradmin"
admin_password = "<Password>"
provision_vm_agent = true
network_interface_ids = [azurerm_network_interface.sessionhost_nic.*.id[count.index]]
identity {
type = "SystemAssigned"
}
os_disk {
caching = "ReadWrite"
storage_account_type = "Premium_LRS"
}
source_image_reference {
publisher = "MicrosoftWindowsDesktop"
offer = "Windows-10"
sku = "20h2-evd"
version = "latest"
}
}
locals {
registration_token = "${azurerm_virtual_desktop_host_pool_registration_info.reginfo.token}"
shutdown_command = "shutdown -r -t 10"
exit_code_hack = "exit 0"
commandtorun = "New-Item -Path HKLM:/SOFTWARE/Microsoft/RDInfraAgent/AADJPrivate"
powershell_command = "${local.commandtorun}; ${local.shutdown_command}; ${local.exit_code_hack}"
}
resource "azurerm_virtual_machine_extension" "xxxAVDModule" {
depends_on = [
azurerm_windows_virtual_machine.xxx_sessionhost
]
count = 2
name = "Microsoft.PowerShell.DSC"
virtual_machine_id = azurerm_windows_virtual_machine.avd_sessionhost.*.id[count.index]
publisher = "Microsoft.Powershell"
type = "DSC"
type_handler_version = "2.73"
settings = <<-SETTINGS
{
"modulesUrl": "https://wvdportalstorageblob.blob.core.windows.net/galleryartifacts/Configuration_11-22-2021.zip",
"ConfigurationFunction": "Configuration.ps1\\AddSessionHost",
"Properties" : {
"hostPoolName" : "${azurerm_virtual_desktop_host_pool.new-hp.name}",
"aadJoin": true
}
}
SETTINGS
protected_settings = <<PROTECTED_SETTINGS
{
"properties": {
"registrationInfoToken": "${azurerm_virtual_desktop_host_pool_registration_info.reginfo.token}"
}
}
PROTECTED_SETTINGS
}
resource "azurerm_virtual_machine_extension" "AADLoginForWindows" {
depends_on = [
azurerm_windows_virtual_machine.xxxx_sessionhost,
azurerm_virtual_machine_extension.AVDModule
]
count = 2
name = "AADLoginForWindows"
virtual_machine_id = azurerm_windows_virtual_machine.avd_sessionhost.*.id[count.index]
publisher = "Microsoft.Azure.ActiveDirectory"
type = "AADLoginForWindows"
type_handler_version = "1.0"
auto_upgrade_minor_version = true
}
resource "azurerm_virtual_machine_extension" "xxxxaadjprivate" {
depends_on = [
azurerm_virtual_machine_extension.AADLoginForWindows
]
count = 2
name = "AADJPRIVATE"
virtual_machine_id = azurerm_windows_virtual_machine.avd_sessionhost.*.id[count.index]
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.9"
settings = <<SETTINGS
{
"commandToExecute": "powershell.exe -Command \"${local.powershell_command}\""
}
SETTINGS
}
terraform plan:
terraform apply:
VM Joined in AD after deployment:
Virtual Machine Overview:

How to create azurerm_virtual_machine_extension with a network watcher installed

How to create azurerm_virtual_machine_extension with a network watcher installed. using a Powershell Script.
resource "azurerm_virtual_machine_extension" "example" {
name = "hostname"
virtual_machine_id = azurerm_virtual_machine.example.id
publisher = "Microsoft.Azure.Extensions"
type = "CustomScript"
type_handler_version = "2.0"
settings = <<SETTINGS
{
"commandToExecute": "hostname && uptime"
}
SETTINGS
tags = {
environment = "Production"
}
}
You can use this below terraform code to achive your requirement.
main.tf
provider "azurerm" {
features {}
}
data "azurerm_resource_group" "example" {
name = "v-raXXXX-XXX"
#location = "West Europe"
}
resource "azurerm_virtual_network" "example" {
name = "example-network"
address_space = ["10.0.0.0/16"]
location = data.azurerm_resource_group.example.location
resource_group_name = data.azurerm_resource_group.example.name
}
resource "azurerm_subnet" "example" {
name = "internal"
resource_group_name = data.azurerm_resource_group.example.name
virtual_network_name = azurerm_virtual_network.example.name
address_prefixes = ["10.0.2.0/24"]
}
resource "azurerm_network_interface" "example" {
name = "example-nic"
location = data.azurerm_resource_group.example.location
resource_group_name = data.azurerm_resource_group.example.name
ip_configuration {
name = "internal"
subnet_id = azurerm_subnet.example.id
private_ip_address_allocation = "Dynamic"
}
}
resource "azurerm_windows_virtual_machine" "example" {
name = "example-machine"
resource_group_name = data.azurerm_resource_group.example.name
location = data.azurerm_resource_group.example.location
size = "Standard_F2"
admin_username = "adminuser"
admin_password = "P#$$w0rd1234!"
network_interface_ids = [
azurerm_network_interface.example.id,
]
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
}
source_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2016-Datacenter"
version = "latest"
}
}
locals {
powershell_command = "Set-AzVMExtension -ResourceGroupName ${var.resource_group_name} -Location ${var.location} -VMName ${var.VM_Name}"
}
resource "azurerm_virtual_machine_extension" "example" {
name = "hostname2"
virtual_machine_id = azurerm_windows_virtual_machine.example.id
publisher = "Microsoft.Azure.NetworkWatcher"
type = "NetworkWatcherAgentWindows"
type_handler_version = "1.4"
settings = <<SETTINGS
{
"commandToExecute": "powershell.exe -Command \"${local.powershell_command}\""
}
SETTINGS
tags = {
environment = "Production"
}
depends_on = [
azurerm_windows_virtual_machine.example
]
}
variable.tf
variable "resource_group_name" {
default = "v-rXXXX-XXXee"
}
variable "location" {
default="West US 2"
}
variable "VM_Name" {
default = "example-machine"
}
OutPut--

Getting error PropertyChangeNotAllowed while creating VM in Azure

I’m trying to create a VM in Azure using below config.
resource “azurerm_virtual_machine” “VM38” {
name = “VM38”
resource_group_name = data.azurerm_resource_group.myRG.name
location = data.azurerm_resource_group.myRG.location
vm_size = “Standard_F16s_v2”
delete_os_disk_on_termination = true
delete_data_disks_on_termination = true
os_profile {
computer_name = “vm38”
admin_username = “adminuser”
admin_password = “Password1234!”
custom_data = base64encode(data.cloudinit_config.hybrid_vm38_cloudinit_cfg.rendered)
}
os_profile_linux_config {
disable_password_authentication = false
}
storage_image_reference {
id = data.azurerm_image.my_image.id
}
depends_on = [aws_instance.vm12]
storage_os_disk {
name = “VMDisk”
create_option = “FromImage”
caching = “ReadWrite”
#disk_size_gb = 16
#os_type = “Linux”
#managed_disk_type = “Standard_LRS”
vhd_uri = var.vmVHDURI
}
network_interface_ids = [azurerm_network_interface.mgmtNwIntf.id, azurerm_network_interface.transportNwIntf.id]
}
When I execute terraform apply I’m getting below error…
Error: compute.VirtualMachinesClient#CreateOrUpdate: Failure sending request: StatusCode=0 – Original Error: autorest/azure: Service returned an error. Status= Code=“PropertyChangeNotAllowed” Message=“Changing property ‘osDisk.name’ is not allowed.” Target=“osDisk.name”
with azurerm_virtual_machine.VM38,
on az_virtual_machine.tf line 1, in resource “azurerm_virtual_machine” “VM38”:
1: resource “azurerm_virtual_machine” “VM38” {
Please let me know how to resolve this issue.
Terraform and Azure provider version details are given below:
Terraform v1.0.8
on linux_amd64
provider registry.terraform.io/hashicorp/azurerm v2.79.1
Thanks & Regards,
-Ravi
**In terraform.tfvars**
resourceGroupName = "myResourceGroup"
deviceImageName = "myDeviceImageName"
**In cloudinit_config.tf**
data "cloudinit_config" "hybrid_vm38_cloudinit_cfg" {
gzip = false
base64_encode = false
depends_on = [aws_instance.hybrid_vm12]
part {
filename = "cloud-config"
content_type = "text/cloud-config"
content = file("cloudinit/vm38_cloud_config.yaml")
}
part {
filename = "config-C8K.txt"
content_type = "text/cloud-boothook"
content = file("cloudinit/vm38_cloud_boothook.cfg")
}
}
**In az_resource_group.tf**
data "azurerm_resource_group" "vm38RG" {
name = var.resourceGroupName
}
**In az_image.tf**
data "azurerm_image" "deviceImage" {
name = var.deviceImageName
resource_group_name = data.azurerm_resource_group.vm38RG.name
}
**In az_virtual_network.tf**
resource "azurerm_virtual_network" "vm38VirtualNw" {
name = "vm38VirtualNw"
address_space = ["30.0.0.0/16"]
location = "eastus"
resource_group_name = data.azurerm_resource_group.vm38RG.name
tags = {
environment = "My virtual network"
}
}
**In az_subnet.tf**
resource "azurerm_subnet" "vm38MgmtSubnet" {
name = "vm38MgmtSubnet"
resource_group_name = data.azurerm_resource_group.vm38RG.name
virtual_network_name = azurerm_virtual_network.vm38VirtualNw.name
address_prefixes = ["30.0.11.0/24"]
}
resource "azurerm_subnet" "vm38TransportSubnet" {
name = "vm38TransportSubnet"
resource_group_name = data.azurerm_resource_group.vm38RG.name
virtual_network_name = azurerm_virtual_network.vm38VirtualNw.name
address_prefixes = ["30.0.12.0/24"]
}
**In az_network_interface.tf**
resource "azurerm_network_interface" "vm38MgmtNwIntf" {
name = "vm38MgmtNwIntf"
location = data.azurerm_resource_group.vm38RG.location
resource_group_name = data.azurerm_resource_group.vm38RG.name
ip_configuration {
name = "vm38MgmtPvtIP"
subnet_id = azurerm_subnet.vm38MgmtSubnet.id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.vm38MgmtPublicIP.id
}
}
resource "azurerm_network_interface" "vm38TransportNwIntf" {
name = "vm38TransportNwIntf"
location = data.azurerm_resource_group.vm38RG.location
resource_group_name = data.azurerm_resource_group.vm38RG.name
ip_configuration {
name = "vm38TransportPvtIP"
subnet_id = azurerm_subnet.vm38TransportSubnet.id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.vm38TransportPublicIP.id
}
}
**In az_virtual_machine.tf**
resource "azurerm_virtual_machine" "VM38" {
name = "VM38"
resource_group_name = data.azurerm_resource_group.vm38RG.name
location = data.azurerm_resource_group.vm38RG.location
vm_size = "Standard_F16s_v2"
delete_os_disk_on_termination = true
#delete_data_disks_on_termination = true
os_profile {
computer_name = "vm38"
admin_username = "adminuser"
admin_password = "Password1234!"
custom_data = base64encode(data.cloudinit_config.hybrid_vm38_cloudinit_cfg.rendered)
}
os_profile_linux_config {
disable_password_authentication = false
}
storage_image_reference {
id = data.azurerm_image.deviceImage.id
}
depends_on = [aws_instance.hybrid_vm12]
storage_os_disk {
name = "osDisk"
create_option = "FromImage"
caching = "ReadWrite"
#disk_size_gb = 16
#os_type = "Linux"
managed_disk_type = "Standard_LRS"
}
/*
storage_data_disk {
name = "vm38SecondaryDisk"
caching = "ReadWrite"
create_option = "Empty"
disk_size_gb = 2048
lun = 0
managed_disk_type = "Premium_LRS"
}
*/
network_interface_ids = [
azurerm_network_interface.vm38MgmtNwIntf.id,
azurerm_network_interface.vm38TransportNwIntf.id
]
}
You can't change the os_disk name while creating the VM. It should be "osdisk" or something starting with that.
I tested using the below code:
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "example" {
name = "ansuman-resources"
location = "West US 2"
}
resource "azurerm_virtual_network" "example" {
name = "ansuman-network"
address_space = ["10.0.0.0/16"]
location = "${azurerm_resource_group.example.location}"
resource_group_name = "${azurerm_resource_group.example.name}"
}
resource "azurerm_subnet" "example" {
name = "internal"
resource_group_name = "${azurerm_resource_group.example.name}"
virtual_network_name = "${azurerm_virtual_network.example.name}"
address_prefixes = ["10.0.2.0/24"]
}
resource "azurerm_network_interface" "example" {
name = "ansuman-nic"
location = "${azurerm_resource_group.example.location}"
resource_group_name = "${azurerm_resource_group.example.name}"
ip_configuration {
name = "testconfiguration1"
subnet_id = "${azurerm_subnet.example.id}"
private_ip_address_allocation = "Dynamic"
}
}
# we assume that this Custom Image already exists
data "azurerm_image" "custom" {
name = "ansumantestvm-image-20211007225625"
resource_group_name = "resourcegroup"
}
resource "azurerm_virtual_machine" "example" {
name = "ansuman-vm"
location = "${azurerm_resource_group.example.location}"
resource_group_name = "${azurerm_resource_group.example.name}"
network_interface_ids = ["${azurerm_network_interface.example.id}"]
vm_size = "Standard_F2"
# This means the OS Disk will be deleted when Terraform destroys the Virtual Machine
# NOTE: This may not be optimal in all cases.
delete_os_disk_on_termination = true
storage_image_reference {
id = "${data.azurerm_image.custom.id}"
}
storage_os_disk {
name = "osdisk"
caching = "ReadWrite"
create_option = "FromImage"
managed_disk_type = "Standard_LRS"
}
os_profile {
computer_name = "hostname"
admin_username = "testadmin"
admin_password = "Password1234!"
}
os_profile_windows_config {
}
}
Output:
Note: Please make sure while creating the image from the original VM , first generalize it . If its not generalized then VM created from the custom image will get stuck in creating state and will not be able to boot up.
If you want to change the osdisk name to something of your choice then as a solution try creating the managed os disk first from the image using create option "copy" or "import" and then attach the disk while creating the VM as creating managed disk from custom image is also not supported ,it can be only done for platform image or marketplace image . You can refer this GitHub issue and this Github issue.
Reference terraform code for similar issue to give custom name to osdisk created from platform image/ market place image which Charles Xu has done in this SO thread.

Terraform enable VM Insights

Did someone managed to enable via terraforms Insights for a VM?
i'm able to create a VM, enable logging, but not enable insights..
i've seen this question: but don't find a clear answer..
How to enable azure vm application insights monitoring agent using terraform
Here is my full terraform script that i'm using for tests, i'm running it directly on the cloud shell from azure.
# Configure the Azure provider
provider "azurerm" {
# The "feature" block is required for AzureRM provider 2.x.
features {}
}
variable "prefix" {
default = "tfvmex"
}
resource "azurerm_resource_group" "main" {
name = "${var.prefix}-resources"
location = "West Europe"
}
resource "azurerm_virtual_network" "main" {
name = "${var.prefix}-network"
address_space = ["10.0.0.0/16"]
location = azurerm_resource_group.main.location
resource_group_name = azurerm_resource_group.main.name
}
resource "azurerm_subnet" "internal" {
name = "internal"
resource_group_name = azurerm_resource_group.main.name
virtual_network_name = azurerm_virtual_network.main.name
address_prefixes = ["10.0.2.0/24"]
}
resource "azurerm_network_interface" "main" {
name = "${var.prefix}-nic"
location = azurerm_resource_group.main.location
resource_group_name = azurerm_resource_group.main.name
ip_configuration {
name = "testconfiguration1"
subnet_id = azurerm_subnet.internal.id
private_ip_address_allocation = "Dynamic"
}
}
resource "azurerm_virtual_machine" "main" {
name = "${var.prefix}-vm"
location = azurerm_resource_group.main.location
resource_group_name = azurerm_resource_group.main.name
network_interface_ids = [azurerm_network_interface.main.id]
vm_size = "Standard_DS1_v2"
# Uncomment this line to delete the OS disk automatically when deleting the VM
# delete_os_disk_on_termination = true
# Uncomment this line to delete the data disks automatically when deleting the VM
# delete_data_disks_on_termination = true
storage_image_reference {
publisher = "Canonical"
offer = "UbuntuServer"
sku = "16.04-LTS"
version = "latest"
}
storage_os_disk {
name = "myosdisk1"
caching = "ReadWrite"
create_option = "FromImage"
managed_disk_type = "Standard_LRS"
}
os_profile {
computer_name = "hostname"
admin_username = "testadmin"
admin_password = "Password1234!"
}
os_profile_linux_config {
disable_password_authentication = false
}
tags = {
environment = "staging"
}
}
resource "azurerm_storage_account" "main" {
name = "omstesttest22"
resource_group_name = azurerm_resource_group.main.name
location = "westus"
account_tier = "Standard"
account_replication_type = "GRS"
tags = {
environment = "staging"
}
}
resource "azurerm_log_analytics_workspace" "law02" {
name = "${var.prefix}-logAnalytics"
location = azurerm_resource_group.main.location
resource_group_name = azurerm_resource_group.main.name
sku = "PerGB2018"
retention_in_days = 30
}
resource "azurerm_log_analytics_solution" "example" {
solution_name = "ContainerInsights"
location = azurerm_resource_group.main.location
resource_group_name = azurerm_resource_group.main.name
workspace_resource_id = azurerm_log_analytics_workspace.law02.id
workspace_name = azurerm_log_analytics_workspace.law02.name
plan {
publisher = "Microsoft"
product = "OMSGallery/ContainerInsights"
}
}
#===================================================================
# Set Monitoring and Log Analytics Workspace
#===================================================================
resource "azurerm_virtual_machine_extension" "oms_mma02" {
name = "test-OMSExtension"
virtual_machine_id = azurerm_virtual_machine.main.id
publisher = "Microsoft.EnterpriseCloud.Monitoring"
type = "OmsAgentForLinux"
type_handler_version = "1.12"
auto_upgrade_minor_version = true
settings = <<SETTINGS
{
"workspaceId" : "${azurerm_log_analytics_workspace.law02.workspace_id}"
}
SETTINGS
protected_settings = <<PROTECTED_SETTINGS
{
"workspaceKey" : "${azurerm_log_analytics_workspace.law02.primary_shared_key}"
}
PROTECTED_SETTINGS
}
Hope it was clear.
Thanks!
From the document, VM insights require the following two agents to be installed on each virtual machine to be monitored.
Log Analytics agent. Collects events and performance data from the virtual machine or virtual machine scale set and delivers it to the Log Analytics workspace. Deployment methods for the Log Analytics agent on Azure resources use the VM extension for Windows and Linux.
Dependency agent. Collects discovered data about processes running on the virtual machine and external process dependencies, which are used by the Map feature in VM insights. The Dependency agent relies on the Log Analytics agent to deliver its data to Azure Monitor. Deployment methods for the Dependency agent on Azure resources use the VM extension for Windows and Linux.
After my validation, you can add the DependencyAgent extension to your existing code.
resource "azurerm_virtual_machine_extension" "da" {
name = "DAExtension"
virtual_machine_id = azurerm_virtual_machine.main.id
publisher = "Microsoft.Azure.Monitoring.DependencyAgent"
type = "DependencyAgentLinux"
type_handler_version = "9.5"
auto_upgrade_minor_version = true
}
For more information, read Configure Log Analytics workspace for VM insights and Enable VM insights guest health (preview)
please use the product "OMSGallery/VMInsights" (instead of "OMSGallery/ContainerInsights")
resource "azurerm_log_analytics_solution" "..." {
solution_name = "..."
location = ...
resource_group_name = ...
workspace_resource_id = ...
workspace_name = ...
plan {
publisher = "Microsoft"
product = "OMSGallery/VMInsights"
}
}
To deploy it using Terraform:
Deploy a log analytics workspace and a VMInsights solution associated with the workspace.
resource "azurerm_log_analytics_workspace" "law" {
name = "LogAnalyticsWorkspace"
location = "Your location"
resource_group_name = "Your resource group"
sku = "PerGB2018"
retention_in_days = "your retention in days"
internet_ingestion_enabled= true
internet_query_enabled = false
tags = "Your tags"
}
resource "azurerm_log_analytics_solution" "vminsights" {
solution_name = "VMInsights"
location = "Your location"
resource_group_name = "Your resource group"
workspace_resource_id = azurerm_log_analytics_workspace.law.id
workspace_name = azurerm_log_analytics_workspace.law.name
tags = "Your tags"
plan {
publisher = "Microsoft"
product = "OMSGallery/VMInsights"
}
}
Deploy VM with as usual with OMSAgent and DependencyAgentWindows extensions:
resource "azurerm_windows_virtual_machine" "vm" {
......
......
}
OMS for Windows:
https://learn.microsoft.com/en-us/azure/virtual-machines/extensions/oms-windows
resource "azurerm_virtual_machine_extension" "omsext" {
name = "OMSExtension"
virtual_machine_id = azurerm_windows_virtual_machine.vm.id
publisher = "Microsoft.EnterpriseCloud.Monitoring"
type = "MicrosoftMonitoringAgent"
type_handler_version = "1.0"
auto_upgrade_minor_version = true
settings = <<SETTINGS
{
"workspaceId": "${azurerm_log_analytics_workspace.law.id}"
}
SETTINGS
protected_settings = <<PROTECTED_SETTINGS
{
"workspaceKey": "${azurerm_log_analytics_workspace.law.primary_shared_key}"
}
PROTECTED_SETTINGS
tags = "Your tags"
}
DA Agent for Windows:
https://learn.microsoft.com/en-us/azure/virtual-machines/extensions/agent-dependency-windows
resource "azurerm_virtual_machine_extension" "DAAgent" {
name = "DAAgentExtension"
virtual_machine_id = azurerm_windows_virtual_machine.vm.id
publisher = "Microsoft.Azure.Monitoring.DependencyAgent"
type = "DependencyAgentWindows"
type_handler_version = "9.10"
auto_upgrade_minor_version = true
tags = "Your tags"
}
Microsoft have changed the settings needed in the MicrosoftMonitoringAgent extensions, and the terraform specified by #Bill no longer works as of June 2022. The Terraform that worked for me was:
# Import the subscription and resource groups
data "azurerm_subscription" "current" {
}
data "azurerm_resource_group" "rg" {
name = "rg-name"
provider = azurerm
}
resource "random_password" "windowsvm-password" {
length = 24
special = false
}
# Define the VM itself
resource "azurerm_windows_virtual_machine" "windowsvm-c" {
name = "mywindowsvm"
computer_name = "mywindowsvm"
resource_group_name = data.azurerm_resource_group.rg.name
location = data.azurerm_resource_group.rg.location
size = "Standard_B2s"
admin_username = "adminlogin"
admin_password = random_password.windowsvm-password.result
identity { type = "SystemAssigned" }
network_interface_ids = [
azurerm_network_interface.windowsvm-c-nic.id,
]
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
}
source_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2022-datacenter-azure-edition-core"
version = "latest"
}
patch_mode = "AutomaticByPlatform"
hotpatching_enabled = true
}
# Add logging and monitoring
resource "azurerm_log_analytics_workspace" "law" {
name = "vmloganalytics"
resource_group_name = data.azurerm_resource_group.rg-c.name
location = data.azurerm_resource_group.rg-c.location
sku = "PerGB2018"
retention_in_days = 365
internet_ingestion_enabled= true
internet_query_enabled = false
}
resource "azurerm_log_analytics_solution" "vminsights" {
solution_name = "vminsights"
resource_group_name = data.azurerm_resource_group.rg-c.name
location = data.azurerm_resource_group.rg-c.location
workspace_resource_id = azurerm_log_analytics_workspace.law.id
workspace_name = azurerm_log_analytics_workspace.law.name
plan {
publisher = "Microsoft"
product = "VMInsights"
}
}
# This extension is needed for other extensions
resource "azurerm_virtual_machine_extension" "daa-agent" {
name = "DependencyAgentWindows"
virtual_machine_id = azurerm_windows_virtual_machine.windowsvm-c.id
publisher = "Microsoft.Azure.Monitoring.DependencyAgent"
type = "DependencyAgentWindows"
type_handler_version = "9.10"
automatic_upgrade_enabled = true
auto_upgrade_minor_version = true
}
# Add logging and monitoring extensions
resource "azurerm_virtual_machine_extension" "monitor-agent" {
depends_on = [ azurerm_virtual_machine_extension.daa-agent ]
name = "AzureMonitorWindowsAgent"
virtual_machine_id = azurerm_windows_virtual_machine.windowsvm-c.id
publisher = "Microsoft.Azure.Monitor"
type = "AzureMonitorWindowsAgent"
type_handler_version = "1.5"
automatic_upgrade_enabled = true
auto_upgrade_minor_version = true
}
resource "azurerm_virtual_machine_extension" "msmonitor-agent" {
depends_on = [ azurerm_virtual_machine_extension.daa-agent ]
name = "MicrosoftMonitoringAgent" # Must be called this
virtual_machine_id = azurerm_windows_virtual_machine.windowsvm-c.id
publisher = "Microsoft.EnterpriseCloud.Monitoring"
type = "MicrosoftMonitoringAgent"
type_handler_version = "1.0"
# Not yet supported
# automatic_upgrade_enabled = true
# auto_upgrade_minor_version = true
settings = <<SETTINGS
{
"workspaceId": "${azurerm_log_analytics_workspace.law.id}",
"azureResourceId": "${azurerm_windows_virtual_machine.windowsvm-c.id}",
"stopOnMultipleConnections": "false"
}
SETTINGS
protected_settings = <<PROTECTED_SETTINGS
{
"workspaceKey": "${azurerm_log_analytics_workspace.law.primary_shared_key}"
}
PROTECTED_SETTINGS
}
Note the extended settings under "msmonitor-agent"
Here are few articles for this topic, maybe you can reference to:
Azure Monitor for application monitoring with Terraform
Azure Insights: Terraform; Log Analytics Workspaces; Custom scripts with Arc-enabled servers; Virtual WAN resources

Terraform: Subnet in use azurerm

Error Message
I get the following error message when executing terraform apply:
Error: Error Creating/Updating Virtual Network "CTI-NETWORK" (Resource Group "CTI-RESOURCES"): network.VirtualNetworksClient#CreateOrUpdate: Failure sending request: StatusCode=400 -- Original Error: Code="InUseSubnetCannotBeDeleted" Message="Subnet CTI-PRD is in use by /subscriptions/d92e8f07-e127-4015-b67a-a547af76fdfc/resourceGroups/CTI-RESOURCES/providers/Microsoft.Network/networkInterfaces/CTI-NIC-PRD1/ipConfigurations/CTI-IP-PRD1 and cannot be deleted. In order to delete the subnet, delete all the resources within the subnet. See aka.ms/deletesubnet." Details=[]
I assume I've got a dependency mixed up but cant seem to figure it out.
Code Snippet
Content of main.tf
provider "azurerm" {
version = "=1.38.0"
subscription_id = "d92e8f07-e127-4015-b67a-a547af76fdfc"
}
resource "azurerm_resource_group" "resourcegroup" {
name = "${var.prefix}RESOURCES"
location = var.location
}
resource "azurerm_virtual_network" "network" {
name = "${var.prefix}NETWORK"
resource_group_name = azurerm_resource_group.resourcegroup.name
address_space = ["10.0.0.0/16"]
location = var.location
}
resource "azurerm_subnet" "prd-subnet" {
name = "${var.prefix}PRD"
resource_group_name = azurerm_resource_group.resourcegroup.name
virtual_network_name = azurerm_virtual_network.network.name
address_prefix = "10.0.0.0/24"
}
resource "azurerm_subnet" "tst-subnet" {
name = "${var.prefix}TST"
resource_group_name = azurerm_resource_group.resourcegroup.name
virtual_network_name = azurerm_virtual_network.network.name
address_prefix = "10.0.1.0/24"
}
resource "azurerm_public_ip" "ip-prd-1" {
name = "${var.prefix}PIP-PRD1"
resource_group_name = azurerm_resource_group.resourcegroup.name
location = var.location
allocation_method = "Dynamic"
domain_name_label = "vm-prd-1"
}
resource "azurerm_network_interface" "nic-prd-1" {
name = "${var.prefix}NIC-PRD1"
resource_group_name = azurerm_resource_group.resourcegroup.name
location = var.location
ip_configuration {
name = "${var.prefix}IP-PRD1"
subnet_id = azurerm_subnet.prd-subnet.id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.ip-prd-1.id
}
}
resource "azurerm_virtual_machine" "vm-prd-1" {
name = "${var.prefix}VM-PRD-1"
location = var.location
resource_group_name = azurerm_resource_group.resourcegroup.name
network_interface_ids = [azurerm_network_interface.nic-prd-1.id]
vm_size = var.size
delete_os_disk_on_termination = true
delete_data_disks_on_termination = true
storage_image_reference {
publisher = "credativ"
offer = "Debian"
sku = "9-backports"
version = "latest"
}
storage_os_disk {
name = "lin-disk-1"
caching = "ReadWrite"
create_option = "FromImage"
managed_disk_type = "Standard_LRS"
}
os_profile {
computer_name = "${var.prefix}IP-PRD1"
admin_username = "ADM-ADV"
admin_password = "!!W0rksh0p"
}
os_profile_linux_config {
disable_password_authentication = false
}
tags = {
environment = "Production"
application = "CTI Core"
}
}
resource "azurerm_public_ip" "ip-prd-2" {
name = "${var.prefix}PIP-PRD-2"
resource_group_name = azurerm_resource_group.resourcegroup.name
location = var.location
allocation_method = "Dynamic"
domain_name_label = "vm-prd-2"
}
resource "azurerm_network_interface" "nic-prd-2" {
name = "${var.prefix}NIC-PRD-2"
resource_group_name = azurerm_resource_group.resourcegroup.name
location = var.location
ip_configuration {
name = "${var.prefix}IP-PRD-2"
subnet_id = azurerm_subnet.prd-subnet.id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.ip-prd-2.id
}
}
resource "azurerm_virtual_machine" "vm-prd-chef" {
name = "${var.prefix}VM-PRD-CHEF"
location = var.location
resource_group_name = azurerm_resource_group.resourcegroup.name
network_interface_ids = [azurerm_network_interface.nic-prd-2.id]
vm_size = var.size
delete_os_disk_on_termination = true
delete_data_disks_on_termination = true
storage_image_reference {
publisher = "Canonical"
offer = "UbuntuServer"
sku = "18.04-LTS"
version = "latest"
}
storage_os_disk {
name = "lin-disk-2"
caching = "ReadWrite"
create_option = "FromImage"
managed_disk_type = "Standard_LRS"
}
os_profile {
computer_name = "${var.prefix}IP-PRD-CHEF"
admin_username = "XXX"
admin_password = "XXX"
}
os_profile_linux_config {
disable_password_authentication = false
}
tags = {
environment = "Production"
application = "CTI Service"
}
provisioner "remote-exec" {
inline = [
"touch /root/test.txt"
]
}
}
Content of variables.tf
variable "prefix" {
type = string
default = "CTI-"
description = "Prefix of the resources"
}
variable "location" {
type = string
default = "westeurope"
description = "Location of the resources"
}
variable "size" {
type = string
default = "Standard_A1_v2"
description = "Size of the virtual machines"
}
Thanks for you help!
With the message you provided, you want to create another VM in the existing subnet of the Vnet. So you need to use the data resource instead of the resource format. Change your Terraform code like this:
Change:
resource "azurerm_virtual_network" "network" {
name = "${var.prefix}NETWORK"
resource_group_name = azurerm_resource_group.resourcegroup.name
address_space = ["10.0.0.0/16"]
location = var.location
}
resource "azurerm_subnet" "prd-subnet" {
name = "${var.prefix}PRD"
resource_group_name = azurerm_resource_group.resourcegroup.name
virtual_network_name = azurerm_virtual_network.network.name
address_prefix = "10.0.0.0/24"
}
Into:
data "azurerm_virtual_network" "network" {
name = "${var.prefix}NETWORK"
resource_group_name = azurerm_resource_group.resourcegroup.name
}
data "azurerm_subnet" "prd-subnet" {
name = "${var.prefix}PRD"
virtual_network_name = data.azurerm_virtual_network.network.name
resource_group_name = azurerm_resource_group.resourcegroup.name
}
resource "azurerm_network_interface" "nic-prd-1" {
name = "${var.prefix}NIC-PRD1"
resource_group_name = azurerm_resource_group.resourcegroup.name
location = var.location
ip_configuration {
name = "${var.prefix}IP-PRD1"
subnet_id = data.azurerm_subnet.prd-subnet.id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.ip-prd-1.id
}
}
The Terraform data will quote the existing resource and do not change them. If the other subnet tst-subnet is also existing, you can change it like above yourself.

Resources