Bobby
Bobby

Reputation: 97

attach an existing managed disk to a new VM using ARM template

I wanted to deploy a vm with managed disks . I have already created a managed disk in another resource group and I want to use this during the template deployment. I am currently blocked here.

I am Using the below parameter here existingVirtualNetworkResourceGroup , this has the managed disk I wanted to use it in my template.

parameters:

"existingVirtualNetworkResourceGroup": { "type": "string", "defaultValue": "poc-rg", "allowedValues": [ "poc-rg" ],

varibales:

"managedDisklocation":"[resourceId(parameters('existingVirtualNetworkResourceGroup'), 'Microsoft.Compute/disks')]",
"managedDiskpath":"[concat(variables(managedDisklocation),'/poc-manageddisk')]"

resources:

{
    "apiVersion": "2015-05-01-preview",
    "type": "Microsoft.Compute/virtualMachines",
    "name": "[variables('vmNameMdb')]",
    "location": "[resourceGroup().location]",
    "dependsOn": ["[concat('Microsoft.Storage/storageAccounts/', variables('newStorageAccountName'))]",
    "[concat('Microsoft.Network/networkInterfaces/', variables('nicName'))]"],
    "properties": {
        "hardwareProfile": {
            "vmSize": "[parameters('vmSize')]"
        },
        "osProfile": {
            "computerName": "[variables('vmNameMdb')]",
            "adminUsername": "[parameters('adminUsername')]",
            "adminPassword": "[parameters('adminPassword')]",
            "secrets": [{
                "sourceVault": {
                    "id": "[parameters('keyVaultSubscriptionId')]"
                },
                "vaultCertificates": [{
                    "certificateUrl": "[parameters('engineCertificate')]"
                }],
                "vaultCertificates": [{
                    "certificateUrl": "[parameters('vmAgentCertificate')]"
                }]
            }]
        },
        "storageProfile": {
            "imageReference": {
                "publisher": "[parameters('imagePublisher')]",
                "offer": "[parameters('imageOffer')]",
                "sku": "[parameters('imageSKU')]",
                "version": "latest"
            },
            "osDisk": {
                "createOption": "FromImage"
            },
            "dataDisks": [
            {
                "lun": 0,
                "name": "[concat(parameters('vmName'),'-datadisk1')]",
                "createOption": "attach",
                "managedDisk": {
                        "id": "[parameters(managedDiskpath)]"
                }
            }
        ]
        },
        "networkProfile": {
            "networkInterfaces": [{
                "id": "[resourceId('Microsoft.Network/networkInterfaces',variables('nicName'))]"
            }]
        }
    }
},

Error:

Deployment template validation failed: 'The template variable 'managedDisklocation' is not valid: Unable to evaluate template language function 'resourceId': the type 'Microsoft.Compute/disks' requires '1' resource name argument(s). Please see https://aka.ms/arm-template-expressions/#resourceid for usage details.. Please see https://aka.ms/arm-template-expressions for usage details.'. (Code: InvalidTemplate)

Upvotes: 0

Views: 3938

Answers (5)

Divyamshu Gupta
Divyamshu Gupta

Reputation: 21

Here is the code to create new disks and attach them to an existing Virtual Machine that's running. With this, you can attach multiple disks mentioned in the disk count.

Important! Make sure the virtual machine and your created disks belong to same Resource Group and Location.

Template.json

{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "vmPrefixName": {
            "type": "String"
        },
        "vmCount": {
            "defaultValue": 1,
            "type": "Int"
        },
        "diskStorageType": {
            "defaultValue": "StandardSSD_LRS",
            "allowedValues": [
                "StandardSSD_LRS",
                "Premium_LRS"
            ],
            "type": "String"
        },
        "dataDiskCount": {
            "defaultValue": 1,
            "type": "Int"
        },
        "dataDiskSize": {
            "defaultValue": [],
            "type": "Array"
        },
        "location": {
            "defaultValue": "[resourceGroup().location]",
            "type": "String"
        }
    },
    "resources": [
        {
            "type": "Microsoft.Compute/virtualMachines",
            "apiVersion": "2018-06-01",
            "name": "[concat(parameters('vmPrefixName'),string(if(greater(parameters('vmCount'),1),copyIndex(1),'')))]",
            "location": "[parameters('location')]",
            "properties": {
                "storageProfile": {
                    "copy": [
                        {
                            "name": "dataDisks",
                            "count": "[parameters('dataDiskCount')]",
                            "input": {
                                "name": "[concat(concat(parameters('vmPrefixName'),string(if(greater(parameters('vmCount'),1),copyIndex(1),''))),'_datadisk', string(add(copyIndex('dataDisks'),1)))]",
                                "lun": "[copyIndex('dataDisks')]",
                                "createOption": "Empty",
                                "diskSizeGB": "[parameters('dataDiskSize')[copyIndex('dataDisks')]]",
                                "managedDisk": {
                                    "storageAccountType": "[parameters('diskStorageType')]"
                                }
                            }
                        }
                    ]
                }
            }
        }
    ]
}

Parameter.json

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "vmPrefixName": {
      "value": ""
    },
    "vmCount": {
      "value": 1
    },
    "diskStorageType": {
      "value": ""
    },
    "dataDiskCount": {
      "value": 2
    },
    "dataDiskSize": {
      "value": [
        128,
        64
      ]
    },
    "location": {
      "value": "eastus"
    }
  }
}

Upvotes: 0

Hannel
Hannel

Reputation: 1706

I was successfully able to able to deploy VM with attached disk from different resource group but same region with template below.

