The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}?api-version=2024-07-01
URI Parameters
Name |
In |
Required |
Type |
Description |
resourceGroupName
|
path |
True
|
string
|
The name of the resource group.
|
subscriptionId
|
path |
True
|
string
|
Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.
|
vmName
|
path |
True
|
string
|
The name of the virtual machine.
|
api-version
|
query |
True
|
string
|
Client Api Version.
|
Name |
Required |
Type |
Description |
If-Match
|
|
string
|
The ETag of the transformation. Omit this value to always overwrite the current resource. Specify the last-seen ETag value to prevent accidentally overwriting concurrent changes.
|
If-None-Match
|
|
string
|
Set to '*' to allow a new record set to be created, but to prevent updating an existing record set. Other values will result in error from server as they are not supported.
|
Request Body
Name |
Type |
Description |
parameters
|
VirtualMachine
|
Parameters supplied to the Create Virtual Machine operation.
|
Responses
Security
azure_auth
Azure Active Directory OAuth2 Flow
Type:
oauth2
Flow:
implicit
Authorization URL:
https://login.microsoftonline.com/common/oauth2/authorize
Scopes
Name |
Description |
user_impersonation
|
impersonate your user account
|
Examples
Create a custom-image vm from an unmanaged generalized os image.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/{vm-name}?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"osDisk": {
"name": "myVMosdisk",
"image": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/{existing-generalized-os-image-blob-name}.vhd"
},
"osType": "Windows",
"createOption": "FromImage",
"caching": "ReadWrite",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd"
}
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.OperatingSystemTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualHardDisk;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_CustomImageVmFromAnUnmanagedGeneralizedOsImage.json
*/
/**
* Sample code: Create a custom-image vm from an unmanaged generalized os image.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void
createACustomImageVmFromAnUnmanagedGeneralizedOsImage(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines()
.createOrUpdate("myResourceGroup", "{vm-name}", new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile().withOsDisk(new OSDisk()
.withOsType(OperatingSystemTypes.WINDOWS).withName("myVMosdisk")
.withVhd(new VirtualHardDisk().withUri(
"http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd"))
.withImage(new VirtualHardDisk().withUri(
"http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/{existing-generalized-os-image-blob-name}.vhd"))
.withCaching(CachingTypes.READ_WRITE).withCreateOption(DiskCreateOptionTypes.FROM_IMAGE)))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_custom_image_vm_from_an_unmanaged_generalized_os_image.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="{vm-name}",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"image": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/{existing-generalized-os-image-blob-name}.vhd"
},
"name": "myVMosdisk",
"osType": "Windows",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd"
},
}
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_CustomImageVmFromAnUnmanagedGeneralizedOsImage.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_CustomImageVmFromAnUnmanagedGeneralizedOsImage.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createACustomImageVmFromAnUnmanagedGeneralizedOsImage() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "{vm-name}", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
Image: &armcompute.VirtualHardDisk{
URI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/{existing-generalized-os-image-blob-name}.vhd"),
},
OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
Vhd: &armcompute.VirtualHardDisk{
URI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd"),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// Image: &armcompute.VirtualHardDisk{
// URI: to.Ptr("https://{existing-storage-account-name}.blob.core.windows.net/system/Microsoft.Compute/Images/vhds/{existing-generalized-os-image-blob-name}.vhd"),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// Vhd: &armcompute.VirtualHardDisk{
// URI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net/vhds/myDisk.vhd"),
// },
// },
// },
// VMID: to.Ptr("926cd555-a07c-4ff5-b214-4aa4dd09d79b"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_CustomImageVmFromAnUnmanagedGeneralizedOsImage.json
*/
async function createACustomImageVMFromAnUnmanagedGeneralizedOSImage() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "{vm-name}";
const parameters = {
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
image: {
uri: "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/{existing-generalized-os-image-blob-name}.vhd",
},
osType: "Windows",
vhd: {
uri: "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd",
},
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_CustomImageVmFromAnUnmanagedGeneralizedOsImage.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "{vm-name}";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
OSType = SupportedOperatingSystemType.Windows,
Name = "myVMosdisk",
VhdUri = new Uri("http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd"),
ImageUri = new Uri("http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/{existing-generalized-os-image-blob-name}.vhd"),
Caching = CachingType.ReadWrite,
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"osDisk": {
"name": "myVMosdisk",
"image": {
"uri": "https://{existing-storage-account-name}.blob.core.windows.net/system/Microsoft.Compute/Images/vhds/{existing-generalized-os-image-blob-name}.vhd"
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Windows",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/vhds/myDisk.vhd"
}
},
"dataDisks": []
},
"vmId": "926cd555-a07c-4ff5-b214-4aa4dd09d79b",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"osDisk": {
"name": "myVMosdisk",
"image": {
"uri": "https://{existing-storage-account-name}.blob.core.windows.net/system/Microsoft.Compute/Images/vhds/{existing-generalized-os-image-blob-name}.vhd"
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Windows",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/vhds/myDisk.vhd"
}
},
"dataDisks": []
},
"vmId": "926cd555-a07c-4ff5-b214-4aa4dd09d79b",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a Linux vm with a patch setting assessmentMode of ImageDefault.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Premium_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}",
"linuxConfiguration": {
"provisionVMAgent": true,
"patchSettings": {
"assessmentMode": "ImageDefault"
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.LinuxConfiguration;
import com.azure.resourcemanager.compute.models.LinuxPatchAssessmentMode;
import com.azure.resourcemanager.compute.models.LinuxPatchSettings;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingAssessmentModeOfImageDefault.json
*/
/**
* Sample code: Create a Linux vm with a patch setting assessmentMode of ImageDefault.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createALinuxVmWithAPatchSettingAssessmentModeOfImageDefault(
com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D2S_V3))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer")
.withSku("16.04-LTS").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.PREMIUM_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder")
.withLinuxConfiguration(new LinuxConfiguration().withProvisionVMAgent(true).withPatchSettings(
new LinuxPatchSettings().withAssessmentMode(LinuxPatchAssessmentMode.IMAGE_DEFAULT))))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_linux_vm_with_patch_setting_assessment_mode_of_image_default.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
"linuxConfiguration": {
"patchSettings": {"assessmentMode": "ImageDefault"},
"provisionVMAgent": True,
},
},
"storageProfile": {
"imageReference": {
"offer": "UbuntuServer",
"publisher": "Canonical",
"sku": "16.04-LTS",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Premium_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingAssessmentModeOfImageDefault.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingAssessmentModeOfImageDefault.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createALinuxVmWithAPatchSettingAssessmentModeOfImageDefault() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
LinuxConfiguration: &armcompute.LinuxConfiguration{
PatchSettings: &armcompute.LinuxPatchSettings{
AssessmentMode: to.Ptr(armcompute.LinuxPatchAssessmentModeImageDefault),
},
ProvisionVMAgent: to.Ptr(true),
},
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("UbuntuServer"),
Publisher: to.Ptr("Canonical"),
SKU: to.Ptr("16.04-LTS"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesPremiumLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// LinuxConfiguration: &armcompute.LinuxConfiguration{
// PatchSettings: &armcompute.LinuxPatchSettings{
// AssessmentMode: to.Ptr(armcompute.LinuxPatchAssessmentModeImageDefault),
// },
// ProvisionVMAgent: to.Ptr(true),
// },
// Secrets: []*armcompute.VaultSecretGroup{
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("UbuntuServer"),
// Publisher: to.Ptr("Canonical"),
// SKU: to.Ptr("16.04-LTS"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesPremiumLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesLinux),
// },
// },
// VMID: to.Ptr("a149cd25-409f-41af-8088-275f5486bc93"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingAssessmentModeOfImageDefault.json
*/
async function createALinuxVMWithAPatchSettingAssessmentModeOfImageDefault() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D2s_v3" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
linuxConfiguration: {
patchSettings: { assessmentMode: "ImageDefault" },
provisionVMAgent: true,
},
},
storageProfile: {
imageReference: {
offer: "UbuntuServer",
publisher: "Canonical",
sku: "16.04-LTS",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Premium_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingAssessmentModeOfImageDefault.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD2SV3,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "Canonical",
Offer = "UbuntuServer",
Sku = "16.04-LTS",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.PremiumLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
LinuxConfiguration = new LinuxConfiguration()
{
ProvisionVmAgent = true,
PatchSettings = new LinuxPatchSettings()
{
AssessmentMode = LinuxPatchAssessmentMode.ImageDefault,
},
},
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"provisionVMAgent": true,
"patchSettings": {
"assessmentMode": "ImageDefault"
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"osType": "Linux",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Premium_LRS"
}
},
"dataDisks": []
},
"vmId": "a149cd25-409f-41af-8088-275f5486bc93",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"provisionVMAgent": true,
"patchSettings": {
"assessmentMode": "ImageDefault"
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"osType": "Linux",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Premium_LRS"
}
},
"dataDisks": []
},
"vmId": "a149cd25-409f-41af-8088-275f5486bc93",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Premium_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}",
"linuxConfiguration": {
"provisionVMAgent": true,
"patchSettings": {
"patchMode": "AutomaticByPlatform",
"assessmentMode": "AutomaticByPlatform",
"automaticByPlatformSettings": {
"rebootSetting": "Never",
"bypassPlatformSafetyChecksOnUserSchedule": true
}
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.LinuxConfiguration;
import com.azure.resourcemanager.compute.models.LinuxPatchAssessmentMode;
import com.azure.resourcemanager.compute.models.LinuxPatchSettings;
import com.azure.resourcemanager.compute.models.LinuxVMGuestPatchAutomaticByPlatformRebootSetting;
import com.azure.resourcemanager.compute.models.LinuxVMGuestPatchAutomaticByPlatformSettings;
import com.azure.resourcemanager.compute.models.LinuxVMGuestPatchMode;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_LinuxVmWithAutomaticByPlatformSettings.json
*/
/**
* Sample code: Create a Linux vm with a patch setting patchMode of AutomaticByPlatform and
* AutomaticByPlatformSettings.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createALinuxVmWithAPatchSettingPatchModeOfAutomaticByPlatformAndAutomaticByPlatformSettings(
com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D2S_V3))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer")
.withSku("16.04-LTS").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.PREMIUM_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder")
.withLinuxConfiguration(new LinuxConfiguration().withProvisionVMAgent(true).withPatchSettings(
new LinuxPatchSettings().withPatchMode(LinuxVMGuestPatchMode.AUTOMATIC_BY_PLATFORM)
.withAssessmentMode(LinuxPatchAssessmentMode.AUTOMATIC_BY_PLATFORM)
.withAutomaticByPlatformSettings(new LinuxVMGuestPatchAutomaticByPlatformSettings()
.withRebootSetting(LinuxVMGuestPatchAutomaticByPlatformRebootSetting.NEVER)
.withBypassPlatformSafetyChecksOnUserSchedule(true)))))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_linux_vm_with_automatic_by_platform_settings.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
"linuxConfiguration": {
"patchSettings": {
"assessmentMode": "AutomaticByPlatform",
"automaticByPlatformSettings": {
"bypassPlatformSafetyChecksOnUserSchedule": True,
"rebootSetting": "Never",
},
"patchMode": "AutomaticByPlatform",
},
"provisionVMAgent": True,
},
},
"storageProfile": {
"imageReference": {
"offer": "UbuntuServer",
"publisher": "Canonical",
"sku": "16.04-LTS",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Premium_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithAutomaticByPlatformSettings.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithAutomaticByPlatformSettings.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createALinuxVmWithAPatchSettingPatchModeOfAutomaticByPlatformAndAutomaticByPlatformSettings() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
LinuxConfiguration: &armcompute.LinuxConfiguration{
PatchSettings: &armcompute.LinuxPatchSettings{
AssessmentMode: to.Ptr(armcompute.LinuxPatchAssessmentModeAutomaticByPlatform),
AutomaticByPlatformSettings: &armcompute.LinuxVMGuestPatchAutomaticByPlatformSettings{
BypassPlatformSafetyChecksOnUserSchedule: to.Ptr(true),
RebootSetting: to.Ptr(armcompute.LinuxVMGuestPatchAutomaticByPlatformRebootSettingNever),
},
PatchMode: to.Ptr(armcompute.LinuxVMGuestPatchModeAutomaticByPlatform),
},
ProvisionVMAgent: to.Ptr(true),
},
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("UbuntuServer"),
Publisher: to.Ptr("Canonical"),
SKU: to.Ptr("16.04-LTS"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesPremiumLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// LinuxConfiguration: &armcompute.LinuxConfiguration{
// PatchSettings: &armcompute.LinuxPatchSettings{
// AssessmentMode: to.Ptr(armcompute.LinuxPatchAssessmentModeAutomaticByPlatform),
// AutomaticByPlatformSettings: &armcompute.LinuxVMGuestPatchAutomaticByPlatformSettings{
// BypassPlatformSafetyChecksOnUserSchedule: to.Ptr(true),
// RebootSetting: to.Ptr(armcompute.LinuxVMGuestPatchAutomaticByPlatformRebootSettingNever),
// },
// PatchMode: to.Ptr(armcompute.LinuxVMGuestPatchModeAutomaticByPlatform),
// },
// ProvisionVMAgent: to.Ptr(true),
// },
// Secrets: []*armcompute.VaultSecretGroup{
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("UbuntuServer"),
// Publisher: to.Ptr("Canonical"),
// SKU: to.Ptr("16.04-LTS"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesPremiumLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesLinux),
// },
// },
// VMID: to.Ptr("a149cd25-409f-41af-8088-275f5486bc93"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithAutomaticByPlatformSettings.json
*/
async function createALinuxVMWithAPatchSettingPatchModeOfAutomaticByPlatformAndAutomaticByPlatformSettings() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D2s_v3" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
linuxConfiguration: {
patchSettings: {
assessmentMode: "AutomaticByPlatform",
automaticByPlatformSettings: {
bypassPlatformSafetyChecksOnUserSchedule: true,
rebootSetting: "Never",
},
patchMode: "AutomaticByPlatform",
},
provisionVMAgent: true,
},
},
storageProfile: {
imageReference: {
offer: "UbuntuServer",
publisher: "Canonical",
sku: "16.04-LTS",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Premium_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithAutomaticByPlatformSettings.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD2SV3,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "Canonical",
Offer = "UbuntuServer",
Sku = "16.04-LTS",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.PremiumLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
LinuxConfiguration = new LinuxConfiguration()
{
ProvisionVmAgent = true,
PatchSettings = new LinuxPatchSettings()
{
PatchMode = LinuxVmGuestPatchMode.AutomaticByPlatform,
AssessmentMode = LinuxPatchAssessmentMode.AutomaticByPlatform,
AutomaticByPlatformSettings = new LinuxVmGuestPatchAutomaticByPlatformSettings()
{
RebootSetting = LinuxVmGuestPatchAutomaticByPlatformRebootSetting.Never,
BypassPlatformSafetyChecksOnUserSchedule = true,
},
},
},
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"provisionVMAgent": true,
"patchSettings": {
"patchMode": "AutomaticByPlatform",
"assessmentMode": "AutomaticByPlatform",
"automaticByPlatformSettings": {
"rebootSetting": "Never",
"bypassPlatformSafetyChecksOnUserSchedule": true
}
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"osType": "Linux",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Premium_LRS"
}
},
"dataDisks": []
},
"vmId": "a149cd25-409f-41af-8088-275f5486bc93",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"provisionVMAgent": true,
"patchSettings": {
"patchMode": "AutomaticByPlatform",
"assessmentMode": "AutomaticByPlatform",
"automaticByPlatformSettings": {
"rebootSetting": "Never",
"bypassPlatformSafetyChecksOnUserSchedule": true
}
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"osType": "Linux",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Premium_LRS"
}
},
"dataDisks": []
},
"vmId": "a149cd25-409f-41af-8088-275f5486bc93",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a Linux vm with a patch setting patchMode of ImageDefault.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Premium_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}",
"linuxConfiguration": {
"provisionVMAgent": true,
"patchSettings": {
"patchMode": "ImageDefault"
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.LinuxConfiguration;
import com.azure.resourcemanager.compute.models.LinuxPatchSettings;
import com.azure.resourcemanager.compute.models.LinuxVMGuestPatchMode;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingModeOfImageDefault.json
*/
/**
* Sample code: Create a Linux vm with a patch setting patchMode of ImageDefault.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void
createALinuxVmWithAPatchSettingPatchModeOfImageDefault(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D2S_V3))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer")
.withSku("16.04-LTS").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.PREMIUM_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder")
.withLinuxConfiguration(new LinuxConfiguration().withProvisionVMAgent(true).withPatchSettings(
new LinuxPatchSettings().withPatchMode(LinuxVMGuestPatchMode.IMAGE_DEFAULT))))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_linux_vm_with_patch_setting_mode_of_image_default.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
"linuxConfiguration": {"patchSettings": {"patchMode": "ImageDefault"}, "provisionVMAgent": True},
},
"storageProfile": {
"imageReference": {
"offer": "UbuntuServer",
"publisher": "Canonical",
"sku": "16.04-LTS",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Premium_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingModeOfImageDefault.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingModeOfImageDefault.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createALinuxVmWithAPatchSettingPatchModeOfImageDefault() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
LinuxConfiguration: &armcompute.LinuxConfiguration{
PatchSettings: &armcompute.LinuxPatchSettings{
PatchMode: to.Ptr(armcompute.LinuxVMGuestPatchModeImageDefault),
},
ProvisionVMAgent: to.Ptr(true),
},
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("UbuntuServer"),
Publisher: to.Ptr("Canonical"),
SKU: to.Ptr("16.04-LTS"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesPremiumLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// LinuxConfiguration: &armcompute.LinuxConfiguration{
// PatchSettings: &armcompute.LinuxPatchSettings{
// PatchMode: to.Ptr(armcompute.LinuxVMGuestPatchModeImageDefault),
// },
// ProvisionVMAgent: to.Ptr(true),
// },
// Secrets: []*armcompute.VaultSecretGroup{
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("UbuntuServer"),
// Publisher: to.Ptr("Canonical"),
// SKU: to.Ptr("16.04-LTS"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesPremiumLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesLinux),
// },
// },
// VMID: to.Ptr("a149cd25-409f-41af-8088-275f5486bc93"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingModeOfImageDefault.json
*/
async function createALinuxVMWithAPatchSettingPatchModeOfImageDefault() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D2s_v3" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
linuxConfiguration: {
patchSettings: { patchMode: "ImageDefault" },
provisionVMAgent: true,
},
},
storageProfile: {
imageReference: {
offer: "UbuntuServer",
publisher: "Canonical",
sku: "16.04-LTS",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Premium_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingModeOfImageDefault.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD2SV3,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "Canonical",
Offer = "UbuntuServer",
Sku = "16.04-LTS",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.PremiumLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
LinuxConfiguration = new LinuxConfiguration()
{
ProvisionVmAgent = true,
PatchSettings = new LinuxPatchSettings()
{
PatchMode = LinuxVmGuestPatchMode.ImageDefault,
},
},
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"provisionVMAgent": true,
"patchSettings": {
"patchMode": "ImageDefault"
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"osType": "Linux",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Premium_LRS"
}
},
"dataDisks": []
},
"vmId": "a149cd25-409f-41af-8088-275f5486bc93",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"provisionVMAgent": true,
"patchSettings": {
"patchMode": "ImageDefault"
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"osType": "Linux",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Premium_LRS"
}
},
"dataDisks": []
},
"vmId": "a149cd25-409f-41af-8088-275f5486bc93",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Premium_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}",
"linuxConfiguration": {
"provisionVMAgent": true,
"patchSettings": {
"patchMode": "AutomaticByPlatform",
"assessmentMode": "AutomaticByPlatform"
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.LinuxConfiguration;
import com.azure.resourcemanager.compute.models.LinuxPatchAssessmentMode;
import com.azure.resourcemanager.compute.models.LinuxPatchSettings;
import com.azure.resourcemanager.compute.models.LinuxVMGuestPatchMode;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingModesOfAutomaticByPlatform.json
*/
/**
* Sample code: Create a Linux vm with a patch settings patchMode and assessmentMode set to AutomaticByPlatform.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createALinuxVmWithAPatchSettingsPatchModeAndAssessmentModeSetToAutomaticByPlatform(
com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D2S_V3))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer")
.withSku("16.04-LTS").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.PREMIUM_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder")
.withLinuxConfiguration(new LinuxConfiguration().withProvisionVMAgent(true).withPatchSettings(
new LinuxPatchSettings().withPatchMode(LinuxVMGuestPatchMode.AUTOMATIC_BY_PLATFORM)
.withAssessmentMode(LinuxPatchAssessmentMode.AUTOMATIC_BY_PLATFORM))))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_linux_vm_with_patch_setting_modes_of_automatic_by_platform.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
"linuxConfiguration": {
"patchSettings": {"assessmentMode": "AutomaticByPlatform", "patchMode": "AutomaticByPlatform"},
"provisionVMAgent": True,
},
},
"storageProfile": {
"imageReference": {
"offer": "UbuntuServer",
"publisher": "Canonical",
"sku": "16.04-LTS",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Premium_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingModesOfAutomaticByPlatform.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingModesOfAutomaticByPlatform.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createALinuxVmWithAPatchSettingsPatchModeAndAssessmentModeSetToAutomaticByPlatform() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
LinuxConfiguration: &armcompute.LinuxConfiguration{
PatchSettings: &armcompute.LinuxPatchSettings{
AssessmentMode: to.Ptr(armcompute.LinuxPatchAssessmentModeAutomaticByPlatform),
PatchMode: to.Ptr(armcompute.LinuxVMGuestPatchModeAutomaticByPlatform),
},
ProvisionVMAgent: to.Ptr(true),
},
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("UbuntuServer"),
Publisher: to.Ptr("Canonical"),
SKU: to.Ptr("16.04-LTS"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesPremiumLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// LinuxConfiguration: &armcompute.LinuxConfiguration{
// PatchSettings: &armcompute.LinuxPatchSettings{
// AssessmentMode: to.Ptr(armcompute.LinuxPatchAssessmentModeAutomaticByPlatform),
// PatchMode: to.Ptr(armcompute.LinuxVMGuestPatchModeAutomaticByPlatform),
// },
// ProvisionVMAgent: to.Ptr(true),
// },
// Secrets: []*armcompute.VaultSecretGroup{
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("UbuntuServer"),
// Publisher: to.Ptr("Canonical"),
// SKU: to.Ptr("16.04-LTS"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesPremiumLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesLinux),
// },
// },
// VMID: to.Ptr("a149cd25-409f-41af-8088-275f5486bc93"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingModesOfAutomaticByPlatform.json
*/
async function createALinuxVMWithAPatchSettingsPatchModeAndAssessmentModeSetToAutomaticByPlatform() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D2s_v3" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
linuxConfiguration: {
patchSettings: {
assessmentMode: "AutomaticByPlatform",
patchMode: "AutomaticByPlatform",
},
provisionVMAgent: true,
},
},
storageProfile: {
imageReference: {
offer: "UbuntuServer",
publisher: "Canonical",
sku: "16.04-LTS",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Premium_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_LinuxVmWithPatchSettingModesOfAutomaticByPlatform.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD2SV3,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "Canonical",
Offer = "UbuntuServer",
Sku = "16.04-LTS",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.PremiumLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
LinuxConfiguration = new LinuxConfiguration()
{
ProvisionVmAgent = true,
PatchSettings = new LinuxPatchSettings()
{
PatchMode = LinuxVmGuestPatchMode.AutomaticByPlatform,
AssessmentMode = LinuxPatchAssessmentMode.AutomaticByPlatform,
},
},
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"provisionVMAgent": true,
"patchSettings": {
"patchMode": "AutomaticByPlatform",
"assessmentMode": "AutomaticByPlatform"
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"osType": "Linux",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Premium_LRS"
}
},
"dataDisks": []
},
"vmId": "a149cd25-409f-41af-8088-275f5486bc93",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"provisionVMAgent": true,
"patchSettings": {
"patchMode": "AutomaticByPlatform",
"assessmentMode": "AutomaticByPlatform"
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"osType": "Linux",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Premium_LRS"
}
},
"dataDisks": []
},
"vmId": "a149cd25-409f-41af-8088-275f5486bc93",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/{vm-name}?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D2_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": [
{
"diskSizeGB": 1023,
"createOption": "Empty",
"lun": 0,
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk0.vhd"
}
},
{
"diskSizeGB": 1023,
"createOption": "Empty",
"lun": 1,
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk1.vhd"
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DataDisk;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualHardDisk;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_PlatformImageVmWithUnmanagedOsAndDataDisks.json
*/
/**
* Sample code: Create a platform-image vm with unmanaged os and data disks.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void
createAPlatformImageVmWithUnmanagedOsAndDataDisks(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines()
.createOrUpdate("myResourceGroup", "{vm-name}", new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D2_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withVhd(new VirtualHardDisk().withUri(
"http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd"))
.withCaching(CachingTypes.READ_WRITE).withCreateOption(DiskCreateOptionTypes.FROM_IMAGE))
.withDataDisks(Arrays.asList(new DataDisk().withLun(0).withVhd(new VirtualHardDisk().withUri(
"http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk0.vhd"))
.withCreateOption(DiskCreateOptionTypes.EMPTY).withDiskSizeGB(1023),
new DataDisk().withLun(1).withVhd(new VirtualHardDisk().withUri(
"http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk1.vhd"))
.withCreateOption(DiskCreateOptionTypes.EMPTY).withDiskSizeGB(1023))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_platform_image_vm_with_unmanaged_os_and_data_disks.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="{vm-name}",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"dataDisks": [
{
"createOption": "Empty",
"diskSizeGB": 1023,
"lun": 0,
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk0.vhd"
},
},
{
"createOption": "Empty",
"diskSizeGB": 1023,
"lun": 1,
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk1.vhd"
},
},
],
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd"
},
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_PlatformImageVmWithUnmanagedOsAndDataDisks.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_PlatformImageVmWithUnmanagedOsAndDataDisks.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAPlatformImageVmWithUnmanagedOsAndDataDisks() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "{vm-name}", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
DataDisks: []*armcompute.DataDisk{
{
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesEmpty),
DiskSizeGB: to.Ptr[int32](1023),
Lun: to.Ptr[int32](0),
Vhd: &armcompute.VirtualHardDisk{
URI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk0.vhd"),
},
},
{
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesEmpty),
DiskSizeGB: to.Ptr[int32](1023),
Lun: to.Ptr[int32](1),
Vhd: &armcompute.VirtualHardDisk{
URI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk1.vhd"),
},
}},
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
Vhd: &armcompute.VirtualHardDisk{
URI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd"),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// {
// Name: to.Ptr("dataDisk0"),
// Caching: to.Ptr(armcompute.CachingTypesNone),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesEmpty),
// DiskSizeGB: to.Ptr[int32](1023),
// Lun: to.Ptr[int32](0),
// Vhd: &armcompute.VirtualHardDisk{
// URI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net/vhds/myDisk0.vhd"),
// },
// },
// {
// Name: to.Ptr("dataDisk1"),
// Caching: to.Ptr(armcompute.CachingTypesNone),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesEmpty),
// DiskSizeGB: to.Ptr[int32](1023),
// Lun: to.Ptr[int32](1),
// Vhd: &armcompute.VirtualHardDisk{
// URI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net/vhds/myDisk1.vhd"),
// },
// }},
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// Vhd: &armcompute.VirtualHardDisk{
// URI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net/vhds/myDisk.vhd"),
// },
// },
// },
// VMID: to.Ptr("5230a749-2f68-4830-900b-702182d32e63"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_PlatformImageVmWithUnmanagedOsAndDataDisks.json
*/
async function createAPlatformImageVMWithUnmanagedOSAndDataDisks() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "{vm-name}";
const parameters = {
hardwareProfile: { vmSize: "Standard_D2_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
dataDisks: [
{
createOption: "Empty",
diskSizeGB: 1023,
lun: 0,
vhd: {
uri: "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk0.vhd",
},
},
{
createOption: "Empty",
diskSizeGB: 1023,
lun: 1,
vhd: {
uri: "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk1.vhd",
},
},
],
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
vhd: {
uri: "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd",
},
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_PlatformImageVmWithUnmanagedOsAndDataDisks.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "{vm-name}";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD2V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
VhdUri = new Uri("http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd"),
Caching = CachingType.ReadWrite,
},
DataDisks =
{
new VirtualMachineDataDisk(0,DiskCreateOptionType.Empty)
{
VhdUri = new Uri("http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk0.vhd"),
DiskSizeGB = 1023,
},new VirtualMachineDataDisk(1,DiskCreateOptionType.Empty)
{
VhdUri = new Uri("http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk1.vhd"),
DiskSizeGB = 1023,
}
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/vhds/myDisk.vhd"
},
"createOption": "FromImage",
"name": "myVMosdisk",
"caching": "ReadWrite"
},
"dataDisks": [
{
"name": "dataDisk0",
"diskSizeGB": 1023,
"createOption": "Empty",
"caching": "None",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/vhds/myDisk0.vhd"
},
"lun": 0
},
{
"name": "dataDisk1",
"diskSizeGB": 1023,
"createOption": "Empty",
"caching": "None",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/vhds/myDisk1.vhd"
},
"lun": 1
}
]
},
"vmId": "5230a749-2f68-4830-900b-702182d32e63",
"hardwareProfile": {
"vmSize": "Standard_D2_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/vhds/myDisk.vhd"
},
"createOption": "FromImage",
"name": "myVMosdisk",
"caching": "ReadWrite"
},
"dataDisks": [
{
"name": "dataDisk0",
"diskSizeGB": 1023,
"createOption": "Empty",
"caching": "None",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/vhds/myDisk0.vhd"
},
"lun": 0
},
{
"name": "dataDisk1",
"diskSizeGB": 1023,
"createOption": "Empty",
"caching": "None",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/vhds/myDisk1.vhd"
},
"lun": 1
}
]
},
"vmId": "5230a749-2f68-4830-900b-702182d32e63",
"hardwareProfile": {
"vmSize": "Standard_D2_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"communityGalleryImageId": "/CommunityGalleries/galleryPublicName/Images/communityGalleryImageName/Versions/communityGalleryImageVersionName"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_FromACommunityGalleryImage.json
*/
/**
* Sample code: Create a VM from a community gallery image.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVMFromACommunityGalleryImage(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withCommunityGalleryImageId(
"/CommunityGalleries/galleryPublicName/Images/communityGalleryImageName/Versions/communityGalleryImageVersionName"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_from_acommunity_gallery_image.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"communityGalleryImageId": "/CommunityGalleries/galleryPublicName/Images/communityGalleryImageName/Versions/communityGalleryImageVersionName"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromACommunityGalleryImage.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromACommunityGalleryImage.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmFromACommunityGalleryImage() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
CommunityGalleryImageID: to.Ptr("/CommunityGalleries/galleryPublicName/Images/communityGalleryImageName/Versions/communityGalleryImageVersionName"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// LinuxConfiguration: &armcompute.LinuxConfiguration{
// DisablePasswordAuthentication: to.Ptr(false),
// },
// Secrets: []*armcompute.VaultSecretGroup{
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// CommunityGalleryImageID: to.Ptr("/CommunityGalleries/galleryPublicName/Images/communityGalleryImageName/Versions/communityGalleryImageVersionName"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// DiskSizeGB: to.Ptr[int32](30),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesLinux),
// },
// },
// VMID: to.Ptr("71aa3d5a-d73d-4970-9182-8580433b2865"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromACommunityGalleryImage.json
*/
async function createAVMFromACommunityGalleryImage() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
imageReference: {
communityGalleryImageId:
"/CommunityGalleries/galleryPublicName/Images/communityGalleryImageName/Versions/communityGalleryImageVersionName",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromACommunityGalleryImage.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
CommunityGalleryImageId = "/CommunityGalleries/galleryPublicName/Images/communityGalleryImageName/Versions/communityGalleryImageVersionName",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"disablePasswordAuthentication": false
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"communityGalleryImageId": "/CommunityGalleries/galleryPublicName/Images/communityGalleryImageName/Versions/communityGalleryImageVersionName"
},
"osDisk": {
"name": "myVMosdisk",
"diskSizeGB": 30,
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Linux"
},
"dataDisks": []
},
"vmId": "71aa3d5a-d73d-4970-9182-8580433b2865",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"disablePasswordAuthentication": false
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"communityGalleryImageId": "/CommunityGalleries/galleryPublicName/Images/communityGalleryImageName/Versions/communityGalleryImageVersionName"
},
"osDisk": {
"name": "myVMosdisk",
"diskSizeGB": 30,
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Linux"
},
"dataDisks": []
},
"vmId": "71aa3d5a-d73d-4970-9182-8580433b2865",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a vm from a custom image.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_FromACustomImage.json
*/
/**
* Sample code: Create a vm from a custom image.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmFromACustomImage(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile().withImageReference(new ImageReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_from_acustom_image.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromACustomImage.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromACustomImage.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmFromACustomImage() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// LinuxConfiguration: &armcompute.LinuxConfiguration{
// DisablePasswordAuthentication: to.Ptr(false),
// },
// Secrets: []*armcompute.VaultSecretGroup{
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/nsgcustom"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// DiskSizeGB: to.Ptr[int32](30),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesLinux),
// },
// },
// VMID: to.Ptr("71aa3d5a-d73d-4970-9182-8580433b2865"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromACustomImage.json
*/
async function createAVMFromACustomImage() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
imageReference: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromACustomImage.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}"),
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"disablePasswordAuthentication": false
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/nsgcustom"
},
"osDisk": {
"name": "myVMosdisk",
"diskSizeGB": 30,
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Linux"
},
"dataDisks": []
},
"vmId": "71aa3d5a-d73d-4970-9182-8580433b2865",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"disablePasswordAuthentication": false
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/nsgcustom"
},
"osDisk": {
"name": "myVMosdisk",
"diskSizeGB": 30,
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Linux"
},
"dataDisks": []
},
"vmId": "71aa3d5a-d73d-4970-9182-8580433b2865",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a vm from a generalized shared image.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_FromAGeneralizedSharedImage.json
*/
/**
* Sample code: Create a vm from a generalized shared image.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmFromAGeneralizedSharedImage(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile().withImageReference(new ImageReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_from_ageneralized_shared_image.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromAGeneralizedSharedImage.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromAGeneralizedSharedImage.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmFromAGeneralizedSharedImage() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// LinuxConfiguration: &armcompute.LinuxConfiguration{
// DisablePasswordAuthentication: to.Ptr(false),
// },
// Secrets: []*armcompute.VaultSecretGroup{
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// DiskSizeGB: to.Ptr[int32](30),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesLinux),
// },
// },
// VMID: to.Ptr("71aa3d5a-d73d-4970-9182-8580433b2865"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromAGeneralizedSharedImage.json
*/
async function createAVMFromAGeneralizedSharedImage() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
imageReference: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromAGeneralizedSharedImage.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"),
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"disablePasswordAuthentication": false
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"
},
"osDisk": {
"name": "myVMosdisk",
"diskSizeGB": 30,
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Linux"
},
"dataDisks": []
},
"vmId": "71aa3d5a-d73d-4970-9182-8580433b2865",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"disablePasswordAuthentication": false
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"
},
"osDisk": {
"name": "myVMosdisk",
"diskSizeGB": 30,
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Linux"
},
"dataDisks": []
},
"vmId": "71aa3d5a-d73d-4970-9182-8580433b2865",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a VM from a shared gallery image
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sharedGalleryImageId": "/SharedGalleries/sharedGalleryName/Images/sharedGalleryImageName/Versions/sharedGalleryImageVersionName"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_FromASharedGalleryImage.json
*/
/**
* Sample code: Create a VM from a shared gallery image.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVMFromASharedGalleryImage(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withSharedGalleryImageId(
"/SharedGalleries/sharedGalleryName/Images/sharedGalleryImageName/Versions/sharedGalleryImageVersionName"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_from_ashared_gallery_image.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"sharedGalleryImageId": "/SharedGalleries/sharedGalleryName/Images/sharedGalleryImageName/Versions/sharedGalleryImageVersionName"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromASharedGalleryImage.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromASharedGalleryImage.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmFromASharedGalleryImage() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
SharedGalleryImageID: to.Ptr("/SharedGalleries/sharedGalleryName/Images/sharedGalleryImageName/Versions/sharedGalleryImageVersionName"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// LinuxConfiguration: &armcompute.LinuxConfiguration{
// DisablePasswordAuthentication: to.Ptr(false),
// },
// Secrets: []*armcompute.VaultSecretGroup{
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// SharedGalleryImageID: to.Ptr("/SharedGalleries/sharedGalleryName/Images/sharedGalleryImageName/Versions/sharedGalleryImageVersionName"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// DiskSizeGB: to.Ptr[int32](30),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesLinux),
// },
// },
// VMID: to.Ptr("71aa3d5a-d73d-4970-9182-8580433b2865"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromASharedGalleryImage.json
*/
async function createAVMFromASharedGalleryImage() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
imageReference: {
sharedGalleryImageId:
"/SharedGalleries/sharedGalleryName/Images/sharedGalleryImageName/Versions/sharedGalleryImageVersionName",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromASharedGalleryImage.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
SharedGalleryImageUniqueId = "/SharedGalleries/sharedGalleryName/Images/sharedGalleryImageName/Versions/sharedGalleryImageVersionName",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"disablePasswordAuthentication": false
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sharedGalleryImageId": "/SharedGalleries/sharedGalleryName/Images/sharedGalleryImageName/Versions/sharedGalleryImageVersionName"
},
"osDisk": {
"name": "myVMosdisk",
"diskSizeGB": 30,
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Linux"
},
"dataDisks": []
},
"vmId": "71aa3d5a-d73d-4970-9182-8580433b2865",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"disablePasswordAuthentication": false
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sharedGalleryImageId": "/SharedGalleries/sharedGalleryName/Images/sharedGalleryImageName/Versions/sharedGalleryImageVersionName"
},
"osDisk": {
"name": "myVMosdisk",
"diskSizeGB": 30,
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Linux"
},
"dataDisks": []
},
"vmId": "71aa3d5a-d73d-4970-9182-8580433b2865",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a vm from a specialized shared image.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_FromASpecializedSharedImage.json
*/
/**
* Sample code: Create a vm from a specialized shared image.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmFromASpecializedSharedImage(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile().withImageReference(new ImageReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_from_aspecialized_shared_image.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromASpecializedSharedImage.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromASpecializedSharedImage.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmFromASpecializedSharedImage() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// DiskSizeGB: to.Ptr[int32](30),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesLinux),
// },
// },
// VMID: to.Ptr("71aa3d5a-d73d-4970-9182-8580433b2865"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromASpecializedSharedImage.json
*/
async function createAVMFromASpecializedSharedImage() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
storageProfile: {
imageReference: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_FromASpecializedSharedImage.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"),
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"
},
"osDisk": {
"name": "myVMosdisk",
"diskSizeGB": 30,
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Linux"
},
"dataDisks": []
},
"vmId": "71aa3d5a-d73d-4970-9182-8580433b2865",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"
},
"osDisk": {
"name": "myVMosdisk",
"diskSizeGB": 30,
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Linux"
},
"dataDisks": []
},
"vmId": "71aa3d5a-d73d-4970-9182-8580433b2865",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a vm in a Virtual Machine Scale Set with customer assigned platformFaultDomain.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"virtualMachineScaleSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/{existing-flex-vmss-name-with-platformFaultDomainCount-greater-than-1}"
},
"platformFaultDomain": 1
}
}
import com.azure.core.management.SubResource;
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_InAVmssWithCustomerAssignedPlatformFaultDomain.json
*/
/**
* Sample code: Create a vm in a Virtual Machine Scale Set with customer assigned platformFaultDomain.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmInAVirtualMachineScaleSetWithCustomerAssignedPlatformFaultDomain(
com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true))))
.withVirtualMachineScaleSet(new SubResource().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/{existing-flex-vmss-name-with-platformFaultDomainCount-greater-than-1}"))
.withPlatformFaultDomain(1),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_in_avmss_with_customer_assigned_platform_fault_domain.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"platformFaultDomain": 1,
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
"virtualMachineScaleSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/{existing-flex-vmss-name-with-platformFaultDomainCount-greater-than-1}"
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_InAVmssWithCustomerAssignedPlatformFaultDomain.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_InAVmssWithCustomerAssignedPlatformFaultDomain.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmInAVirtualMachineScaleSetWithCustomerAssignedPlatformFaultDomain() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
PlatformFaultDomain: to.Ptr[int32](1),
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
VirtualMachineScaleSet: &armcompute.SubResource{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/{existing-flex-vmss-name-with-platformFaultDomainCount-greater-than-1}"),
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// PlatformFaultDomain: to.Ptr[int32](1),
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VirtualMachineScaleSet: &armcompute.SubResource{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/myExistingFlexVmss"),
// },
// VMID: to.Ptr("7cce54f2-ecd3-4ddd-a8d9-50984faa3918"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_InAVmssWithCustomerAssignedPlatformFaultDomain.json
*/
async function createAVMInAVirtualMachineScaleSetWithCustomerAssignedPlatformFaultDomain() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
platformFaultDomain: 1,
storageProfile: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
virtualMachineScaleSet: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/{existing-flex-vmss-name-with-platformFaultDomainCount-greater-than-1}",
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_InAVmssWithCustomerAssignedPlatformFaultDomain.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
VirtualMachineScaleSetId = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/{existing-flex-vmss-name-with-platformFaultDomainCount-greater-than-1}"),
PlatformFaultDomain = 1,
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"vmId": "7cce54f2-ecd3-4ddd-a8d9-50984faa3918",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"virtualMachineScaleSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/myExistingFlexVmss"
},
"platformFaultDomain": 1,
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"vmId": "7cce54f2-ecd3-4ddd-a8d9-50984faa3918",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"virtualMachineScaleSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/myExistingFlexVmss"
},
"platformFaultDomain": 1,
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a vm in an availability set.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"availabilitySet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/{existing-availability-set-name}"
}
}
}
import com.azure.core.management.SubResource;
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_InAnAvailabilitySet.json
*/
/**
* Sample code: Create a vm in an availability set.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmInAnAvailabilitySet(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true))))
.withAvailabilitySet(new SubResource().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/{existing-availability-set-name}")),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_in_an_availability_set.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"availabilitySet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/{existing-availability-set-name}"
},
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_InAnAvailabilitySet.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_InAnAvailabilitySet.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmInAnAvailabilitySet() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
AvailabilitySet: &armcompute.SubResource{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/{existing-availability-set-name}"),
},
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// AvailabilitySet: &armcompute.SubResource{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/NSGEXISTINGAS"),
// },
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("b7a098cc-b0b8-46e8-a205-62f301a62a8f"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_InAnAvailabilitySet.json
*/
async function createAVMInAnAvailabilitySet() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
availabilitySet: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/{existing-availability-set-name}",
},
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_InAnAvailabilitySet.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
AvailabilitySetId = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/{existing-availability-set-name}"),
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"vmId": "b7a098cc-b0b8-46e8-a205-62f301a62a8f",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"availabilitySet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/NSGEXISTINGAS"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"vmId": "b7a098cc-b0b8-46e8-a205-62f301a62a8f",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"availabilitySet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/NSGEXISTINGAS"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a vm with a marketplace image plan.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"plan": {
"publisher": "microsoft-ads",
"product": "windows-data-science-vm",
"name": "windows2016"
},
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "windows2016",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "windows-data-science-vm"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.Plan;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithAMarketplaceImagePlan.json
*/
/**
* Sample code: Create a vm with a marketplace image plan.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithAMarketplaceImagePlan(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withPlan(new Plan().withName("windows2016").withPublisher("microsoft-ads")
.withProduct("windows-data-science-vm"))
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("microsoft-ads")
.withOffer("windows-data-science-vm").withSku("windows2016").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_amarketplace_image_plan.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"plan": {"name": "windows2016", "product": "windows-data-science-vm", "publisher": "microsoft-ads"},
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "windows-data-science-vm",
"publisher": "microsoft-ads",
"sku": "windows2016",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithAMarketplaceImagePlan.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithAMarketplaceImagePlan.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithAMarketplaceImagePlan() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Plan: &armcompute.Plan{
Name: to.Ptr("windows2016"),
Product: to.Ptr("windows-data-science-vm"),
Publisher: to.Ptr("microsoft-ads"),
},
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("windows-data-science-vm"),
Publisher: to.Ptr("microsoft-ads"),
SKU: to.Ptr("windows2016"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Plan: &armcompute.Plan{
// Name: to.Ptr("standard-data-science-vm"),
// Product: to.Ptr("standard-data-science-vm"),
// Publisher: to.Ptr("microsoft-ads"),
// },
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("standard-data-science-vm"),
// Publisher: to.Ptr("microsoft-ads"),
// SKU: to.Ptr("standard-data-science-vm"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("5c0d55a7-c407-4ed6-bf7d-ddb810267c85"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithAMarketplaceImagePlan.json
*/
async function createAVMWithAMarketplaceImagePlan() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
plan: {
name: "windows2016",
product: "windows-data-science-vm",
publisher: "microsoft-ads",
},
storageProfile: {
imageReference: {
offer: "windows-data-science-vm",
publisher: "microsoft-ads",
sku: "windows2016",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithAMarketplaceImagePlan.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
Plan = new ComputePlan()
{
Name = "windows2016",
Publisher = "microsoft-ads",
Product = "windows-data-science-vm",
},
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "microsoft-ads",
Offer = "windows-data-science-vm",
Sku = "windows2016",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "standard-data-science-vm",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "standard-data-science-vm"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"plan": {
"publisher": "microsoft-ads",
"product": "standard-data-science-vm",
"name": "standard-data-science-vm"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "standard-data-science-vm",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "standard-data-science-vm"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"plan": {
"publisher": "microsoft-ads",
"product": "standard-data-science-vm",
"name": "standard-data-science-vm"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
Create a vm with an extensions time budget.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
"enabled": true
}
},
"extensionsTimeBudget": "PT30M"
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.BootDiagnostics;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiagnosticsProfile;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithExtensionsTimeBudget.json
*/
/**
* Sample code: Create a vm with an extensions time budget.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithAnExtensionsTimeBudget(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true))))
.withDiagnosticsProfile(new DiagnosticsProfile().withBootDiagnostics(new BootDiagnostics()
.withEnabled(true).withStorageUri("http://{existing-storage-account-name}.blob.core.windows.net")))
.withExtensionsTimeBudget("PT30M"),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_extensions_time_budget.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": True,
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
}
},
"extensionsTimeBudget": "PT30M",
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithExtensionsTimeBudget.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithExtensionsTimeBudget.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithAnExtensionsTimeBudget() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
DiagnosticsProfile: &armcompute.DiagnosticsProfile{
BootDiagnostics: &armcompute.BootDiagnostics{
Enabled: to.Ptr(true),
StorageURI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net"),
},
},
ExtensionsTimeBudget: to.Ptr("PT30M"),
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// DiagnosticsProfile: &armcompute.DiagnosticsProfile{
// BootDiagnostics: &armcompute.BootDiagnostics{
// Enabled: to.Ptr(true),
// StorageURI: to.Ptr("http://nsgdiagnostic.blob.core.windows.net"),
// },
// },
// ExtensionsTimeBudget: to.Ptr("PT30M"),
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("676420ba-7a24-4bfe-80bd-9c841ee184fa"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithExtensionsTimeBudget.json
*/
async function createAVMWithAnExtensionsTimeBudget() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
diagnosticsProfile: {
bootDiagnostics: {
enabled: true,
storageUri: "http://{existing-storage-account-name}.blob.core.windows.net",
},
},
extensionsTimeBudget: "PT30M",
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithExtensionsTimeBudget.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
BootDiagnostics = new BootDiagnostics()
{
Enabled = true,
StorageUri = new Uri("http://{existing-storage-account-name}.blob.core.windows.net"),
},
ExtensionsTimeBudget = "PT30M",
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://nsgdiagnostic.blob.core.windows.net",
"enabled": true
}
},
"vmId": "676420ba-7a24-4bfe-80bd-9c841ee184fa",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"extensionsTimeBudget": "PT30M",
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://nsgdiagnostic.blob.core.windows.net",
"enabled": true
}
},
"vmId": "676420ba-7a24-4bfe-80bd-9c841ee184fa",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"extensionsTimeBudget": "PT30M",
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a vm with Application Profile.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "{image_sku}",
"publisher": "{image_publisher}",
"version": "latest",
"offer": "{image_offer}"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"applicationProfile": {
"galleryApplications": [
{
"tags": "myTag1",
"order": 1,
"packageReferenceId": "/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdb/resourceGroups/myresourceGroupName2/providers/Microsoft.Compute/galleries/myGallery1/applications/MyApplication1/versions/1.0",
"configurationReference": "https://mystorageaccount.blob.core.windows.net/configurations/settings.config",
"treatFailureAsDeploymentFailure": false,
"enableAutomaticUpgrade": false
},
{
"packageReferenceId": "/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdg/resourceGroups/myresourceGroupName3/providers/Microsoft.Compute/galleries/myGallery2/applications/MyApplication2/versions/1.1"
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.ApplicationProfile;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VMGalleryApplication;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithApplicationProfile.json
*/
/**
* Sample code: Create a vm with Application Profile.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithApplicationProfile(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("{image_publisher}")
.withOffer("{image_offer}").withSku("{image_sku}").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true))))
.withApplicationProfile(new ApplicationProfile().withGalleryApplications(Arrays.asList(
new VMGalleryApplication().withTags("myTag1").withOrder(1).withPackageReferenceId(
"/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdb/resourceGroups/myresourceGroupName2/providers/Microsoft.Compute/galleries/myGallery1/applications/MyApplication1/versions/1.0")
.withConfigurationReference(
"https://mystorageaccount.blob.core.windows.net/configurations/settings.config")
.withTreatFailureAsDeploymentFailure(false).withEnableAutomaticUpgrade(false),
new VMGalleryApplication().withPackageReferenceId(
"/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdg/resourceGroups/myresourceGroupName3/providers/Microsoft.Compute/galleries/myGallery2/applications/MyApplication2/versions/1.1")))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_application_profile.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"applicationProfile": {
"galleryApplications": [
{
"configurationReference": "https://mystorageaccount.blob.core.windows.net/configurations/settings.config",
"enableAutomaticUpgrade": False,
"order": 1,
"packageReferenceId": "/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdb/resourceGroups/myresourceGroupName2/providers/Microsoft.Compute/galleries/myGallery1/applications/MyApplication1/versions/1.0",
"tags": "myTag1",
"treatFailureAsDeploymentFailure": False,
},
{
"packageReferenceId": "/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdg/resourceGroups/myresourceGroupName3/providers/Microsoft.Compute/galleries/myGallery2/applications/MyApplication2/versions/1.1"
},
]
},
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "{image_offer}",
"publisher": "{image_publisher}",
"sku": "{image_sku}",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithApplicationProfile.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithApplicationProfile.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithApplicationProfile() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
ApplicationProfile: &armcompute.ApplicationProfile{
GalleryApplications: []*armcompute.VMGalleryApplication{
{
ConfigurationReference: to.Ptr("https://mystorageaccount.blob.core.windows.net/configurations/settings.config"),
EnableAutomaticUpgrade: to.Ptr(false),
Order: to.Ptr[int32](1),
PackageReferenceID: to.Ptr("/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdb/resourceGroups/myresourceGroupName2/providers/Microsoft.Compute/galleries/myGallery1/applications/MyApplication1/versions/1.0"),
Tags: to.Ptr("myTag1"),
TreatFailureAsDeploymentFailure: to.Ptr(false),
},
{
PackageReferenceID: to.Ptr("/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdg/resourceGroups/myresourceGroupName3/providers/Microsoft.Compute/galleries/myGallery2/applications/MyApplication2/versions/1.1"),
}},
},
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("{image_offer}"),
Publisher: to.Ptr("{image_publisher}"),
SKU: to.Ptr("{image_sku}"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// ApplicationProfile: &armcompute.ApplicationProfile{
// GalleryApplications: []*armcompute.VMGalleryApplication{
// {
// ConfigurationReference: to.Ptr("https://mystorageaccount.blob.core.windows.net/configurations/settings.config"),
// Order: to.Ptr[int32](1),
// PackageReferenceID: to.Ptr("/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdb/resourceGroups/myresourceGroupName2/providers/Microsoft.Compute/galleries/myGallery1/applications/MyApplication1/versions/1.0"),
// Tags: to.Ptr("myTag1"),
// },
// {
// PackageReferenceID: to.Ptr("/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdg/resourceGroups/myresourceGroupName3/providers/Microsoft.Compute/galleries/myGallery2/applications/MyApplication2/versions/1.1"),
// }},
// },
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// LinuxConfiguration: &armcompute.LinuxConfiguration{
// DisablePasswordAuthentication: to.Ptr(true),
// SSH: &armcompute.SSHConfiguration{
// PublicKeys: []*armcompute.SSHPublicKey{
// {
// Path: to.Ptr("/home/{your-username}/.ssh/authorized_keys"),
// KeyData: to.Ptr("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCeClRAk2ipUs/l5voIsDC5q9RI+YSRd1Bvd/O+axgY4WiBzG+4FwJWZm/mLLe5DoOdHQwmU2FrKXZSW4w2sYE70KeWnrFViCOX5MTVvJgPE8ClugNl8RWth/tU849DvM9sT7vFgfVSHcAS2yDRyDlueii+8nF2ym8XWAPltFVCyLHRsyBp5YPqK8JFYIa1eybKsY3hEAxRCA+/7bq8et+Gj3coOsuRmrehav7rE6N12Pb80I6ofa6SM5XNYq4Xk0iYNx7R3kdz0Jj9XgZYWjAHjJmT0gTRoOnt6upOuxK7xI/ykWrllgpXrCPu3Ymz+c+ujaqcxDopnAl2lmf69/J1"),
// }},
// },
// },
// Secrets: []*armcompute.VaultSecretGroup{
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("UbuntuServer"),
// Publisher: to.Ptr("Canonical"),
// SKU: to.Ptr("16.04-LTS"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesLinux),
// },
// },
// VMID: to.Ptr("e0de9b84-a506-4b95-9623-00a425d05c90"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithApplicationProfile.json
*/
async function createAVMWithApplicationProfile() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
applicationProfile: {
galleryApplications: [
{
configurationReference:
"https://mystorageaccount.blob.core.windows.net/configurations/settings.config",
enableAutomaticUpgrade: false,
order: 1,
packageReferenceId:
"/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdb/resourceGroups/myresourceGroupName2/providers/Microsoft.Compute/galleries/myGallery1/applications/MyApplication1/versions/1.0",
tags: "myTag1",
treatFailureAsDeploymentFailure: false,
},
{
packageReferenceId:
"/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdg/resourceGroups/myresourceGroupName3/providers/Microsoft.Compute/galleries/myGallery2/applications/MyApplication2/versions/1.1",
},
],
},
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
imageReference: {
offer: "{image_offer}",
publisher: "{image_publisher}",
sku: "{image_sku}",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithApplicationProfile.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "{image_publisher}",
Offer = "{image_offer}",
Sku = "{image_sku}",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
GalleryApplications =
{
new VirtualMachineGalleryApplication("/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdb/resourceGroups/myresourceGroupName2/providers/Microsoft.Compute/galleries/myGallery1/applications/MyApplication1/versions/1.0")
{
Tags = "myTag1",
Order = 1,
ConfigurationReference = "https://mystorageaccount.blob.core.windows.net/configurations/settings.config",
TreatFailureAsDeploymentFailure = false,
EnableAutomaticUpgrade = false,
},new VirtualMachineGalleryApplication("/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdg/resourceGroups/myresourceGroupName3/providers/Microsoft.Compute/galleries/myGallery2/applications/MyApplication2/versions/1.1")
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"ssh": {
"publicKeys": [
{
"path": "/home/{your-username}/.ssh/authorized_keys",
"keyData": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCeClRAk2ipUs/l5voIsDC5q9RI+YSRd1Bvd/O+axgY4WiBzG+4FwJWZm/mLLe5DoOdHQwmU2FrKXZSW4w2sYE70KeWnrFViCOX5MTVvJgPE8ClugNl8RWth/tU849DvM9sT7vFgfVSHcAS2yDRyDlueii+8nF2ym8XWAPltFVCyLHRsyBp5YPqK8JFYIa1eybKsY3hEAxRCA+/7bq8et+Gj3coOsuRmrehav7rE6N12Pb80I6ofa6SM5XNYq4Xk0iYNx7R3kdz0Jj9XgZYWjAHjJmT0gTRoOnt6upOuxK7xI/ykWrllgpXrCPu3Ymz+c+ujaqcxDopnAl2lmf69/J1"
}
]
},
"disablePasswordAuthentication": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"osType": "Linux",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"applicationProfile": {
"galleryApplications": [
{
"tags": "myTag1",
"order": 1,
"packageReferenceId": "/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdb/resourceGroups/myresourceGroupName2/providers/Microsoft.Compute/galleries/myGallery1/applications/MyApplication1/versions/1.0",
"configurationReference": "https://mystorageaccount.blob.core.windows.net/configurations/settings.config"
},
{
"packageReferenceId": "/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdg/resourceGroups/myresourceGroupName3/providers/Microsoft.Compute/galleries/myGallery2/applications/MyApplication2/versions/1.1"
}
]
},
"vmId": "e0de9b84-a506-4b95-9623-00a425d05c90",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"ssh": {
"publicKeys": [
{
"path": "/home/{your-username}/.ssh/authorized_keys",
"keyData": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCeClRAk2ipUs/l5voIsDC5q9RI+YSRd1Bvd/O+axgY4WiBzG+4FwJWZm/mLLe5DoOdHQwmU2FrKXZSW4w2sYE70KeWnrFViCOX5MTVvJgPE8ClugNl8RWth/tU849DvM9sT7vFgfVSHcAS2yDRyDlueii+8nF2ym8XWAPltFVCyLHRsyBp5YPqK8JFYIa1eybKsY3hEAxRCA+/7bq8et+Gj3coOsuRmrehav7rE6N12Pb80I6ofa6SM5XNYq4Xk0iYNx7R3kdz0Jj9XgZYWjAHjJmT0gTRoOnt6upOuxK7xI/ykWrllgpXrCPu3Ymz+c+ujaqcxDopnAl2lmf69/J1"
}
]
},
"disablePasswordAuthentication": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "16.04-LTS",
"publisher": "Canonical",
"version": "latest",
"offer": "UbuntuServer"
},
"osDisk": {
"osType": "Linux",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"applicationProfile": {
"galleryApplications": [
{
"tags": "myTag1",
"order": 1,
"packageReferenceId": "/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdb/resourceGroups/myresourceGroupName2/providers/Microsoft.Compute/galleries/myGallery1/applications/MyApplication1/versions/1.0",
"configurationReference": "https://mystorageaccount.blob.core.windows.net/configurations/settings.config"
},
{
"packageReferenceId": "/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdg/resourceGroups/myresourceGroupName3/providers/Microsoft.Compute/galleries/myGallery2/applications/MyApplication2/versions/1.1"
}
]
},
"vmId": "e0de9b84-a506-4b95-9623-00a425d05c90",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a vm with boot diagnostics.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
"enabled": true
}
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.BootDiagnostics;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiagnosticsProfile;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithBootDiagnostics.json
*/
/**
* Sample code: Create a vm with boot diagnostics.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithBootDiagnostics(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true))))
.withDiagnosticsProfile(new DiagnosticsProfile().withBootDiagnostics(new BootDiagnostics()
.withEnabled(true).withStorageUri("http://{existing-storage-account-name}.blob.core.windows.net"))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_boot_diagnostics.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": True,
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
}
},
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithBootDiagnostics.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithBootDiagnostics.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithBootDiagnostics() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
DiagnosticsProfile: &armcompute.DiagnosticsProfile{
BootDiagnostics: &armcompute.BootDiagnostics{
Enabled: to.Ptr(true),
StorageURI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net"),
},
},
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// DiagnosticsProfile: &armcompute.DiagnosticsProfile{
// BootDiagnostics: &armcompute.BootDiagnostics{
// Enabled: to.Ptr(true),
// StorageURI: to.Ptr("http://nsgdiagnostic.blob.core.windows.net"),
// },
// },
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("676420ba-7a24-4bfe-80bd-9c841ee184fa"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithBootDiagnostics.json
*/
async function createAVMWithBootDiagnostics() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
diagnosticsProfile: {
bootDiagnostics: {
enabled: true,
storageUri: "http://{existing-storage-account-name}.blob.core.windows.net",
},
},
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithBootDiagnostics.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
BootDiagnostics = new BootDiagnostics()
{
Enabled = true,
StorageUri = new Uri("http://{existing-storage-account-name}.blob.core.windows.net"),
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://nsgdiagnostic.blob.core.windows.net",
"enabled": true
}
},
"vmId": "676420ba-7a24-4bfe-80bd-9c841ee184fa",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://nsgdiagnostic.blob.core.windows.net",
"enabled": true
}
},
"vmId": "676420ba-7a24-4bfe-80bd-9c841ee184fa",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a vm with data disks using 'Copy' and 'Restore' options.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D2_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
},
"dataDisks": [
{
"diskSizeGB": 1023,
"createOption": "Copy",
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/{existing-snapshot-name}"
},
"lun": 0
},
{
"diskSizeGB": 1023,
"createOption": "Copy",
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-disk-name}"
},
"lun": 1
},
{
"diskSizeGB": 1023,
"createOption": "Restore",
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/restorePointCollections/{existing-rpc-name}/restorePoints/{existing-rp-name}/diskRestorePoints/{existing-disk-restore-point-name}"
},
"lun": 2
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.ApiEntityReference;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DataDisk;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithDataDisksFromSourceResource.json
*/
/**
* Sample code: Create a vm with data disks using 'Copy' and 'Restore' options.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void
createAVmWithDataDisksUsingCopyAndRestoreOptions(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D2_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS)))
.withDataDisks(Arrays.asList(new DataDisk().withLun(0).withCreateOption(DiskCreateOptionTypes.COPY)
.withDiskSizeGB(1023)
.withSourceResource(new ApiEntityReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/{existing-snapshot-name}")),
new DataDisk().withLun(1).withCreateOption(DiskCreateOptionTypes.COPY).withDiskSizeGB(1023)
.withSourceResource(new ApiEntityReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-disk-name}")),
new DataDisk().withLun(2).withCreateOption(DiskCreateOptionTypes.RESTORE).withDiskSizeGB(1023)
.withSourceResource(new ApiEntityReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/restorePointCollections/{existing-rpc-name}/restorePoints/{existing-rp-name}/diskRestorePoints/{existing-disk-restore-point-name}")))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_data_disks_from_source_resource.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"dataDisks": [
{
"createOption": "Copy",
"diskSizeGB": 1023,
"lun": 0,
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/{existing-snapshot-name}"
},
},
{
"createOption": "Copy",
"diskSizeGB": 1023,
"lun": 1,
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-disk-name}"
},
},
{
"createOption": "Restore",
"diskSizeGB": 1023,
"lun": 2,
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/restorePointCollections/{existing-rpc-name}/restorePoints/{existing-rp-name}/diskRestorePoints/{existing-disk-restore-point-name}"
},
},
],
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithDataDisksFromSourceResource.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithDataDisksFromSourceResource.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithDataDisksUsingCopyAndRestoreOptions() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
DataDisks: []*armcompute.DataDisk{
{
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesCopy),
DiskSizeGB: to.Ptr[int32](1023),
Lun: to.Ptr[int32](0),
SourceResource: &armcompute.APIEntityReference{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/{existing-snapshot-name}"),
},
},
{
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesCopy),
DiskSizeGB: to.Ptr[int32](1023),
Lun: to.Ptr[int32](1),
SourceResource: &armcompute.APIEntityReference{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-disk-name}"),
},
},
{
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesRestore),
DiskSizeGB: to.Ptr[int32](1023),
Lun: to.Ptr[int32](2),
SourceResource: &armcompute.APIEntityReference{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/restorePointCollections/{existing-rpc-name}/restorePoints/{existing-rp-name}/diskRestorePoints/{existing-disk-restore-point-name}"),
},
}},
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// {
// Caching: to.Ptr(armcompute.CachingTypesNone),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesCopy),
// DiskSizeGB: to.Ptr[int32](1023),
// Lun: to.Ptr[int32](0),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// SourceResource: &armcompute.APIEntityReference{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/{existing-snapshot-name}"),
// },
// },
// {
// Caching: to.Ptr(armcompute.CachingTypesNone),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesCopy),
// DiskSizeGB: to.Ptr[int32](1023),
// Lun: to.Ptr[int32](1),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// SourceResource: &armcompute.APIEntityReference{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-disk-name}"),
// },
// },
// {
// Caching: to.Ptr(armcompute.CachingTypesNone),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesRestore),
// DiskSizeGB: to.Ptr[int32](1023),
// Lun: to.Ptr[int32](2),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// SourceResource: &armcompute.APIEntityReference{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/restorePointCollections/{existing-rpc-name}/restorePoints/{existing-rp-name}/diskRestorePoints/{existing-disk-restore-point-name}"),
// },
// }},
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("3906fef9-a1e5-4b83-a8a8-540858b41df0"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithDataDisksFromSourceResource.json
*/
async function createAVMWithDataDisksUsingCopyAndRestoreOptions() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D2_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
dataDisks: [
{
createOption: "Copy",
diskSizeGB: 1023,
lun: 0,
sourceResource: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/{existing-snapshot-name}",
},
},
{
createOption: "Copy",
diskSizeGB: 1023,
lun: 1,
sourceResource: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-disk-name}",
},
},
{
createOption: "Restore",
diskSizeGB: 1023,
lun: 2,
sourceResource: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/restorePointCollections/{existing-rpc-name}/restorePoints/{existing-rp-name}/diskRestorePoints/{existing-disk-restore-point-name}",
},
},
],
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithDataDisksFromSourceResource.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD2V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
DataDisks =
{
new VirtualMachineDataDisk(0,DiskCreateOptionType.Copy)
{
DiskSizeGB = 1023,
SourceResourceId = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/{existing-snapshot-name}"),
},new VirtualMachineDataDisk(1,DiskCreateOptionType.Copy)
{
DiskSizeGB = 1023,
SourceResourceId = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-disk-name}"),
},new VirtualMachineDataDisk(2,DiskCreateOptionType.Restore)
{
DiskSizeGB = 1023,
SourceResourceId = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/restorePointCollections/{existing-rpc-name}/restorePoints/{existing-rp-name}/diskRestorePoints/{existing-disk-restore-point-name}"),
}
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": [
{
"caching": "None",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "Copy",
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/{existing-snapshot-name}"
},
"lun": 0,
"diskSizeGB": 1023
},
{
"caching": "None",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "Copy",
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-disk-name}"
},
"lun": 1,
"diskSizeGB": 1023
},
{
"caching": "None",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "Restore",
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/restorePointCollections/{existing-rpc-name}/restorePoints/{existing-rp-name}/diskRestorePoints/{existing-disk-restore-point-name}"
},
"lun": 2,
"diskSizeGB": 1023
}
]
},
"vmId": "3906fef9-a1e5-4b83-a8a8-540858b41df0",
"hardwareProfile": {
"vmSize": "Standard_D2_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": [
{
"caching": "None",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "Copy",
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/{existing-snapshot-name}"
},
"lun": 0,
"diskSizeGB": 1023,
"toBeDetached": false
},
{
"caching": "None",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "Copy",
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-disk-name}"
},
"lun": 1,
"diskSizeGB": 1023,
"toBeDetached": false
},
{
"caching": "None",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "Restore",
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/restorePointCollections/{existing-rpc-name}/restorePoints/{existing-rp-name}/diskRestorePoints/{existing-disk-restore-point-name}"
},
"lun": 2,
"diskSizeGB": 1023,
"toBeDetached": false
}
]
},
"vmId": "3906fef9-a1e5-4b83-a8a8-540858b41df0",
"hardwareProfile": {
"vmSize": "Standard_D2_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a VM with Disk Controller Type
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D4_v3"
},
"scheduledEventsPolicy": {
"scheduledEventsAdditionalPublishingTargets": {
"eventGridAndResourceGraph": {
"enable": true
}
},
"userInitiatedRedeploy": {
"automaticallyApprove": true
},
"userInitiatedReboot": {
"automaticallyApprove": true
}
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
},
"diskControllerType": "NVMe"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
"enabled": true
}
},
"userData": "U29tZSBDdXN0b20gRGF0YQ=="
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.BootDiagnostics;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiagnosticsProfile;
import com.azure.resourcemanager.compute.models.DiskControllerTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.EventGridAndResourceGraph;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.ScheduledEventsAdditionalPublishingTargets;
import com.azure.resourcemanager.compute.models.ScheduledEventsPolicy;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.UserInitiatedReboot;
import com.azure.resourcemanager.compute.models.UserInitiatedRedeploy;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithDiskControllerType.json
*/
/**
* Sample code: Create a VM with Disk Controller Type.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVMWithDiskControllerType(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D4_V3))
.withScheduledEventsPolicy(new ScheduledEventsPolicy()
.withUserInitiatedRedeploy(new UserInitiatedRedeploy().withAutomaticallyApprove(true))
.withUserInitiatedReboot(new UserInitiatedReboot().withAutomaticallyApprove(true))
.withScheduledEventsAdditionalPublishingTargets(new ScheduledEventsAdditionalPublishingTargets()
.withEventGridAndResourceGraph(new EventGridAndResourceGraph().withEnable(true))))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS)))
.withDiskControllerType(DiskControllerTypes.NVME))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true))))
.withDiagnosticsProfile(new DiagnosticsProfile().withBootDiagnostics(new BootDiagnostics()
.withEnabled(true).withStorageUri("http://{existing-storage-account-name}.blob.core.windows.net")))
.withUserData("U29tZSBDdXN0b20gRGF0YQ=="),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_disk_controller_type.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": True,
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
}
},
"hardwareProfile": {"vmSize": "Standard_D4_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"scheduledEventsPolicy": {
"scheduledEventsAdditionalPublishingTargets": {"eventGridAndResourceGraph": {"enable": True}},
"userInitiatedReboot": {"automaticallyApprove": True},
"userInitiatedRedeploy": {"automaticallyApprove": True},
},
"storageProfile": {
"diskControllerType": "NVMe",
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
"userData": "U29tZSBDdXN0b20gRGF0YQ==",
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithDiskControllerType.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithDiskControllerType.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithDiskControllerType() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
DiagnosticsProfile: &armcompute.DiagnosticsProfile{
BootDiagnostics: &armcompute.BootDiagnostics{
Enabled: to.Ptr(true),
StorageURI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net"),
},
},
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD4V3),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
ScheduledEventsPolicy: &armcompute.ScheduledEventsPolicy{
ScheduledEventsAdditionalPublishingTargets: &armcompute.ScheduledEventsAdditionalPublishingTargets{
EventGridAndResourceGraph: &armcompute.EventGridAndResourceGraph{
Enable: to.Ptr(true),
},
},
UserInitiatedReboot: &armcompute.UserInitiatedReboot{
AutomaticallyApprove: to.Ptr(true),
},
UserInitiatedRedeploy: &armcompute.UserInitiatedRedeploy{
AutomaticallyApprove: to.Ptr(true),
},
},
StorageProfile: &armcompute.StorageProfile{
DiskControllerType: to.Ptr(armcompute.DiskControllerTypesNVMe),
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
UserData: to.Ptr("U29tZSBDdXN0b20gRGF0YQ=="),
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// DiagnosticsProfile: &armcompute.DiagnosticsProfile{
// BootDiagnostics: &armcompute.BootDiagnostics{
// Enabled: to.Ptr(true),
// StorageURI: to.Ptr("http://nsgdiagnostic.blob.core.windows.net"),
// },
// },
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD4V3),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// ScheduledEventsPolicy: &armcompute.ScheduledEventsPolicy{
// ScheduledEventsAdditionalPublishingTargets: &armcompute.ScheduledEventsAdditionalPublishingTargets{
// EventGridAndResourceGraph: &armcompute.EventGridAndResourceGraph{
// Enable: to.Ptr(true),
// },
// },
// UserInitiatedReboot: &armcompute.UserInitiatedReboot{
// AutomaticallyApprove: to.Ptr(true),
// },
// UserInitiatedRedeploy: &armcompute.UserInitiatedRedeploy{
// AutomaticallyApprove: to.Ptr(true),
// },
// },
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// DiskControllerType: to.Ptr(armcompute.DiskControllerTypesNVMe),
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("676420ba-7a24-4bfe-80bd-9c841ee184fa"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithDiskControllerType.json
*/
async function createAVMWithDiskControllerType() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
diagnosticsProfile: {
bootDiagnostics: {
enabled: true,
storageUri: "http://{existing-storage-account-name}.blob.core.windows.net",
},
},
hardwareProfile: { vmSize: "Standard_D4_v3" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
scheduledEventsPolicy: {
scheduledEventsAdditionalPublishingTargets: {
eventGridAndResourceGraph: { enable: true },
},
userInitiatedReboot: { automaticallyApprove: true },
userInitiatedRedeploy: { automaticallyApprove: true },
},
storageProfile: {
diskControllerType: "NVMe",
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
userData: "U29tZSBDdXN0b20gRGF0YQ==",
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithDiskControllerType.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD4V3,
},
ScheduledEventsPolicy = new ScheduledEventsPolicy()
{
UserInitiatedRedeploy = new UserInitiatedRedeploy()
{
AutomaticallyApprove = true,
},
AutomaticallyApprove = true,
Enable = true,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
DiskControllerType = DiskControllerType.NVMe,
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
BootDiagnostics = new BootDiagnostics()
{
Enabled = true,
StorageUri = new Uri("http://{existing-storage-account-name}.blob.core.windows.net"),
},
UserData = "U29tZSBDdXN0b20gRGF0YQ==",
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": [],
"diskControllerType": "NVMe"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://nsgdiagnostic.blob.core.windows.net",
"enabled": true
}
},
"vmId": "676420ba-7a24-4bfe-80bd-9c841ee184fa",
"hardwareProfile": {
"vmSize": "Standard_D4_v3"
},
"scheduledEventsPolicy": {
"scheduledEventsAdditionalPublishingTargets": {
"eventGridAndResourceGraph": {
"enable": true
}
},
"userInitiatedRedeploy": {
"automaticallyApprove": true
},
"userInitiatedReboot": {
"automaticallyApprove": true
}
},
"provisioningState": "Updating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": [],
"diskControllerType": "NVMe"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://nsgdiagnostic.blob.core.windows.net",
"enabled": true
}
},
"vmId": "676420ba-7a24-4bfe-80bd-9c841ee184fa",
"hardwareProfile": {
"vmSize": "Standard_D4_v3"
},
"scheduledEventsPolicy": {
"scheduledEventsAdditionalPublishingTargets": {
"eventGridAndResourceGraph": {
"enable": true
}
},
"userInitiatedRedeploy": {
"automaticallyApprove": true
},
"userInitiatedReboot": {
"automaticallyApprove": true
}
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a vm with DiskEncryptionSet resource id in the os disk and data disk.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS",
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
}
},
"name": "myVMosdisk",
"createOption": "FromImage"
},
"dataDisks": [
{
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS",
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
}
},
"diskSizeGB": 1023,
"createOption": "Empty",
"lun": 0
},
{
"caching": "ReadWrite",
"managedDisk": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-managed-disk-name}",
"storageAccountType": "Standard_LRS",
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
}
},
"diskSizeGB": 1023,
"createOption": "Attach",
"lun": 1
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DataDisk;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.DiskEncryptionSetParameters;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithDiskEncryptionSetResource.json
*/
/**
* Sample code: Create a vm with DiskEncryptionSet resource id in the os disk and data disk.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithDiskEncryptionSetResourceIdInTheOsDiskAndDataDisk(
com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile().withImageReference(new ImageReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE)
.withManagedDisk(new ManagedDiskParameters()
.withStorageAccountType(StorageAccountTypes.STANDARD_LRS)
.withDiskEncryptionSet(new DiskEncryptionSetParameters().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"))))
.withDataDisks(Arrays.asList(new DataDisk().withLun(0).withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.EMPTY).withDiskSizeGB(1023)
.withManagedDisk(new ManagedDiskParameters()
.withStorageAccountType(StorageAccountTypes.STANDARD_LRS)
.withDiskEncryptionSet(new DiskEncryptionSetParameters().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"))),
new DataDisk().withLun(1).withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.ATTACH).withDiskSizeGB(1023)
.withManagedDisk(new ManagedDiskParameters().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-managed-disk-name}")
.withStorageAccountType(StorageAccountTypes.STANDARD_LRS)
.withDiskEncryptionSet(new DiskEncryptionSetParameters().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"))))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_disk_encryption_set_resource.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"dataDisks": [
{
"caching": "ReadWrite",
"createOption": "Empty",
"diskSizeGB": 1023,
"lun": 0,
"managedDisk": {
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
},
"storageAccountType": "Standard_LRS",
},
},
{
"caching": "ReadWrite",
"createOption": "Attach",
"diskSizeGB": 1023,
"lun": 1,
"managedDisk": {
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
},
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-managed-disk-name}",
"storageAccountType": "Standard_LRS",
},
},
],
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
},
"storageAccountType": "Standard_LRS",
},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithDiskEncryptionSetResource.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithDiskEncryptionSetResource.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithDiskEncryptionSetResourceIdInTheOsDiskAndDataDisk() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
DataDisks: []*armcompute.DataDisk{
{
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesEmpty),
DiskSizeGB: to.Ptr[int32](1023),
Lun: to.Ptr[int32](0),
ManagedDisk: &armcompute.ManagedDiskParameters{
DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"),
},
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
{
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesAttach),
DiskSizeGB: to.Ptr[int32](1023),
Lun: to.Ptr[int32](1),
ManagedDisk: &armcompute.ManagedDiskParameters{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-managed-disk-name}"),
DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"),
},
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
}},
ImageReference: &armcompute.ImageReference{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"),
},
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// LinuxConfiguration: &armcompute.LinuxConfiguration{
// DisablePasswordAuthentication: to.Ptr(false),
// },
// Secrets: []*armcompute.VaultSecretGroup{
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// {
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesEmpty),
// DiskSizeGB: to.Ptr[int32](1023),
// Lun: to.Ptr[int32](0),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"),
// },
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// },
// {
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesAttach),
// DiskSizeGB: to.Ptr[int32](1023),
// Lun: to.Ptr[int32](1),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-managed-disk-name}"),
// DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"),
// },
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// }},
// ImageReference: &armcompute.ImageReference{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/nsgcustom"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// DiskSizeGB: to.Ptr[int32](30),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskencryptionset-name}"),
// },
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesLinux),
// },
// },
// VMID: to.Ptr("71aa3d5a-d73d-4970-9182-8580433b2865"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithDiskEncryptionSetResource.json
*/
async function createAVMWithDiskEncryptionSetResourceIdInTheOSDiskAndDataDisk() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
dataDisks: [
{
caching: "ReadWrite",
createOption: "Empty",
diskSizeGB: 1023,
lun: 0,
managedDisk: {
diskEncryptionSet: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}",
},
storageAccountType: "Standard_LRS",
},
},
{
caching: "ReadWrite",
createOption: "Attach",
diskSizeGB: 1023,
lun: 1,
managedDisk: {
diskEncryptionSet: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}",
},
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-managed-disk-name}",
storageAccountType: "Standard_LRS",
},
},
],
imageReference: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: {
diskEncryptionSet: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}",
},
storageAccountType: "Standard_LRS",
},
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithDiskEncryptionSetResource.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}"),
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
DiskEncryptionSetId = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"),
},
},
DataDisks =
{
new VirtualMachineDataDisk(0,DiskCreateOptionType.Empty)
{
Caching = CachingType.ReadWrite,
DiskSizeGB = 1023,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
DiskEncryptionSetId = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"),
},
},new VirtualMachineDataDisk(1,DiskCreateOptionType.Attach)
{
Caching = CachingType.ReadWrite,
DiskSizeGB = 1023,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
DiskEncryptionSetId = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"),
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-managed-disk-name}"),
},
}
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"disablePasswordAuthentication": false
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/nsgcustom"
},
"osDisk": {
"name": "myVMosdisk",
"diskSizeGB": 30,
"managedDisk": {
"storageAccountType": "Standard_LRS",
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskencryptionset-name}"
}
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Linux"
},
"dataDisks": [
{
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS",
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
}
},
"diskSizeGB": 1023,
"createOption": "Empty",
"lun": 0
},
{
"caching": "ReadWrite",
"managedDisk": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-managed-disk-name}",
"storageAccountType": "Standard_LRS",
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
}
},
"diskSizeGB": 1023,
"createOption": "Attach",
"lun": 1
}
]
},
"vmId": "71aa3d5a-d73d-4970-9182-8580433b2865",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"linuxConfiguration": {
"disablePasswordAuthentication": false
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/nsgcustom"
},
"osDisk": {
"name": "myVMosdisk",
"diskSizeGB": 30,
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"caching": "ReadWrite",
"createOption": "FromImage",
"osType": "Linux"
},
"dataDisks": [
{
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS",
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
}
},
"diskSizeGB": 1023,
"createOption": "Empty",
"lun": 0
},
{
"caching": "ReadWrite",
"managedDisk": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-managed-disk-name}",
"storageAccountType": "Standard_LRS",
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
}
},
"diskSizeGB": 1023,
"createOption": "Attach",
"lun": 1
}
]
},
"vmId": "71aa3d5a-d73d-4970-9182-8580433b2865",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a vm with empty data disks.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D2_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
},
"dataDisks": [
{
"diskSizeGB": 1023,
"createOption": "Empty",
"lun": 0
},
{
"diskSizeGB": 1023,
"createOption": "Empty",
"lun": 1
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DataDisk;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithEmptyDataDisks.json
*/
/**
* Sample code: Create a vm with empty data disks.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithEmptyDataDisks(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D2_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS)))
.withDataDisks(Arrays.asList(
new DataDisk().withLun(0).withCreateOption(DiskCreateOptionTypes.EMPTY).withDiskSizeGB(1023),
new DataDisk().withLun(1).withCreateOption(DiskCreateOptionTypes.EMPTY).withDiskSizeGB(1023))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_empty_data_disks.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"dataDisks": [
{"createOption": "Empty", "diskSizeGB": 1023, "lun": 0},
{"createOption": "Empty", "diskSizeGB": 1023, "lun": 1},
],
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithEmptyDataDisks.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithEmptyDataDisks.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithEmptyDataDisks() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
DataDisks: []*armcompute.DataDisk{
{
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesEmpty),
DiskSizeGB: to.Ptr[int32](1023),
Lun: to.Ptr[int32](0),
},
{
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesEmpty),
DiskSizeGB: to.Ptr[int32](1023),
Lun: to.Ptr[int32](1),
}},
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// {
// Caching: to.Ptr(armcompute.CachingTypesNone),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesEmpty),
// DiskSizeGB: to.Ptr[int32](1023),
// Lun: to.Ptr[int32](0),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// },
// {
// Caching: to.Ptr(armcompute.CachingTypesNone),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesEmpty),
// DiskSizeGB: to.Ptr[int32](1023),
// Lun: to.Ptr[int32](1),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// }},
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("3906fef9-a1e5-4b83-a8a8-540858b41df0"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithEmptyDataDisks.json
*/
async function createAVMWithEmptyDataDisks() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D2_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
dataDisks: [
{ createOption: "Empty", diskSizeGB: 1023, lun: 0 },
{ createOption: "Empty", diskSizeGB: 1023, lun: 1 },
],
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithEmptyDataDisks.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD2V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
DataDisks =
{
new VirtualMachineDataDisk(0,DiskCreateOptionType.Empty)
{
DiskSizeGB = 1023,
},new VirtualMachineDataDisk(1,DiskCreateOptionType.Empty)
{
DiskSizeGB = 1023,
}
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": [
{
"caching": "None",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "Empty",
"lun": 0,
"diskSizeGB": 1023
},
{
"caching": "None",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "Empty",
"lun": 1,
"diskSizeGB": 1023
}
]
},
"vmId": "3906fef9-a1e5-4b83-a8a8-540858b41df0",
"hardwareProfile": {
"vmSize": "Standard_D2_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": [
{
"caching": "None",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "Empty",
"lun": 0,
"diskSizeGB": 1023,
"toBeDetached": false
},
{
"caching": "None",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "Empty",
"lun": 1,
"diskSizeGB": 1023,
"toBeDetached": false
}
]
},
"vmId": "3906fef9-a1e5-4b83-a8a8-540858b41df0",
"hardwareProfile": {
"vmSize": "Standard_D2_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a VM with encryption identity
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity": {}
}
},
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"securityProfile": {
"encryptionIdentity": {
"userAssignedIdentityResourceId": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity"
}
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2019-Datacenter",
"version": "latest"
},
"osDisk": {
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.EncryptionIdentity;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.ResourceIdentityType;
import com.azure.resourcemanager.compute.models.SecurityProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineIdentity;
import com.azure.resourcemanager.compute.models.VirtualMachineIdentityUserAssignedIdentities;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithEncryptionIdentity.json
*/
/**
* Sample code: Create a VM with encryption identity.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVMWithEncryptionIdentity(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus").withIdentity(new VirtualMachineIdentity()
.withType(ResourceIdentityType.USER_ASSIGNED)
.withUserAssignedIdentities(mapOf(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity",
new VirtualMachineIdentityUserAssignedIdentities())))
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D2S_V3))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2019-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_ONLY)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_SSD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true))))
.withSecurityProfile(new SecurityProfile()
.withEncryptionIdentity(new EncryptionIdentity().withUserAssignedIdentityResourceId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity"))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_encryption_identity.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity": {}
},
},
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"securityProfile": {
"encryptionIdentity": {
"userAssignedIdentityResourceId": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity"
}
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2019-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "StandardSSD_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithEncryptionIdentity.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithEncryptionIdentity.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithEncryptionIdentity() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Identity: &armcompute.VirtualMachineIdentity{
Type: to.Ptr(armcompute.ResourceIdentityTypeUserAssigned),
UserAssignedIdentities: map[string]*armcompute.UserAssignedIdentitiesValue{
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity": {},
},
},
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
SecurityProfile: &armcompute.SecurityProfile{
EncryptionIdentity: &armcompute.EncryptionIdentity{
UserAssignedIdentityResourceID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity"),
},
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2019-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadOnly),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardSSDLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Identity: &armcompute.VirtualMachineIdentity{
// Type: to.Ptr(armcompute.ResourceIdentityTypeUserAssigned),
// UserAssignedIdentities: map[string]*armcompute.UserAssignedIdentitiesValue{
// "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity": &armcompute.UserAssignedIdentitiesValue{
// },
// },
// },
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// SecurityProfile: &armcompute.SecurityProfile{
// EncryptionIdentity: &armcompute.EncryptionIdentity{
// UserAssignedIdentityResourceID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity"),
// },
// },
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2019-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadOnly),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardSSDLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("5c0d55a7-c407-4ed6-bf7d-ddb810267c85"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithEncryptionIdentity.json
*/
async function createAVMWithEncryptionIdentity() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D2s_v3" },
identity: {
type: "UserAssigned",
userAssignedIdentities: {
"/subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/MicrosoftManagedIdentity/userAssignedIdentities/myIdentity":
{},
},
},
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
securityProfile: {
encryptionIdentity: {
userAssignedIdentityResourceId:
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity",
},
},
storageProfile: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2019-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadOnly",
createOption: "FromImage",
managedDisk: { storageAccountType: "StandardSSD_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithEncryptionIdentity.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
Identity = new ManagedServiceIdentity("UserAssigned")
{
UserAssignedIdentities =
{
[new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity")] = new UserAssignedIdentity(),
},
},
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD2SV3,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2019-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadOnly,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardSsdLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
SecurityProfile = new SecurityProfile()
{
UserAssignedIdentityResourceId = "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity",
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"name": "myVM",
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity": {}
}
},
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2019-Datacenter",
"version": "latest"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"encryptionIdentity": {
"userAssignedIdentityResourceId": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity"
}
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"provisioningState": "Creating"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
{
"name": "myVM",
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity": {}
}
},
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2019-Datacenter",
"version": "latest"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"encryptionIdentity": {
"userAssignedIdentityResourceId": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity"
}
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"provisioningState": "Creating"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
Create a vm with ephemeral os disk provisioning in Cache disk using placement property.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"plan": {
"publisher": "microsoft-ads",
"product": "windows-data-science-vm",
"name": "windows2016"
},
"properties": {
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "windows2016",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "windows-data-science-vm"
},
"osDisk": {
"caching": "ReadOnly",
"diffDiskSettings": {
"option": "Local",
"placement": "CacheDisk"
},
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiffDiskOptions;
import com.azure.resourcemanager.compute.models.DiffDiskPlacement;
import com.azure.resourcemanager.compute.models.DiffDiskSettings;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.Plan;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsCacheDisk.json
*/
/**
* Sample code: Create a vm with ephemeral os disk provisioning in Cache disk using placement property.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithEphemeralOsDiskProvisioningInCacheDiskUsingPlacementProperty(
com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withPlan(new Plan().withName("windows2016").withPublisher("microsoft-ads")
.withProduct("windows-data-science-vm"))
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_DS1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("microsoft-ads")
.withOffer("windows-data-science-vm").withSku("windows2016").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_ONLY)
.withDiffDiskSettings(new DiffDiskSettings().withOption(DiffDiskOptions.LOCAL)
.withPlacement(DiffDiskPlacement.CACHE_DISK))
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_adiff_os_disk_using_diff_disk_placement_as_cache_disk.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"plan": {"name": "windows2016", "product": "windows-data-science-vm", "publisher": "microsoft-ads"},
"properties": {
"hardwareProfile": {"vmSize": "Standard_DS1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "windows-data-science-vm",
"publisher": "microsoft-ads",
"sku": "windows2016",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"diffDiskSettings": {"option": "Local", "placement": "CacheDisk"},
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsCacheDisk.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsCacheDisk.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithEphemeralOsDiskProvisioningInCacheDiskUsingPlacementProperty() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Plan: &armcompute.Plan{
Name: to.Ptr("windows2016"),
Product: to.Ptr("windows-data-science-vm"),
Publisher: to.Ptr("microsoft-ads"),
},
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardDS1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("windows-data-science-vm"),
Publisher: to.Ptr("microsoft-ads"),
SKU: to.Ptr("windows2016"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadOnly),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
DiffDiskSettings: &armcompute.DiffDiskSettings{
Option: to.Ptr(armcompute.DiffDiskOptionsLocal),
Placement: to.Ptr(armcompute.DiffDiskPlacementCacheDisk),
},
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Plan: &armcompute.Plan{
// Name: to.Ptr("standard-data-science-vm"),
// Product: to.Ptr("standard-data-science-vm"),
// Publisher: to.Ptr("microsoft-ads"),
// },
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardDS1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("standard-data-science-vm"),
// Publisher: to.Ptr("microsoft-ads"),
// SKU: to.Ptr("standard-data-science-vm"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadOnly),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// DiffDiskSettings: &armcompute.DiffDiskSettings{
// Option: to.Ptr(armcompute.DiffDiskOptionsLocal),
// Placement: to.Ptr(armcompute.DiffDiskPlacementCacheDisk),
// },
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("5c0d55a7-c407-4ed6-bf7d-ddb810267c85"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsCacheDisk.json
*/
async function createAVMWithEphemeralOSDiskProvisioningInCacheDiskUsingPlacementProperty() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_DS1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
plan: {
name: "windows2016",
product: "windows-data-science-vm",
publisher: "microsoft-ads",
},
storageProfile: {
imageReference: {
offer: "windows-data-science-vm",
publisher: "microsoft-ads",
sku: "windows2016",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadOnly",
createOption: "FromImage",
diffDiskSettings: { option: "Local", placement: "CacheDisk" },
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsCacheDisk.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
Plan = new ComputePlan()
{
Name = "windows2016",
Publisher = "microsoft-ads",
Product = "windows-data-science-vm",
},
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardDS1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "microsoft-ads",
Offer = "windows-data-science-vm",
Sku = "windows2016",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadOnly,
DiffDiskSettings = new DiffDiskSettings()
{
Option = DiffDiskOption.Local,
Placement = DiffDiskPlacement.CacheDisk,
},
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "standard-data-science-vm",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "standard-data-science-vm"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"diffDiskSettings": {
"option": "Local",
"placement": "CacheDisk"
},
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"provisioningState": "Creating"
},
"plan": {
"publisher": "microsoft-ads",
"product": "standard-data-science-vm",
"name": "standard-data-science-vm"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "standard-data-science-vm",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "standard-data-science-vm"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"diffDiskSettings": {
"option": "Local",
"placement": "CacheDisk"
},
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"provisioningState": "Creating"
},
"plan": {
"publisher": "microsoft-ads",
"product": "standard-data-science-vm",
"name": "standard-data-science-vm"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
Create a vm with ephemeral os disk provisioning in Nvme disk using placement property.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"plan": {
"publisher": "microsoft-ads",
"product": "windows-data-science-vm",
"name": "windows2016"
},
"properties": {
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "windows2016",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "windows-data-science-vm"
},
"osDisk": {
"caching": "ReadOnly",
"diffDiskSettings": {
"option": "Local",
"placement": "NvmeDisk"
},
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiffDiskOptions;
import com.azure.resourcemanager.compute.models.DiffDiskPlacement;
import com.azure.resourcemanager.compute.models.DiffDiskSettings;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.Plan;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsNvmeDisk.json
*/
/**
* Sample code: Create a vm with ephemeral os disk provisioning in Nvme disk using placement property.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithEphemeralOsDiskProvisioningInNvmeDiskUsingPlacementProperty(
com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withPlan(new Plan().withName("windows2016").withPublisher("microsoft-ads")
.withProduct("windows-data-science-vm"))
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_DS1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("microsoft-ads")
.withOffer("windows-data-science-vm").withSku("windows2016").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_ONLY)
.withDiffDiskSettings(new DiffDiskSettings().withOption(DiffDiskOptions.LOCAL)
.withPlacement(DiffDiskPlacement.NVME_DISK))
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_adiff_os_disk_using_diff_disk_placement_as_nvme_disk.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"plan": {"name": "windows2016", "product": "windows-data-science-vm", "publisher": "microsoft-ads"},
"properties": {
"hardwareProfile": {"vmSize": "Standard_DS1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "windows-data-science-vm",
"publisher": "microsoft-ads",
"sku": "windows2016",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"diffDiskSettings": {"option": "Local", "placement": "NvmeDisk"},
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsNvmeDisk.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsNvmeDisk.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithEphemeralOsDiskProvisioningInNvmeDiskUsingPlacementProperty() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Plan: &armcompute.Plan{
Name: to.Ptr("windows2016"),
Product: to.Ptr("windows-data-science-vm"),
Publisher: to.Ptr("microsoft-ads"),
},
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardDS1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("windows-data-science-vm"),
Publisher: to.Ptr("microsoft-ads"),
SKU: to.Ptr("windows2016"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadOnly),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
DiffDiskSettings: &armcompute.DiffDiskSettings{
Option: to.Ptr(armcompute.DiffDiskOptionsLocal),
Placement: to.Ptr(armcompute.DiffDiskPlacementNvmeDisk),
},
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Plan: &armcompute.Plan{
// Name: to.Ptr("standard-data-science-vm"),
// Product: to.Ptr("standard-data-science-vm"),
// Publisher: to.Ptr("microsoft-ads"),
// },
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardDS1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("standard-data-science-vm"),
// Publisher: to.Ptr("microsoft-ads"),
// SKU: to.Ptr("standard-data-science-vm"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadOnly),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// DiffDiskSettings: &armcompute.DiffDiskSettings{
// Option: to.Ptr(armcompute.DiffDiskOptionsLocal),
// Placement: to.Ptr(armcompute.DiffDiskPlacementNvmeDisk),
// },
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("5c0d55a7-c407-4ed6-bf7d-ddb810267c85"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsNvmeDisk.json
*/
async function createAVMWithEphemeralOSDiskProvisioningInNvmeDiskUsingPlacementProperty() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_DS1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
plan: {
name: "windows2016",
product: "windows-data-science-vm",
publisher: "microsoft-ads",
},
storageProfile: {
imageReference: {
offer: "windows-data-science-vm",
publisher: "microsoft-ads",
sku: "windows2016",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadOnly",
createOption: "FromImage",
diffDiskSettings: { option: "Local", placement: "NvmeDisk" },
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsNvmeDisk.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
Plan = new ComputePlan()
{
Name = "windows2016",
Publisher = "microsoft-ads",
Product = "windows-data-science-vm",
},
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardDS1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "microsoft-ads",
Offer = "windows-data-science-vm",
Sku = "windows2016",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadOnly,
DiffDiskSettings = new DiffDiskSettings()
{
Option = DiffDiskOption.Local,
Placement = DiffDiskPlacement.NvmeDisk,
},
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "standard-data-science-vm",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "standard-data-science-vm"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"diffDiskSettings": {
"option": "Local",
"placement": "NvmeDisk"
},
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"provisioningState": "Creating"
},
"plan": {
"publisher": "microsoft-ads",
"product": "standard-data-science-vm",
"name": "standard-data-science-vm"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "standard-data-science-vm",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "standard-data-science-vm"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"diffDiskSettings": {
"option": "Local",
"placement": "NvmeDisk"
},
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"provisioningState": "Creating"
},
"plan": {
"publisher": "microsoft-ads",
"product": "standard-data-science-vm",
"name": "standard-data-science-vm"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
Create a vm with ephemeral os disk provisioning in Resource disk using placement property.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"plan": {
"publisher": "microsoft-ads",
"product": "windows-data-science-vm",
"name": "windows2016"
},
"properties": {
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "windows2016",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "windows-data-science-vm"
},
"osDisk": {
"caching": "ReadOnly",
"diffDiskSettings": {
"option": "Local",
"placement": "ResourceDisk"
},
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiffDiskOptions;
import com.azure.resourcemanager.compute.models.DiffDiskPlacement;
import com.azure.resourcemanager.compute.models.DiffDiskSettings;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.Plan;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsResourceDisk.json
*/
/**
* Sample code: Create a vm with ephemeral os disk provisioning in Resource disk using placement property.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithEphemeralOsDiskProvisioningInResourceDiskUsingPlacementProperty(
com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withPlan(new Plan().withName("windows2016").withPublisher("microsoft-ads")
.withProduct("windows-data-science-vm"))
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_DS1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("microsoft-ads")
.withOffer("windows-data-science-vm").withSku("windows2016").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_ONLY)
.withDiffDiskSettings(new DiffDiskSettings().withOption(DiffDiskOptions.LOCAL)
.withPlacement(DiffDiskPlacement.RESOURCE_DISK))
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_adiff_os_disk_using_diff_disk_placement_as_resource_disk.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"plan": {"name": "windows2016", "product": "windows-data-science-vm", "publisher": "microsoft-ads"},
"properties": {
"hardwareProfile": {"vmSize": "Standard_DS1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "windows-data-science-vm",
"publisher": "microsoft-ads",
"sku": "windows2016",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"diffDiskSettings": {"option": "Local", "placement": "ResourceDisk"},
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsResourceDisk.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsResourceDisk.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithEphemeralOsDiskProvisioningInResourceDiskUsingPlacementProperty() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Plan: &armcompute.Plan{
Name: to.Ptr("windows2016"),
Product: to.Ptr("windows-data-science-vm"),
Publisher: to.Ptr("microsoft-ads"),
},
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardDS1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("windows-data-science-vm"),
Publisher: to.Ptr("microsoft-ads"),
SKU: to.Ptr("windows2016"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadOnly),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
DiffDiskSettings: &armcompute.DiffDiskSettings{
Option: to.Ptr(armcompute.DiffDiskOptionsLocal),
Placement: to.Ptr(armcompute.DiffDiskPlacementResourceDisk),
},
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Plan: &armcompute.Plan{
// Name: to.Ptr("standard-data-science-vm"),
// Product: to.Ptr("standard-data-science-vm"),
// Publisher: to.Ptr("microsoft-ads"),
// },
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardDS1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("standard-data-science-vm"),
// Publisher: to.Ptr("microsoft-ads"),
// SKU: to.Ptr("standard-data-science-vm"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadOnly),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// DiffDiskSettings: &armcompute.DiffDiskSettings{
// Option: to.Ptr(armcompute.DiffDiskOptionsLocal),
// Placement: to.Ptr(armcompute.DiffDiskPlacementResourceDisk),
// },
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("5c0d55a7-c407-4ed6-bf7d-ddb810267c85"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsResourceDisk.json
*/
async function createAVMWithEphemeralOSDiskProvisioningInResourceDiskUsingPlacementProperty() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_DS1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
plan: {
name: "windows2016",
product: "windows-data-science-vm",
publisher: "microsoft-ads",
},
storageProfile: {
imageReference: {
offer: "windows-data-science-vm",
publisher: "microsoft-ads",
sku: "windows2016",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadOnly",
createOption: "FromImage",
diffDiskSettings: { option: "Local", placement: "ResourceDisk" },
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDiskUsingDiffDiskPlacementAsResourceDisk.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
Plan = new ComputePlan()
{
Name = "windows2016",
Publisher = "microsoft-ads",
Product = "windows-data-science-vm",
},
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardDS1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "microsoft-ads",
Offer = "windows-data-science-vm",
Sku = "windows2016",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadOnly,
DiffDiskSettings = new DiffDiskSettings()
{
Option = DiffDiskOption.Local,
Placement = DiffDiskPlacement.ResourceDisk,
},
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "standard-data-science-vm",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "standard-data-science-vm"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"diffDiskSettings": {
"option": "Local",
"placement": "ResourceDisk"
},
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"provisioningState": "Creating"
},
"plan": {
"publisher": "microsoft-ads",
"product": "standard-data-science-vm",
"name": "standard-data-science-vm"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "standard-data-science-vm",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "standard-data-science-vm"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"diffDiskSettings": {
"option": "Local",
"placement": "ResourceDisk"
},
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"provisioningState": "Creating"
},
"plan": {
"publisher": "microsoft-ads",
"product": "standard-data-science-vm",
"name": "standard-data-science-vm"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
Create a vm with ephemeral os disk.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"plan": {
"publisher": "microsoft-ads",
"product": "windows-data-science-vm",
"name": "windows2016"
},
"properties": {
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "windows2016",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "windows-data-science-vm"
},
"osDisk": {
"caching": "ReadOnly",
"diffDiskSettings": {
"option": "Local"
},
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiffDiskOptions;
import com.azure.resourcemanager.compute.models.DiffDiskSettings;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.Plan;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithADiffOsDisk.json
*/
/**
* Sample code: Create a vm with ephemeral os disk.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithEphemeralOsDisk(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withPlan(new Plan().withName("windows2016").withPublisher("microsoft-ads")
.withProduct("windows-data-science-vm"))
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_DS1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("microsoft-ads")
.withOffer("windows-data-science-vm").withSku("windows2016").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_ONLY)
.withDiffDiskSettings(new DiffDiskSettings().withOption(DiffDiskOptions.LOCAL))
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_adiff_os_disk.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"plan": {"name": "windows2016", "product": "windows-data-science-vm", "publisher": "microsoft-ads"},
"properties": {
"hardwareProfile": {"vmSize": "Standard_DS1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "windows-data-science-vm",
"publisher": "microsoft-ads",
"sku": "windows2016",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"diffDiskSettings": {"option": "Local"},
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDisk.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDisk.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithEphemeralOsDisk() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Plan: &armcompute.Plan{
Name: to.Ptr("windows2016"),
Product: to.Ptr("windows-data-science-vm"),
Publisher: to.Ptr("microsoft-ads"),
},
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardDS1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("windows-data-science-vm"),
Publisher: to.Ptr("microsoft-ads"),
SKU: to.Ptr("windows2016"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadOnly),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
DiffDiskSettings: &armcompute.DiffDiskSettings{
Option: to.Ptr(armcompute.DiffDiskOptionsLocal),
},
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Plan: &armcompute.Plan{
// Name: to.Ptr("standard-data-science-vm"),
// Product: to.Ptr("standard-data-science-vm"),
// Publisher: to.Ptr("microsoft-ads"),
// },
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardDS1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("standard-data-science-vm"),
// Publisher: to.Ptr("microsoft-ads"),
// SKU: to.Ptr("standard-data-science-vm"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadOnly),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// DiffDiskSettings: &armcompute.DiffDiskSettings{
// Option: to.Ptr(armcompute.DiffDiskOptionsLocal),
// },
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("5c0d55a7-c407-4ed6-bf7d-ddb810267c85"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDisk.json
*/
async function createAVMWithEphemeralOSDisk() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_DS1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
plan: {
name: "windows2016",
product: "windows-data-science-vm",
publisher: "microsoft-ads",
},
storageProfile: {
imageReference: {
offer: "windows-data-science-vm",
publisher: "microsoft-ads",
sku: "windows2016",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadOnly",
createOption: "FromImage",
diffDiskSettings: { option: "Local" },
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithADiffOsDisk.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
Plan = new ComputePlan()
{
Name = "windows2016",
Publisher = "microsoft-ads",
Product = "windows-data-science-vm",
},
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardDS1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "microsoft-ads",
Offer = "windows-data-science-vm",
Sku = "windows2016",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadOnly,
DiffDiskSettings = new DiffDiskSettings()
{
Option = DiffDiskOption.Local,
},
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "standard-data-science-vm",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "standard-data-science-vm"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"diffDiskSettings": {
"option": "Local"
},
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"provisioningState": "Creating"
},
"plan": {
"publisher": "microsoft-ads",
"product": "standard-data-science-vm",
"name": "standard-data-science-vm"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "standard-data-science-vm",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "standard-data-science-vm"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"diffDiskSettings": {
"option": "Local"
},
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"provisioningState": "Creating"
},
"plan": {
"publisher": "microsoft-ads",
"product": "standard-data-science-vm",
"name": "standard-data-science-vm"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
Create a VM with HibernationEnabled
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/{vm-name}?api-version=2024-07-01
{
"location": "eastus2euap",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"additionalCapabilities": {
"hibernationEnabled": true
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2019-Datacenter",
"version": "latest"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "vmOSdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "{vm-name}",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
"enabled": true
}
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.AdditionalCapabilities;
import com.azure.resourcemanager.compute.models.BootDiagnostics;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiagnosticsProfile;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithHibernationEnabled.json
*/
/**
* Sample code: Create a VM with HibernationEnabled.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVMWithHibernationEnabled(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup",
"{vm-name}",
new VirtualMachineInner().withLocation("eastus2euap")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D2S_V3))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2019-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("vmOSdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withAdditionalCapabilities(new AdditionalCapabilities().withHibernationEnabled(true))
.withOsProfile(new OSProfile().withComputerName("{vm-name}").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true))))
.withDiagnosticsProfile(new DiagnosticsProfile().withBootDiagnostics(new BootDiagnostics()
.withEnabled(true).withStorageUri("http://{existing-storage-account-name}.blob.core.windows.net"))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_hibernation_enabled.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="{vm-name}",
parameters={
"location": "eastus2euap",
"properties": {
"additionalCapabilities": {"hibernationEnabled": True},
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": True,
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
}
},
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "{vm-name}",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2019-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "vmOSdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithHibernationEnabled.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithHibernationEnabled.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithHibernationEnabled() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "{vm-name}", armcompute.VirtualMachine{
Location: to.Ptr("eastus2euap"),
Properties: &armcompute.VirtualMachineProperties{
AdditionalCapabilities: &armcompute.AdditionalCapabilities{
HibernationEnabled: to.Ptr(true),
},
DiagnosticsProfile: &armcompute.DiagnosticsProfile{
BootDiagnostics: &armcompute.BootDiagnostics{
Enabled: to.Ptr(true),
StorageURI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net"),
},
},
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("{vm-name}"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2019-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("vmOSdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("{vm-name}"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/{vm-name}"),
// Location: to.Ptr("eastus2euap"),
// Properties: &armcompute.VirtualMachineProperties{
// AdditionalCapabilities: &armcompute.AdditionalCapabilities{
// HibernationEnabled: to.Ptr(true),
// },
// DiagnosticsProfile: &armcompute.DiagnosticsProfile{
// BootDiagnostics: &armcompute.BootDiagnostics{
// Enabled: to.Ptr(true),
// StorageURI: to.Ptr("http://nsgdiagnostic.blob.core.windows.net"),
// },
// },
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("{vm-name}"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2019-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("vmOSdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("676420ba-7a24-4bfe-80bd-9c841ee184fa"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithHibernationEnabled.json
*/
async function createAVMWithHibernationEnabled() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "{vm-name}";
const parameters = {
additionalCapabilities: { hibernationEnabled: true },
diagnosticsProfile: {
bootDiagnostics: {
enabled: true,
storageUri: "http://{existing-storage-account-name}.blob.core.windows.net",
},
},
hardwareProfile: { vmSize: "Standard_D2s_v3" },
location: "eastus2euap",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "{vm-name}",
},
storageProfile: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2019-Datacenter",
version: "latest",
},
osDisk: {
name: "vmOSdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithHibernationEnabled.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "{vm-name}";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("eastus2euap"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD2SV3,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2019-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "vmOSdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
AdditionalCapabilities = new AdditionalCapabilities()
{
HibernationEnabled = true,
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "{vm-name}",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
BootDiagnostics = new BootDiagnostics()
{
Enabled = true,
StorageUri = new Uri("http://{existing-storage-account-name}.blob.core.windows.net"),
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/{vm-name}",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "{vm-name}",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2019-Datacenter",
"version": "latest"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "vmOSdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://nsgdiagnostic.blob.core.windows.net",
"enabled": true
}
},
"vmId": "676420ba-7a24-4bfe-80bd-9c841ee184fa",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"additionalCapabilities": {
"hibernationEnabled": true
},
"provisioningState": "Updating"
},
"name": "{vm-name}",
"location": "eastus2euap"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/{vm-name}",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "{vm-name}",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2019-Datacenter",
"version": "latest"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "vmOSdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://nsgdiagnostic.blob.core.windows.net",
"enabled": true
}
},
"vmId": "676420ba-7a24-4bfe-80bd-9c841ee184fa",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"additionalCapabilities": {
"hibernationEnabled": true
},
"provisioningState": "Creating"
},
"name": "{vm-name}",
"location": "eastus2euap"
}
Create a vm with Host Encryption using encryptionAtHost property.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"plan": {
"publisher": "microsoft-ads",
"product": "windows-data-science-vm",
"name": "windows2016"
},
"properties": {
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"securityProfile": {
"encryptionAtHost": true
},
"storageProfile": {
"imageReference": {
"sku": "windows2016",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "windows-data-science-vm"
},
"osDisk": {
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.Plan;
import com.azure.resourcemanager.compute.models.SecurityProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithEncryptionAtHost.json
*/
/**
* Sample code: Create a vm with Host Encryption using encryptionAtHost property.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void
createAVmWithHostEncryptionUsingEncryptionAtHostProperty(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withPlan(new Plan().withName("windows2016").withPublisher("microsoft-ads")
.withProduct("windows-data-science-vm"))
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_DS1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("microsoft-ads")
.withOffer("windows-data-science-vm").withSku("windows2016").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_ONLY)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true))))
.withSecurityProfile(new SecurityProfile().withEncryptionAtHost(true)),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_encryption_at_host.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"plan": {"name": "windows2016", "product": "windows-data-science-vm", "publisher": "microsoft-ads"},
"properties": {
"hardwareProfile": {"vmSize": "Standard_DS1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"securityProfile": {"encryptionAtHost": True},
"storageProfile": {
"imageReference": {
"offer": "windows-data-science-vm",
"publisher": "microsoft-ads",
"sku": "windows2016",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithEncryptionAtHost.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithEncryptionAtHost.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithHostEncryptionUsingEncryptionAtHostProperty() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Plan: &armcompute.Plan{
Name: to.Ptr("windows2016"),
Product: to.Ptr("windows-data-science-vm"),
Publisher: to.Ptr("microsoft-ads"),
},
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardDS1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
SecurityProfile: &armcompute.SecurityProfile{
EncryptionAtHost: to.Ptr(true),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("windows-data-science-vm"),
Publisher: to.Ptr("microsoft-ads"),
SKU: to.Ptr("windows2016"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadOnly),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Plan: &armcompute.Plan{
// Name: to.Ptr("standard-data-science-vm"),
// Product: to.Ptr("standard-data-science-vm"),
// Publisher: to.Ptr("microsoft-ads"),
// },
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardDS1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// SecurityProfile: &armcompute.SecurityProfile{
// EncryptionAtHost: to.Ptr(true),
// },
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("standard-data-science-vm"),
// Publisher: to.Ptr("microsoft-ads"),
// SKU: to.Ptr("standard-data-science-vm"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadOnly),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("5c0d55a7-c407-4ed6-bf7d-ddb810267c85"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithEncryptionAtHost.json
*/
async function createAVMWithHostEncryptionUsingEncryptionAtHostProperty() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_DS1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
plan: {
name: "windows2016",
product: "windows-data-science-vm",
publisher: "microsoft-ads",
},
securityProfile: { encryptionAtHost: true },
storageProfile: {
imageReference: {
offer: "windows-data-science-vm",
publisher: "microsoft-ads",
sku: "windows2016",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadOnly",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithEncryptionAtHost.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
Plan = new ComputePlan()
{
Name = "windows2016",
Publisher = "microsoft-ads",
Product = "windows-data-science-vm",
},
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardDS1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "microsoft-ads",
Offer = "windows-data-science-vm",
Sku = "windows2016",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadOnly,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
SecurityProfile = new SecurityProfile()
{
EncryptionAtHost = true,
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "standard-data-science-vm",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "standard-data-science-vm"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"encryptionAtHost": true
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"provisioningState": "Creating"
},
"plan": {
"publisher": "microsoft-ads",
"product": "standard-data-science-vm",
"name": "standard-data-science-vm"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "standard-data-science-vm",
"publisher": "microsoft-ads",
"version": "latest",
"offer": "standard-data-science-vm"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"encryptionAtHost": true
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"provisioningState": "Creating"
},
"plan": {
"publisher": "microsoft-ads",
"product": "standard-data-science-vm",
"name": "standard-data-science-vm"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
Create a vm with managed boot diagnostics.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": true
}
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.BootDiagnostics;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiagnosticsProfile;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithManagedBootDiagnostics.json
*/
/**
* Sample code: Create a vm with managed boot diagnostics.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithManagedBootDiagnostics(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true))))
.withDiagnosticsProfile(
new DiagnosticsProfile().withBootDiagnostics(new BootDiagnostics().withEnabled(true))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_managed_boot_diagnostics.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"diagnosticsProfile": {"bootDiagnostics": {"enabled": True}},
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithManagedBootDiagnostics.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithManagedBootDiagnostics.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithManagedBootDiagnostics() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
DiagnosticsProfile: &armcompute.DiagnosticsProfile{
BootDiagnostics: &armcompute.BootDiagnostics{
Enabled: to.Ptr(true),
},
},
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// DiagnosticsProfile: &armcompute.DiagnosticsProfile{
// BootDiagnostics: &armcompute.BootDiagnostics{
// Enabled: to.Ptr(true),
// },
// },
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("676420ba-7a24-4bfe-80bd-9c841ee184fa"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithManagedBootDiagnostics.json
*/
async function createAVMWithManagedBootDiagnostics() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
diagnosticsProfile: { bootDiagnostics: { enabled: true } },
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithManagedBootDiagnostics.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
BootDiagnostics = new BootDiagnostics()
{
Enabled = true,
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": true
}
},
"vmId": "676420ba-7a24-4bfe-80bd-9c841ee184fa",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": true
}
},
"vmId": "676420ba-7a24-4bfe-80bd-9c841ee184fa",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a VM with network interface configuration
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkApiVersion": "2020-11-01",
"networkInterfaceConfigurations": [
{
"name": "{nic-config-name}",
"properties": {
"primary": true,
"deleteOption": "Delete",
"ipConfigurations": [
{
"name": "{ip-config-name}",
"properties": {
"primary": true,
"publicIPAddressConfiguration": {
"name": "{publicIP-config-name}",
"sku": {
"name": "Basic",
"tier": "Global"
},
"properties": {
"deleteOption": "Detach",
"publicIPAllocationMethod": "Static"
}
}
}
}
]
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DeleteOptions;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkApiVersion;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.PublicIpAddressSku;
import com.azure.resourcemanager.compute.models.PublicIpAddressSkuName;
import com.azure.resourcemanager.compute.models.PublicIpAddressSkuTier;
import com.azure.resourcemanager.compute.models.PublicIpAllocationMethod;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineNetworkInterfaceConfiguration;
import com.azure.resourcemanager.compute.models.VirtualMachineNetworkInterfaceIpConfiguration;
import com.azure.resourcemanager.compute.models.VirtualMachinePublicIpAddressConfiguration;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithNetworkInterfaceConfiguration.json
*/
/**
* Sample code: Create a VM with network interface configuration.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void
createAVMWithNetworkInterfaceConfiguration(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(new NetworkProfile()
.withNetworkApiVersion(NetworkApiVersion.TWO_ZERO_TWO_ZERO_ONE_ONE_ZERO_ONE)
.withNetworkInterfaceConfigurations(
Arrays.asList(new VirtualMachineNetworkInterfaceConfiguration().withName("{nic-config-name}")
.withPrimary(true).withDeleteOption(DeleteOptions.DELETE)
.withIpConfigurations(Arrays.asList(new VirtualMachineNetworkInterfaceIpConfiguration()
.withName("{ip-config-name}").withPrimary(true)
.withPublicIpAddressConfiguration(new VirtualMachinePublicIpAddressConfiguration()
.withName("{publicIP-config-name}")
.withSku(new PublicIpAddressSku().withName(PublicIpAddressSkuName.BASIC)
.withTier(PublicIpAddressSkuTier.GLOBAL))
.withDeleteOption(DeleteOptions.DETACH)
.withPublicIpAllocationMethod(PublicIpAllocationMethod.STATIC))))))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_network_interface_configuration.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkApiVersion": "2020-11-01",
"networkInterfaceConfigurations": [
{
"name": "{nic-config-name}",
"properties": {
"deleteOption": "Delete",
"ipConfigurations": [
{
"name": "{ip-config-name}",
"properties": {
"primary": True,
"publicIPAddressConfiguration": {
"name": "{publicIP-config-name}",
"properties": {
"deleteOption": "Detach",
"publicIPAllocationMethod": "Static",
},
"sku": {"name": "Basic", "tier": "Global"},
},
},
}
],
"primary": True,
},
}
],
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithNetworkInterfaceConfiguration.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithNetworkInterfaceConfiguration.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithNetworkInterfaceConfiguration() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkAPIVersion: to.Ptr(armcompute.NetworkAPIVersionTwoThousandTwenty1101),
NetworkInterfaceConfigurations: []*armcompute.VirtualMachineNetworkInterfaceConfiguration{
{
Name: to.Ptr("{nic-config-name}"),
Properties: &armcompute.VirtualMachineNetworkInterfaceConfigurationProperties{
DeleteOption: to.Ptr(armcompute.DeleteOptionsDelete),
IPConfigurations: []*armcompute.VirtualMachineNetworkInterfaceIPConfiguration{
{
Name: to.Ptr("{ip-config-name}"),
Properties: &armcompute.VirtualMachineNetworkInterfaceIPConfigurationProperties{
Primary: to.Ptr(true),
PublicIPAddressConfiguration: &armcompute.VirtualMachinePublicIPAddressConfiguration{
Name: to.Ptr("{publicIP-config-name}"),
Properties: &armcompute.VirtualMachinePublicIPAddressConfigurationProperties{
DeleteOption: to.Ptr(armcompute.DeleteOptionsDetach),
PublicIPAllocationMethod: to.Ptr(armcompute.PublicIPAllocationMethodStatic),
},
SKU: &armcompute.PublicIPAddressSKU{
Name: to.Ptr(armcompute.PublicIPAddressSKUNameBasic),
Tier: to.Ptr(armcompute.PublicIPAddressSKUTierGlobal),
},
},
},
}},
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/toBeCreatedNetworkInterface"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("b7a098cc-b0b8-46e8-a205-62f301a62a8f"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithNetworkInterfaceConfiguration.json
*/
async function createAVMWithNetworkInterfaceConfiguration() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkApiVersion: "2020-11-01",
networkInterfaceConfigurations: [
{
name: "{nic-config-name}",
deleteOption: "Delete",
ipConfigurations: [
{
name: "{ip-config-name}",
primary: true,
publicIPAddressConfiguration: {
name: "{publicIP-config-name}",
deleteOption: "Detach",
publicIPAllocationMethod: "Static",
sku: { name: "Basic", tier: "Global" },
},
},
],
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithNetworkInterfaceConfiguration.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkApiVersion = NetworkApiVersion.TwoThousandTwenty1101,
NetworkInterfaceConfigurations =
{
new VirtualMachineNetworkInterfaceConfiguration("{nic-config-name}")
{
Primary = true,
DeleteOption = ComputeDeleteOption.Delete,
IPConfigurations =
{
new VirtualMachineNetworkInterfaceIPConfiguration("{ip-config-name}")
{
Primary = true,
PublicIPAddressConfiguration = new VirtualMachinePublicIPAddressConfiguration("{publicIP-config-name}")
{
Sku = new ComputePublicIPAddressSku()
{
Name = ComputePublicIPAddressSkuName.Basic,
Tier = ComputePublicIPAddressSkuTier.Global,
},
DeleteOption = ComputeDeleteOption.Detach,
PublicIPAllocationMethod = PublicIPAllocationMethod.Static,
},
}
},
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/toBeCreatedNetworkInterface",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"vmId": "b7a098cc-b0b8-46e8-a205-62f301a62a8f",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/toBeCreatedNetworkInterface",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"vmId": "b7a098cc-b0b8-46e8-a205-62f301a62a8f",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a VM with network interface configuration with public ip address dns settings
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkApiVersion": "2020-11-01",
"networkInterfaceConfigurations": [
{
"name": "{nic-config-name}",
"properties": {
"primary": true,
"deleteOption": "Delete",
"ipConfigurations": [
{
"name": "{ip-config-name}",
"properties": {
"primary": true,
"publicIPAddressConfiguration": {
"name": "{publicIP-config-name}",
"sku": {
"name": "Basic",
"tier": "Global"
},
"properties": {
"deleteOption": "Detach",
"publicIPAllocationMethod": "Static",
"dnsSettings": {
"domainNameLabel": "aaaaa",
"domainNameLabelScope": "TenantReuse"
}
}
}
}
}
]
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DeleteOptions;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.DomainNameLabelScopeTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkApiVersion;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.PublicIpAddressSku;
import com.azure.resourcemanager.compute.models.PublicIpAddressSkuName;
import com.azure.resourcemanager.compute.models.PublicIpAddressSkuTier;
import com.azure.resourcemanager.compute.models.PublicIpAllocationMethod;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineNetworkInterfaceConfiguration;
import com.azure.resourcemanager.compute.models.VirtualMachineNetworkInterfaceIpConfiguration;
import com.azure.resourcemanager.compute.models.VirtualMachinePublicIpAddressConfiguration;
import com.azure.resourcemanager.compute.models.VirtualMachinePublicIpAddressDnsSettingsConfiguration;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithNetworkInterfaceConfigurationDnsSettings.json
*/
/**
* Sample code: Create a VM with network interface configuration with public ip address dns settings.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVMWithNetworkInterfaceConfigurationWithPublicIpAddressDnsSettings(
com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkApiVersion(NetworkApiVersion.TWO_ZERO_TWO_ZERO_ONE_ONE_ZERO_ONE)
.withNetworkInterfaceConfigurations(
Arrays.asList(new VirtualMachineNetworkInterfaceConfiguration()
.withName("{nic-config-name}").withPrimary(true).withDeleteOption(DeleteOptions.DELETE)
.withIpConfigurations(Arrays.asList(new VirtualMachineNetworkInterfaceIpConfiguration()
.withName("{ip-config-name}").withPrimary(true)
.withPublicIpAddressConfiguration(new VirtualMachinePublicIpAddressConfiguration()
.withName("{publicIP-config-name}")
.withSku(new PublicIpAddressSku().withName(PublicIpAddressSkuName.BASIC)
.withTier(PublicIpAddressSkuTier.GLOBAL))
.withDeleteOption(DeleteOptions.DETACH)
.withDnsSettings(new VirtualMachinePublicIpAddressDnsSettingsConfiguration()
.withDomainNameLabel("aaaaa")
.withDomainNameLabelScope(DomainNameLabelScopeTypes.TENANT_REUSE))
.withPublicIpAllocationMethod(PublicIpAllocationMethod.STATIC))))))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_network_interface_configuration_dns_settings.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkApiVersion": "2020-11-01",
"networkInterfaceConfigurations": [
{
"name": "{nic-config-name}",
"properties": {
"deleteOption": "Delete",
"ipConfigurations": [
{
"name": "{ip-config-name}",
"properties": {
"primary": True,
"publicIPAddressConfiguration": {
"name": "{publicIP-config-name}",
"properties": {
"deleteOption": "Detach",
"dnsSettings": {
"domainNameLabel": "aaaaa",
"domainNameLabelScope": "TenantReuse",
},
"publicIPAllocationMethod": "Static",
},
"sku": {"name": "Basic", "tier": "Global"},
},
},
}
],
"primary": True,
},
}
],
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithNetworkInterfaceConfigurationDnsSettings.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithNetworkInterfaceConfigurationDnsSettings.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithNetworkInterfaceConfigurationWithPublicIpAddressDnsSettings() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkAPIVersion: to.Ptr(armcompute.NetworkAPIVersionTwoThousandTwenty1101),
NetworkInterfaceConfigurations: []*armcompute.VirtualMachineNetworkInterfaceConfiguration{
{
Name: to.Ptr("{nic-config-name}"),
Properties: &armcompute.VirtualMachineNetworkInterfaceConfigurationProperties{
DeleteOption: to.Ptr(armcompute.DeleteOptionsDelete),
IPConfigurations: []*armcompute.VirtualMachineNetworkInterfaceIPConfiguration{
{
Name: to.Ptr("{ip-config-name}"),
Properties: &armcompute.VirtualMachineNetworkInterfaceIPConfigurationProperties{
Primary: to.Ptr(true),
PublicIPAddressConfiguration: &armcompute.VirtualMachinePublicIPAddressConfiguration{
Name: to.Ptr("{publicIP-config-name}"),
Properties: &armcompute.VirtualMachinePublicIPAddressConfigurationProperties{
DeleteOption: to.Ptr(armcompute.DeleteOptionsDetach),
DNSSettings: &armcompute.VirtualMachinePublicIPAddressDNSSettingsConfiguration{
DomainNameLabel: to.Ptr("aaaaa"),
DomainNameLabelScope: to.Ptr(armcompute.DomainNameLabelScopeTypesTenantReuse),
},
PublicIPAllocationMethod: to.Ptr(armcompute.PublicIPAllocationMethodStatic),
},
SKU: &armcompute.PublicIPAddressSKU{
Name: to.Ptr(armcompute.PublicIPAddressSKUNameBasic),
Tier: to.Ptr(armcompute.PublicIPAddressSKUTierGlobal),
},
},
},
}},
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/toBeCreatedNetworkInterface"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("b7a098cc-b0b8-46e8-a205-62f301a62a8f"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithNetworkInterfaceConfigurationDnsSettings.json
*/
async function createAVMWithNetworkInterfaceConfigurationWithPublicIPAddressDnsSettings() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkApiVersion: "2020-11-01",
networkInterfaceConfigurations: [
{
name: "{nic-config-name}",
deleteOption: "Delete",
ipConfigurations: [
{
name: "{ip-config-name}",
primary: true,
publicIPAddressConfiguration: {
name: "{publicIP-config-name}",
deleteOption: "Detach",
dnsSettings: {
domainNameLabel: "aaaaa",
domainNameLabelScope: "TenantReuse",
},
publicIPAllocationMethod: "Static",
sku: { name: "Basic", tier: "Global" },
},
},
],
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithNetworkInterfaceConfigurationDnsSettings.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkApiVersion = NetworkApiVersion.TwoThousandTwenty1101,
NetworkInterfaceConfigurations =
{
new VirtualMachineNetworkInterfaceConfiguration("{nic-config-name}")
{
Primary = true,
DeleteOption = ComputeDeleteOption.Delete,
IPConfigurations =
{
new VirtualMachineNetworkInterfaceIPConfiguration("{ip-config-name}")
{
Primary = true,
PublicIPAddressConfiguration = new VirtualMachinePublicIPAddressConfiguration("{publicIP-config-name}")
{
Sku = new ComputePublicIPAddressSku()
{
Name = ComputePublicIPAddressSkuName.Basic,
Tier = ComputePublicIPAddressSkuTier.Global,
},
DeleteOption = ComputeDeleteOption.Detach,
DnsSettings = new VirtualMachinePublicIPAddressDnsSettingsConfiguration("aaaaa")
{
DomainNameLabelScope = DomainNameLabelScopeType.TenantReuse,
},
PublicIPAllocationMethod = PublicIPAllocationMethod.Static,
},
}
},
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/toBeCreatedNetworkInterface",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"vmId": "b7a098cc-b0b8-46e8-a205-62f301a62a8f",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/toBeCreatedNetworkInterface",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"vmId": "b7a098cc-b0b8-46e8-a205-62f301a62a8f",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a vm with password authentication.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithPasswordAuthentication.json
*/
/**
* Sample code: Create a vm with password authentication.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithPasswordAuthentication(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_password_authentication.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithPasswordAuthentication.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithPasswordAuthentication.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithPasswordAuthentication() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("b248db33-62ba-4d2d-b791-811e075ee0f5"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithPasswordAuthentication.json
*/
async function createAVMWithPasswordAuthentication() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithPasswordAuthentication.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"vmId": "b248db33-62ba-4d2d-b791-811e075ee0f5",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
},
"dataDisks": []
},
"vmId": "b248db33-62ba-4d2d-b791-811e075ee0f5",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a vm with premium storage.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Premium_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithPremiumStorage.json
*/
/**
* Sample code: Create a vm with premium storage.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithPremiumStorage(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.PREMIUM_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true)))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_premium_storage.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Premium_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithPremiumStorage.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithPremiumStorage.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithPremiumStorage() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2016-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesPremiumLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardDS1V2),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2016-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadWrite),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesPremiumLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("a149cd25-409f-41af-8088-275f5486bc93"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithPremiumStorage.json
*/
async function createAVMWithPremiumStorage() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D1_v2" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
storageProfile: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Premium_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithPremiumStorage.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD1V2,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.PremiumLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Premium_LRS"
}
},
"dataDisks": []
},
"vmId": "a149cd25-409f-41af-8088-275f5486bc93",
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"type": "Microsoft.Compute/virtualMachines",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"managedDisk": {
"storageAccountType": "Premium_LRS"
}
},
"dataDisks": []
},
"vmId": "a149cd25-409f-41af-8088-275f5486bc93",
"hardwareProfile": {
"vmSize": "Standard_DS1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a VM with ProxyAgent Settings of enabled and mode.
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"securityProfile": {
"proxyAgentSettings": {
"enabled": true,
"mode": "Enforce"
}
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2019-Datacenter",
"version": "latest"
},
"osDisk": {
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.Mode;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.ProxyAgentSettings;
import com.azure.resourcemanager.compute.models.SecurityProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithProxyAgentSettings.json
*/
/**
* Sample code: Create a VM with ProxyAgent Settings of enabled and mode.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void
createAVMWithProxyAgentSettingsOfEnabledAndMode(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D2S_V3))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2019-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_ONLY)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_SSD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true))))
.withSecurityProfile(new SecurityProfile()
.withProxyAgentSettings(new ProxyAgentSettings().withEnabled(true).withMode(Mode.ENFORCE))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_proxy_agent_settings.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"securityProfile": {"proxyAgentSettings": {"enabled": True, "mode": "Enforce"}},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2019-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "StandardSSD_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithProxyAgentSettings.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithProxyAgentSettings.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithProxyAgentSettingsOfEnabledAndMode() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
SecurityProfile: &armcompute.SecurityProfile{
ProxyAgentSettings: &armcompute.ProxyAgentSettings{
Enabled: to.Ptr(true),
Mode: to.Ptr(armcompute.ModeEnforce),
},
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("WindowsServer"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("2019-Datacenter"),
Version: to.Ptr("latest"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadOnly),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardSSDLRS),
},
},
},
},
}, &armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions{IfMatch: nil,
IfNoneMatch: nil,
})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// You could use response here. We use blank identifier for just demo purposes.
_ = res
// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// res.VirtualMachine = armcompute.VirtualMachine{
// Name: to.Ptr("myVM"),
// Type: to.Ptr("Microsoft.Compute/virtualMachines"),
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM"),
// Location: to.Ptr("westus"),
// Properties: &armcompute.VirtualMachineProperties{
// HardwareProfile: &armcompute.HardwareProfile{
// VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3),
// },
// NetworkProfile: &armcompute.NetworkProfile{
// NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
// {
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
// Properties: &armcompute.NetworkInterfaceReferenceProperties{
// Primary: to.Ptr(true),
// },
// }},
// },
// OSProfile: &armcompute.OSProfile{
// AdminUsername: to.Ptr("{your-username}"),
// ComputerName: to.Ptr("myVM"),
// Secrets: []*armcompute.VaultSecretGroup{
// },
// WindowsConfiguration: &armcompute.WindowsConfiguration{
// EnableAutomaticUpdates: to.Ptr(true),
// ProvisionVMAgent: to.Ptr(true),
// },
// },
// ProvisioningState: to.Ptr("Succeeded"),
// SecurityProfile: &armcompute.SecurityProfile{
// ProxyAgentSettings: &armcompute.ProxyAgentSettings{
// Enabled: to.Ptr(true),
// Mode: to.Ptr(armcompute.ModeEnforce),
// },
// },
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("WindowsServer"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("2019-Datacenter"),
// Version: to.Ptr("latest"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadOnly),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardSSDLRS),
// },
// OSType: to.Ptr(armcompute.OperatingSystemTypesWindows),
// },
// },
// VMID: to.Ptr("5c0d55a7-c407-4ed6-bf7d-ddb810267c85"),
// },
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ComputeManagementClient } = require("@azure/arm-compute");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
*
* @summary The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithProxyAgentSettings.json
*/
async function createAVMWithProxyAgentSettingsOfEnabledAndMode() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
hardwareProfile: { vmSize: "Standard_D2s_v3" },
location: "westus",
networkProfile: {
networkInterfaces: [
{
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
},
securityProfile: { proxyAgentSettings: { enabled: true, mode: "Enforce" } },
storageProfile: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2019-Datacenter",
version: "latest",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadOnly",
createOption: "FromImage",
managedDisk: { storageAccountType: "StandardSSD_LRS" },
},
},
};
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginCreateOrUpdateAndWait(
resourceGroupName,
vmName,
parameters,
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
// Generated from example definition: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithProxyAgentSettings.json
// this example is just showing the usage of "VirtualMachines_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "{subscription-id}";
string resourceGroupName = "myResourceGroup";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this VirtualMachineResource
VirtualMachineCollection collection = resourceGroupResource.GetVirtualMachines();
// invoke the operation
string vmName = "myVM";
VirtualMachineData data = new VirtualMachineData(new AzureLocation("westus"))
{
HardwareProfile = new VirtualMachineHardwareProfile()
{
VmSize = VirtualMachineSizeType.StandardD2SV3,
},
StorageProfile = new VirtualMachineStorageProfile()
{
ImageReference = new ImageReference()
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2019-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadOnly,
ManagedDisk = new VirtualMachineManagedDisk()
{
StorageAccountType = StorageAccountType.StandardSsdLrs,
},
},
},
OSProfile = new VirtualMachineOSProfile()
{
ComputerName = "myVM",
AdminUsername = "{your-username}",
AdminPassword = "{your-password}",
},
NetworkProfile = new VirtualMachineNetworkProfile()
{
NetworkInterfaces =
{
new VirtualMachineNetworkInterfaceReference()
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
}
},
},
SecurityProfile = new SecurityProfile()
{
ProxyAgentSettings = new ProxyAgentSettings()
{
Enabled = true,
Mode = Mode.Enforce,
},
},
};
ArmOperation<VirtualMachineResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, vmName, data);
VirtualMachineResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
VirtualMachineData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2019-Datacenter",
"version": "latest"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"proxyAgentSettings": {
"enabled": true,
"mode": "Enforce"
}
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"provisioningState": "Creating"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
{
"name": "myVM",
"properties": {
"osProfile": {
"adminUsername": "{your-username}",
"secrets": [],
"computerName": "myVM",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"properties": {
"primary": true
}
}
]
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "2019-Datacenter",
"version": "latest"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"proxyAgentSettings": {
"enabled": true,
"mode": "Enforce"
}
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_D2s_v3"
},
"provisioningState": "Creating"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
Create a vm with Scheduled Events Profile
Sample request
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-07-01
{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"scheduledEventsPolicy": {
"scheduledEventsAdditionalPublishingTargets": {
"eventGridAndResourceGraph": {
"enable": true
}
},
"userInitiatedRedeploy": {
"automaticallyApprove": true
},
"userInitiatedReboot": {
"automaticallyApprove": true
}
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
"enabled": true
}
},
"scheduledEventsProfile": {
"terminateNotificationProfile": {
"notBeforeTimeout": "PT10M",
"enable": true
},
"osImageNotificationProfile": {
"notBeforeTimeout": "PT15M",
"enable": true
}
}
}
}
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.BootDiagnostics;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DiagnosticsProfile;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.EventGridAndResourceGraph;
import com.azure.resourcemanager.compute.models.HardwareProfile;
import com.azure.resourcemanager.compute.models.ImageReference;
import com.azure.resourcemanager.compute.models.ManagedDiskParameters;
import com.azure.resourcemanager.compute.models.NetworkInterfaceReference;
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.OSDisk;
import com.azure.resourcemanager.compute.models.OSImageNotificationProfile;
import com.azure.resourcemanager.compute.models.OSProfile;
import com.azure.resourcemanager.compute.models.ScheduledEventsAdditionalPublishingTargets;
import com.azure.resourcemanager.compute.models.ScheduledEventsPolicy;
import com.azure.resourcemanager.compute.models.ScheduledEventsProfile;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.TerminateNotificationProfile;
import com.azure.resourcemanager.compute.models.UserInitiatedReboot;
import com.azure.resourcemanager.compute.models.UserInitiatedRedeploy;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for VirtualMachines CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/
* virtualMachineExamples/VirtualMachine_Create_WithScheduledEventsProfile.json
*/
/**
* Sample code: Create a vm with Scheduled Events Profile.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithScheduledEventsProfile(com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(new HardwareProfile().withVmSize(VirtualMachineSizeTypes.STANDARD_D1_V2))
.withScheduledEventsPolicy(new ScheduledEventsPolicy()
.withUserInitiatedRedeploy(new UserInitiatedRedeploy().withAutomaticallyApprove(true))
.withUserInitiatedReboot(new UserInitiatedReboot().withAutomaticallyApprove(true))
.withScheduledEventsAdditionalPublishingTargets(new ScheduledEventsAdditionalPublishingTargets()
.withEventGridAndResourceGraph(new EventGridAndResourceGraph().withEnable(true))))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.withOsProfile(new OSProfile().withComputerName("myVM").withAdminUsername("{your-username}")
.withAdminPassword("fakeTokenPlaceholder"))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}")
.withPrimary(true))))
.withDiagnosticsProfile(new DiagnosticsProfile().withBootDiagnostics(new BootDiagnostics()
.withEnabled(true).withStorageUri("http://{existing-storage-account-name}.blob.core.windows.net")))
.withScheduledEventsProfile(new ScheduledEventsProfile()
.withTerminateNotificationProfile(
new TerminateNotificationProfile().withNotBeforeTimeout("PT10M").withEnable(true))
.withOsImageNotificationProfile(
new OSImageNotificationProfile().withNotBeforeTimeout("PT15M").withEnable(true))),
null, null, com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_scheduled_events_profile.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": True,
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
}
},
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"scheduledEventsPolicy": {
"scheduledEventsAdditionalPublishingTargets": {"eventGridAndResourceGraph": {"enable": True}},
"userInitiatedReboot": {"automaticallyApprove": True},
"userInitiatedRedeploy": {"automaticallyApprove": True},
},
"scheduledEventsProfile": {
"osImageNotificationProfile": {"enable": True, "notBeforeTimeout": "PT15M"},
"terminateNotificationProfile": {"enable": True, "notBeforeTimeout": "PT10M"},
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithScheduledEventsProfile.json
if __name__ == "__main__":
main()
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armcompute_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/c7b98b36e4023331545051284d8500adf98f02fe/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithScheduledEventsProfile.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithScheduledEventsProfile() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcompute.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myVM", armcompute.VirtualMachine{
Location: to.Ptr("westus"),
Properties: &armcompute.VirtualMachineProperties{
DiagnosticsProfile: &armcompute.DiagnosticsProfile{
BootDiagnostics: &armcompute.BootDiagnostics{
Enabled: to.Ptr(true),
StorageURI: to.Ptr("http://{existing-storage-account-name}.blob.core.windows.net"),
},
},
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD1V2),
},
NetworkProfile: &armcompute.NetworkProfile{
NetworkInterfaces: []*armcompute.NetworkInterfaceReference{
{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
},
ScheduledEventsPolicy: &armcompute.ScheduledEventsPolicy{
ScheduledEventsAdditionalPublishingTargets: &armcompute.ScheduledEventsAdditionalPublishingTargets{
EventGridAndResourceGraph: &armcompute.EventGridAndResourceGraph{
Enable: to.Ptr(true),
},
},
UserInitiatedReboot: &armcompute.UserInitiatedReboot{
AutomaticallyApprove: to.Ptr(true),
},
UserInitia