{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "virtualMachineName": {
            "type": "String"
        },
        "virtualMachineSize": {
            "type": "String"
        },
        "adminUsername": {
            "type": "String"
        },
        "virtualNetworkName": {
            "type": "String"
        },
        "networkInterfaceName": {
            "type": "String"
        },
        "networkSecurityGroupName": {
            "type": "String"
        },
        "adminPassword": {
            "type": "SecureString"
        },
        "diagnosticsStorageAccountName": {
            "type": "String"
        },
        "publicIpAddressName": {
            "type": "String"
        },
        "manageddiskpath": {
            "type": "String"
        }
    },
    "variables": {
        "vnetId": "[resourceId('Microsoft.Network/virtualNetworks', parameters('virtualNetworkName'))]",
        "subnetRef": "[concat(variables('vnetId'), '/subnets/','default')]"
    },
    "resources": [
        {
            "type": "Microsoft.Compute/virtualMachines",
            "name": "[parameters('virtualMachineName')]",
            "apiVersion": "2016-04-30-preview",
            "location": "[resourceGroup().location]",
            "properties": {
                "osProfile": {
                    "computerName": "[parameters('virtualMachineName')]",
                    "adminUsername": "[parameters('adminUsername')]",
                    "adminPassword": "[parameters('adminPassword')]"
                },
                "hardwareProfile": {
                    "vmSize": "[parameters('virtualMachineSize')]"
                },
                "storageProfile": {
                    "imageReference": {
                        "publisher": "Canonical",
                        "offer": "UbuntuServer",
                        "sku": "16.04-LTS",
                        "version": "latest"
                    },
                    "osDisk": {
                        "createOption": "FromImage",
                        "managedDisk": {
                            "storageAccountType": "Standard_LRS"
                        }
                    },
                    "dataDisks": [
                        {
                            "lun": 0,
                            "createOption": "Attach",
                            "managedDisk": {
                                "id": "[parameters('manageddiskpath')]"
                            }
                        }
                    ]
                },
                "networkProfile": {
                    "networkInterfaces": [
                        {
                            "id": "[resourceId('Microsoft.Network/networkInterfaces', parameters('networkInterfaceName'))]"
                        }
                    ]
                },
                "diagnosticsProfile": {
                    "bootDiagnostics": {
                        "enabled": true,
                        "storageUri": "[reference(resourceId('Microsoft.Storage/storageAccounts', parameters('diagnosticsStorageAccountName')), '2015-06-15').primaryEndpoints['blob']]"
                    }
                }
            },
            "dependsOn": [
                "[concat('Microsoft.Network/networkInterfaces/', parameters('networkInterfaceName'))]"
            ]
        },
        {
            "type": "Microsoft.Network/networkInterfaces",
            "name": "[parameters('networkInterfaceName')]",
            "apiVersion": "2016-09-01",
            "location": "[resourceGroup().location]",
            "properties": {
                "ipConfigurations": [
                    {
                        "name": "ipconfig1",
                        "properties": {
                            "subnet": {
                                "id": "[variables('subnetRef')]"
                            },
                            "privateIPAllocationMethod": "Dynamic",
                            "publicIpAddress": {
                                "id": "[resourceId('Microsoft.Network/publicIpAddresses', parameters('publicIpAddressName'))]"
                            }
                        }
                    }
                ],
                "networkSecurityGroup": {
                    "id": "[resourceId('Microsoft.Network/networkSecurityGroups', parameters('networkSecurityGroupName'))]"
                }
            },
            "dependsOn": [
                "[concat('Microsoft.Network/publicIpAddresses/', parameters('publicIpAddressName'))]",
                "[concat('Microsoft.Network/networkSecurityGroups/', parameters('networkSecurityGroupName'))]"
            ]
        },
        {
            "type": "Microsoft.Network/publicIpAddresses",
            "sku": {
                "name": "Basic"
            },
            "name": "[parameters('publicIpAddressName')]",
            "apiVersion": "2017-08-01",
            "location": "[resourceGroup().location]",
            "properties": {
                "publicIpAllocationMethod": "Dynamic"
            }
        },
        {
            "type": "Microsoft.Network/networkSecurityGroups",
            "name": "[parameters('networkSecurityGroupName')]",
            "apiVersion": "2017-06-01",
            "location": "[resourceGroup().location]",
            "properties": {
                "securityRules": [
                    {
                        "name": "default-allow-ssh",
                        "properties": {
                            "priority": 1000,
                            "protocol": "TCP",
                            "access": "Allow",
                            "direction": "Inbound",
                            "sourceAddressPrefix": "*",
                            "sourcePortRange": "*",
                            "destinationAddressPrefix": "*",
                            "destinationPortRange": "22"
                        }
                    }
                ]
            }
        }
    ],
    "outputs": {
        "adminUsername": {
            "type": "String",
            "value": "[parameters('adminUsername')]"
        }
    }
}

Key area, setting the ResourceID for the managed disk as a parameter, since its static and can't be generated.

enter image description here

enter image description here

enter image description here

enter image description here

Hope this helps.

Upvotes: 0

Hannel
Hannel

Reputation: 1706

Looking at the code again carefully, not sure why you have 'managedDisklocation' in the 'managedDiskpath' variable. The 'managedDiskpath' variable should look like below to map to the 'poc-manageddisk' managed disk.

"managedDiskpath":"[resourceId('Microsoft.Compute/disks/poc-manageddisk')]"

Upvotes: 0

Sa Yang
Sa Yang

Reputation: 9411

the Error you got shows the reason:

'The template variable 'managedDisklocation' is not valid: Unable to evaluate template language function '

If you want to attach another disk to Azure VM, the disk's location must be same as the orginal one. It means that the locations of the VM and Disks should be same.

Upvotes: 0

Hannel
Hannel

Reputation: 1706

Are both resource group in the same Location?

Because resources must be in same region.

Upvotes: 0

Related Questions