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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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 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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/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),
},
UserInitiatedRedeploy: &armcompute.UserInitiatedRedeploy{
AutomaticallyApprove: to.Ptr(true),
},
},
ScheduledEventsProfile: &armcompute.ScheduledEventsProfile{
OSImageNotificationProfile: &armcompute.OSImageNotificationProfile{
Enable: to.Ptr(true),
NotBeforeTimeout: to.Ptr("PT15M"),
},
TerminateNotificationProfile: &armcompute.TerminateNotificationProfile{
Enable: to.Ptr(true),
NotBeforeTimeout: to.Ptr("PT10M"),
},
},
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"),
// 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),
// },
// },
// ScheduledEventsProfile: &armcompute.ScheduledEventsProfile{
// OSImageNotificationProfile: &armcompute.OSImageNotificationProfile{
// Enable: to.Ptr(true),
// NotBeforeTimeout: to.Ptr("PT15M"),
// },
// TerminateNotificationProfile: &armcompute.TerminateNotificationProfile{
// Enable: to.Ptr(true),
// NotBeforeTimeout: to.Ptr("PT10M"),
// },
// },
// 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_WithScheduledEventsProfile.json
*/
async function createAVMWithScheduledEventsProfile() {
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",
},
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: {
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_WithScheduledEventsProfile.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,
},
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,
},
},
},
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"),
},
ScheduledEventsProfile = new ComputeScheduledEventsProfile
{
TerminateNotificationProfile = new TerminateNotificationProfile
{
NotBeforeTimeout = "PT10M",
Enable = true,
},
OSImageNotificationProfile = new OSImageNotificationProfile
{
NotBeforeTimeout = "PT15M",
Enable = 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": {
"storageUri": "http://nsgdiagnostic.blob.core.windows.net",
"enabled": true
}
},
"vmId": "676420ba-7a24-4bfe-80bd-9c841ee184fa",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"scheduledEventsPolicy": {
"scheduledEventsAdditionalPublishingTargets": {
"eventGridAndResourceGraph": {
"enable": true
}
},
"userInitiatedRedeploy": {
"automaticallyApprove": true
},
"userInitiatedReboot": {
"automaticallyApprove": true
}
},
"scheduledEventsProfile": {
"terminateNotificationProfile": {
"notBeforeTimeout": "PT10M",
"enable": true
},
"osImageNotificationProfile": {
"notBeforeTimeout": "PT15M",
"enable": true
}
},
"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"
},
"scheduledEventsPolicy": {
"scheduledEventsAdditionalPublishingTargets": {
"eventGridAndResourceGraph": {
"enable": true
}
},
"userInitiatedRedeploy": {
"automaticallyApprove": true
},
"userInitiatedReboot": {
"automaticallyApprove": true
}
},
"scheduledEventsProfile": {
"terminateNotificationProfile": {
"notBeforeTimeout": "PT10M",
"enable": true
},
"osImageNotificationProfile": {
"notBeforeTimeout": "PT15M",
"enable": true
}
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a VM with securityType ConfidentialVM with Customer Managed Keys
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_DC2as_v5"
},
"securityProfile": {
"uefiSettings": {
"secureBootEnabled": true,
"vTpmEnabled": true
},
"securityType": "ConfidentialVM"
},
"storageProfile": {
"imageReference": {
"sku": "windows-cvm",
"publisher": "MicrosoftWindowsServer",
"version": "17763.2183.2109130127",
"offer": "2019-datacenter-cvm"
},
"osDisk": {
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS",
"securityProfile": {
"securityEncryptionType": "DiskWithVMGuestState",
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
}
}
},
"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.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.SecurityEncryptionTypes;
import com.azure.resourcemanager.compute.models.SecurityProfile;
import com.azure.resourcemanager.compute.models.SecurityTypes;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.UefiSettings;
import com.azure.resourcemanager.compute.models.VMDiskSecurityProfile;
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_WithSecurityTypeConfidentialVMWithCustomerManagedKeys.json
*/
/**
* Sample code: Create a VM with securityType ConfidentialVM with Customer Managed Keys.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVMWithSecurityTypeConfidentialVMWithCustomerManagedKeys(
com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(
new HardwareProfile().withVmSize(VirtualMachineSizeTypes.fromString("Standard_DC2as_v5")))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("2019-datacenter-cvm").withSku("windows-cvm").withVersion("17763.2183.2109130127"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_ONLY)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE)
.withManagedDisk(new ManagedDiskParameters()
.withStorageAccountType(StorageAccountTypes.STANDARD_SSD_LRS)
.withSecurityProfile(new VMDiskSecurityProfile()
.withSecurityEncryptionType(SecurityEncryptionTypes.DISK_WITH_VMGUEST_STATE)
.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))))
.withSecurityProfile(new SecurityProfile()
.withUefiSettings(new UefiSettings().withSecureBootEnabled(true).withVTpmEnabled(true))
.withSecurityType(SecurityTypes.CONFIDENTIAL_VM)),
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 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_security_type_confidential_vm_with_customer_managed_keys.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_DC2as_v5"},
"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": {
"securityType": "ConfidentialVM",
"uefiSettings": {"secureBootEnabled": True, "vTpmEnabled": True},
},
"storageProfile": {
"imageReference": {
"offer": "2019-datacenter-cvm",
"publisher": "MicrosoftWindowsServer",
"sku": "windows-cvm",
"version": "17763.2183.2109130127",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"managedDisk": {
"securityProfile": {
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
},
"securityEncryptionType": "DiskWithVMGuestState",
},
"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_WithSecurityTypeConfidentialVMWithCustomerManagedKeys.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithSecurityTypeConfidentialVMWithCustomerManagedKeys.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithSecurityTypeConfidentialVmWithCustomerManagedKeys() {
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.VirtualMachineSizeTypes("Standard_DC2as_v5")),
},
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{
SecurityType: to.Ptr(armcompute.SecurityTypesConfidentialVM),
UefiSettings: &armcompute.UefiSettings{
SecureBootEnabled: to.Ptr(true),
VTpmEnabled: to.Ptr(true),
},
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("2019-datacenter-cvm"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("windows-cvm"),
Version: to.Ptr("17763.2183.2109130127"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadOnly),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
SecurityProfile: &armcompute.VMDiskSecurityProfile{
DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"),
},
SecurityEncryptionType: to.Ptr(armcompute.SecurityEncryptionTypesDiskWithVMGuestState),
},
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.VirtualMachineSizeTypes("Standard_DC2as_v5")),
// },
// 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{
// SecurityType: to.Ptr(armcompute.SecurityTypesConfidentialVM),
// UefiSettings: &armcompute.UefiSettings{
// SecureBootEnabled: to.Ptr(true),
// VTpmEnabled: to.Ptr(true),
// },
// },
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("2019-datacenter-cvm"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("windows-cvm"),
// Version: to.Ptr("17763.2183.2109130127"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadOnly),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// SecurityProfile: &armcompute.VMDiskSecurityProfile{
// DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"),
// },
// SecurityEncryptionType: to.Ptr(armcompute.SecurityEncryptionTypesDiskWithVMGuestState),
// },
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardSSDLRS),
// },
// },
// },
// 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_WithSecurityTypeConfidentialVMWithCustomerManagedKeys.json
*/
async function createAVMWithSecurityTypeConfidentialVMWithCustomerManagedKeys() {
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_DC2as_v5" },
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: {
securityType: "ConfidentialVM",
uefiSettings: { secureBootEnabled: true, vTpmEnabled: true },
},
storageProfile: {
imageReference: {
offer: "2019-datacenter-cvm",
publisher: "MicrosoftWindowsServer",
sku: "windows-cvm",
version: "17763.2183.2109130127",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadOnly",
createOption: "FromImage",
managedDisk: {
securityProfile: {
diskEncryptionSet: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}",
},
securityEncryptionType: "DiskWithVMGuestState",
},
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_WithSecurityTypeConfidentialVMWithCustomerManagedKeys.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 = new VirtualMachineSizeType("Standard_DC2as_v5"),
},
StorageProfile = new VirtualMachineStorageProfile
{
ImageReference = new ImageReference
{
Publisher = "MicrosoftWindowsServer",
Offer = "2019-datacenter-cvm",
Sku = "windows-cvm",
Version = "17763.2183.2109130127",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadOnly,
ManagedDisk = new VirtualMachineManagedDisk
{
StorageAccountType = StorageAccountType.StandardSsdLrs,
SecurityProfile = new VirtualMachineDiskSecurityProfile
{
SecurityEncryptionType = SecurityEncryptionType.DiskWithVmGuestState,
DiskEncryptionSetId = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-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}"),
}},
},
SecurityProfile = new SecurityProfile
{
UefiSettings = new UefiSettings
{
IsSecureBootEnabled = true,
IsVirtualTpmEnabled = true,
},
SecurityType = SecurityType.ConfidentialVm,
},
};
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": "windows-cvm",
"publisher": "MicrosoftWindowsServer",
"version": "17763.2183.2109130127",
"offer": "2019-datacenter-cvm"
},
"osDisk": {
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS",
"securityProfile": {
"securityEncryptionType": "DiskWithVMGuestState",
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
}
}
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"uefiSettings": {
"secureBootEnabled": true,
"vTpmEnabled": true
},
"securityType": "ConfidentialVM"
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DC2as_v5"
},
"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": {
"sku": "windows-cvm",
"publisher": "MicrosoftWindowsServer",
"version": "17763.2183.2109130127",
"offer": "2019-datacenter-cvm"
},
"osDisk": {
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS",
"securityProfile": {
"securityEncryptionType": "DiskWithVMGuestState",
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
}
}
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"uefiSettings": {
"secureBootEnabled": true,
"vTpmEnabled": true
},
"securityType": "ConfidentialVM"
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DC2as_v5"
},
"provisioningState": "Creating"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
Create a VM with securityType ConfidentialVM with NonPersistedTPM securityEncryptionType
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_DC2es_v5"
},
"securityProfile": {
"uefiSettings": {
"secureBootEnabled": false,
"vTpmEnabled": true
},
"securityType": "ConfidentialVM"
},
"storageProfile": {
"imageReference": {
"sku": "linux-cvm",
"publisher": "UbuntuServer",
"version": "17763.2183.2109130127",
"offer": "2022-datacenter-cvm"
},
"osDisk": {
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS",
"securityProfile": {
"securityEncryptionType": "NonPersistedTPM"
}
},
"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.SecurityEncryptionTypes;
import com.azure.resourcemanager.compute.models.SecurityProfile;
import com.azure.resourcemanager.compute.models.SecurityTypes;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.UefiSettings;
import com.azure.resourcemanager.compute.models.VMDiskSecurityProfile;
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_WithSecurityTypeConfidentialVMWithNonPersistedTPM.json
*/
/**
* Sample code: Create a VM with securityType ConfidentialVM with NonPersistedTPM securityEncryptionType.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVMWithSecurityTypeConfidentialVMWithNonPersistedTPMSecurityEncryptionType(
com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(
new HardwareProfile().withVmSize(VirtualMachineSizeTypes.fromString("Standard_DC2es_v5")))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("UbuntuServer")
.withOffer("2022-datacenter-cvm").withSku("linux-cvm").withVersion("17763.2183.2109130127"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_ONLY)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_SSD_LRS)
.withSecurityProfile(new VMDiskSecurityProfile()
.withSecurityEncryptionType(SecurityEncryptionTypes.NON_PERSISTED_TPM)))))
.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()
.withUefiSettings(new UefiSettings().withSecureBootEnabled(false).withVTpmEnabled(true))
.withSecurityType(SecurityTypes.CONFIDENTIAL_VM)),
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 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_security_type_confidential_vm_with_non_persisted_tpm.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_DC2es_v5"},
"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": {
"securityType": "ConfidentialVM",
"uefiSettings": {"secureBootEnabled": False, "vTpmEnabled": True},
},
"storageProfile": {
"imageReference": {
"offer": "2022-datacenter-cvm",
"publisher": "UbuntuServer",
"sku": "linux-cvm",
"version": "17763.2183.2109130127",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"managedDisk": {
"securityProfile": {"securityEncryptionType": "NonPersistedTPM"},
"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_WithSecurityTypeConfidentialVMWithNonPersistedTPM.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithSecurityTypeConfidentialVMWithNonPersistedTPM.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithSecurityTypeConfidentialVmWithNonPersistedTpmSecurityEncryptionType() {
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.VirtualMachineSizeTypes("Standard_DC2es_v5")),
},
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{
SecurityType: to.Ptr(armcompute.SecurityTypesConfidentialVM),
UefiSettings: &armcompute.UefiSettings{
SecureBootEnabled: to.Ptr(false),
VTpmEnabled: to.Ptr(true),
},
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("2022-datacenter-cvm"),
Publisher: to.Ptr("UbuntuServer"),
SKU: to.Ptr("linux-cvm"),
Version: to.Ptr("17763.2183.2109130127"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadOnly),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
SecurityProfile: &armcompute.VMDiskSecurityProfile{
SecurityEncryptionType: to.Ptr(armcompute.SecurityEncryptionTypesNonPersistedTPM),
},
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.VirtualMachineSizeTypes("Standard_DC2es_v5")),
// },
// 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{
// SecurityType: to.Ptr(armcompute.SecurityTypesConfidentialVM),
// UefiSettings: &armcompute.UefiSettings{
// SecureBootEnabled: to.Ptr(false),
// VTpmEnabled: to.Ptr(true),
// },
// },
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("2022-datacenter-cvm"),
// Publisher: to.Ptr("UbuntuServer"),
// SKU: to.Ptr("linux-cvm"),
// Version: to.Ptr("17763.2183.2109130127"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadOnly),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// SecurityProfile: &armcompute.VMDiskSecurityProfile{
// SecurityEncryptionType: to.Ptr(armcompute.SecurityEncryptionTypesNonPersistedTPM),
// },
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardSSDLRS),
// },
// },
// },
// 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_WithSecurityTypeConfidentialVMWithNonPersistedTPM.json
*/
async function createAVMWithSecurityTypeConfidentialVMWithNonPersistedTpmSecurityEncryptionType() {
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_DC2es_v5" },
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: {
securityType: "ConfidentialVM",
uefiSettings: { secureBootEnabled: false, vTpmEnabled: true },
},
storageProfile: {
imageReference: {
offer: "2022-datacenter-cvm",
publisher: "UbuntuServer",
sku: "linux-cvm",
version: "17763.2183.2109130127",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadOnly",
createOption: "FromImage",
managedDisk: {
securityProfile: { securityEncryptionType: "NonPersistedTPM" },
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_WithSecurityTypeConfidentialVMWithNonPersistedTPM.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 = new VirtualMachineSizeType("Standard_DC2es_v5"),
},
StorageProfile = new VirtualMachineStorageProfile
{
ImageReference = new ImageReference
{
Publisher = "UbuntuServer",
Offer = "2022-datacenter-cvm",
Sku = "linux-cvm",
Version = "17763.2183.2109130127",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadOnly,
ManagedDisk = new VirtualMachineManagedDisk
{
StorageAccountType = StorageAccountType.StandardSsdLrs,
SecurityProfile = new VirtualMachineDiskSecurityProfile
{
SecurityEncryptionType = SecurityEncryptionType.NonPersistedTPM,
},
},
},
},
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
{
UefiSettings = new UefiSettings
{
IsSecureBootEnabled = false,
IsVirtualTpmEnabled = true,
},
SecurityType = SecurityType.ConfidentialVm,
},
};
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": "linux-cvm",
"publisher": "UbuntuServer",
"version": "17763.2183.2109130127",
"offer": "2022-datacenter-cvm"
},
"osDisk": {
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS",
"securityProfile": {
"securityEncryptionType": "NonPersistedTPM"
}
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"uefiSettings": {
"secureBootEnabled": false,
"vTpmEnabled": true
},
"securityType": "ConfidentialVM"
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DC2es_v5"
},
"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": {
"sku": "linux-cvm",
"publisher": "UbuntuServer",
"version": "17763.2183.2109130127",
"offer": "2022-datacenter-cvm"
},
"osDisk": {
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS",
"securityProfile": {
"securityEncryptionType": "NonPersistedTPM"
}
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"uefiSettings": {
"secureBootEnabled": false,
"vTpmEnabled": true
},
"securityType": "ConfidentialVM"
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DC2es_v5"
},
"provisioningState": "Creating"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/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_DC2as_v5"
},
"securityProfile": {
"uefiSettings": {
"secureBootEnabled": true,
"vTpmEnabled": true
},
"securityType": "ConfidentialVM"
},
"storageProfile": {
"imageReference": {
"sku": "windows-cvm",
"publisher": "MicrosoftWindowsServer",
"version": "17763.2183.2109130127",
"offer": "2019-datacenter-cvm"
},
"osDisk": {
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS",
"securityProfile": {
"securityEncryptionType": "DiskWithVMGuestState"
}
},
"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.SecurityEncryptionTypes;
import com.azure.resourcemanager.compute.models.SecurityProfile;
import com.azure.resourcemanager.compute.models.SecurityTypes;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.UefiSettings;
import com.azure.resourcemanager.compute.models.VMDiskSecurityProfile;
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_WithSecurityTypeConfidentialVM.json
*/
/**
* Sample code: Create a VM with securityType ConfidentialVM with Platform Managed Keys.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVMWithSecurityTypeConfidentialVMWithPlatformManagedKeys(
com.azure.resourcemanager.AzureResourceManager azure) {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().createOrUpdate("myResourceGroup", "myVM",
new VirtualMachineInner().withLocation("westus")
.withHardwareProfile(
new HardwareProfile().withVmSize(VirtualMachineSizeTypes.fromString("Standard_DC2as_v5")))
.withStorageProfile(new StorageProfile()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("2019-datacenter-cvm").withSku("windows-cvm").withVersion("17763.2183.2109130127"))
.withOsDisk(new OSDisk().withName("myVMosdisk").withCaching(CachingTypes.READ_ONLY)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_SSD_LRS)
.withSecurityProfile(new VMDiskSecurityProfile()
.withSecurityEncryptionType(SecurityEncryptionTypes.DISK_WITH_VMGUEST_STATE)))))
.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()
.withUefiSettings(new UefiSettings().withSecureBootEnabled(true).withVTpmEnabled(true))
.withSecurityType(SecurityTypes.CONFIDENTIAL_VM)),
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 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_security_type_confidential_vm.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_DC2as_v5"},
"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": {
"securityType": "ConfidentialVM",
"uefiSettings": {"secureBootEnabled": True, "vTpmEnabled": True},
},
"storageProfile": {
"imageReference": {
"offer": "2019-datacenter-cvm",
"publisher": "MicrosoftWindowsServer",
"sku": "windows-cvm",
"version": "17763.2183.2109130127",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"managedDisk": {
"securityProfile": {"securityEncryptionType": "DiskWithVMGuestState"},
"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_WithSecurityTypeConfidentialVM.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithSecurityTypeConfidentialVM.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithSecurityTypeConfidentialVmWithPlatformManagedKeys() {
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.VirtualMachineSizeTypes("Standard_DC2as_v5")),
},
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{
SecurityType: to.Ptr(armcompute.SecurityTypesConfidentialVM),
UefiSettings: &armcompute.UefiSettings{
SecureBootEnabled: to.Ptr(true),
VTpmEnabled: to.Ptr(true),
},
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("2019-datacenter-cvm"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("windows-cvm"),
Version: to.Ptr("17763.2183.2109130127"),
},
OSDisk: &armcompute.OSDisk{
Name: to.Ptr("myVMosdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadOnly),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
SecurityProfile: &armcompute.VMDiskSecurityProfile{
SecurityEncryptionType: to.Ptr(armcompute.SecurityEncryptionTypesDiskWithVMGuestState),
},
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.VirtualMachineSizeTypes("Standard_DC2as_v5")),
// },
// 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{
// SecurityType: to.Ptr(armcompute.SecurityTypesConfidentialVM),
// UefiSettings: &armcompute.UefiSettings{
// SecureBootEnabled: to.Ptr(true),
// VTpmEnabled: to.Ptr(true),
// },
// },
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("2019-datacenter-cvm"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("windows-cvm"),
// Version: to.Ptr("17763.2183.2109130127"),
// },
// OSDisk: &armcompute.OSDisk{
// Name: to.Ptr("myVMosdisk"),
// Caching: to.Ptr(armcompute.CachingTypesReadOnly),
// CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
// ManagedDisk: &armcompute.ManagedDiskParameters{
// SecurityProfile: &armcompute.VMDiskSecurityProfile{
// SecurityEncryptionType: to.Ptr(armcompute.SecurityEncryptionTypesDiskWithVMGuestState),
// },
// StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardSSDLRS),
// },
// },
// },
// 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_WithSecurityTypeConfidentialVM.json
*/
async function createAVMWithSecurityTypeConfidentialVMWithPlatformManagedKeys() {
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_DC2as_v5" },
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: {
securityType: "ConfidentialVM",
uefiSettings: { secureBootEnabled: true, vTpmEnabled: true },
},
storageProfile: {
imageReference: {
offer: "2019-datacenter-cvm",
publisher: "MicrosoftWindowsServer",
sku: "windows-cvm",
version: "17763.2183.2109130127",
},
osDisk: {
name: "myVMosdisk",
caching: "ReadOnly",
createOption: "FromImage",
managedDisk: {
securityProfile: { securityEncryptionType: "DiskWithVMGuestState" },
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_WithSecurityTypeConfidentialVM.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 = new VirtualMachineSizeType("Standard_DC2as_v5"),
},
StorageProfile = new VirtualMachineStorageProfile
{
ImageReference = new ImageReference
{
Publisher = "MicrosoftWindowsServer",
Offer = "2019-datacenter-cvm",
Sku = "windows-cvm",
Version = "17763.2183.2109130127",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "myVMosdisk",
Caching = CachingType.ReadOnly,
ManagedDisk = new VirtualMachineManagedDisk
{
StorageAccountType = StorageAccountType.StandardSsdLrs,
SecurityProfile = new VirtualMachineDiskSecurityProfile
{
SecurityEncryptionType = SecurityEncryptionType.DiskWithVmGuestState,
},
},
},
},
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
{
UefiSettings = new UefiSettings
{
IsSecureBootEnabled = true,
IsVirtualTpmEnabled = true,
},
SecurityType = SecurityType.ConfidentialVm,
},
};
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": "windows-cvm",
"publisher": "MicrosoftWindowsServer",
"version": "17763.2183.2109130127",
"offer": "2019-datacenter-cvm"
},
"osDisk": {
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS",
"securityProfile": {
"securityEncryptionType": "DiskWithVMGuestState"
}
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"uefiSettings": {
"secureBootEnabled": true,
"vTpmEnabled": true
},
"securityType": "ConfidentialVM"
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DC2as_v5"
},
"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": {
"sku": "windows-cvm",
"publisher": "MicrosoftWindowsServer",
"version": "17763.2183.2109130127",
"offer": "2019-datacenter-cvm"
},
"osDisk": {
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS",
"securityProfile": {
"securityEncryptionType": "DiskWithVMGuestState"
}
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"uefiSettings": {
"secureBootEnabled": true,
"vTpmEnabled": true
},
"securityType": "ConfidentialVM"
},
"vmId": "5c0d55a7-c407-4ed6-bf7d-ddb810267c85",
"hardwareProfile": {
"vmSize": "Standard_DC2as_v5"
},
"provisioningState": "Creating"
},
"type": "Microsoft.Compute/virtualMachines",
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM",
"location": "westus"
}
Create a vm with ssh 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": "{image_sku}",
"publisher": "{image_publisher}",
"version": "latest",
"offer": "{image_offer}"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"osProfile": {
"adminUsername": "{your-username}",
"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/{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.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.SshConfiguration;
import com.azure.resourcemanager.compute.models.SshPublicKey;
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_WithSshAuthentication.json
*/
/**
* Sample code: Create a vm with ssh authentication.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVmWithSshAuthentication(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}")
.withLinuxConfiguration(new LinuxConfiguration().withDisablePasswordAuthentication(true)
.withSsh(new SshConfiguration().withPublicKeys(
Arrays.asList(new SshPublicKey().withPath("/home/{your-username}/.ssh/authorized_keys")
.withKeyData("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 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_ssh_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": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"linuxConfiguration": {
"disablePasswordAuthentication": True,
"ssh": {
"publicKeys": [
{
"keyData": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCeClRAk2ipUs/l5voIsDC5q9RI+YSRd1Bvd/O+axgY4WiBzG+4FwJWZm/mLLe5DoOdHQwmU2FrKXZSW4w2sYE70KeWnrFViCOX5MTVvJgPE8ClugNl8RWth/tU849DvM9sT7vFgfVSHcAS2yDRyDlueii+8nF2ym8XWAPltFVCyLHRsyBp5YPqK8JFYIa1eybKsY3hEAxRCA+/7bq8et+Gj3coOsuRmrehav7rE6N12Pb80I6ofa6SM5XNYq4Xk0iYNx7R3kdz0Jj9XgZYWjAHjJmT0gTRoOnt6upOuxK7xI/ykWrllgpXrCPu3Ymz+c+ujaqcxDopnAl2lmf69/J1",
"path": "/home/{your-username}/.ssh/authorized_keys",
}
]
},
},
},
"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_WithSshAuthentication.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithSshAuthentication.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithSshAuthentication() {
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{
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"),
}},
},
},
},
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{
// 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_WithSshAuthentication.json
*/
async function createAVMWithSshAuthentication() {
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: {
adminUsername: "{your-username}",
computerName: "myVM",
linuxConfiguration: {
disablePasswordAuthentication: true,
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",
},
],
},
},
},
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_WithSshAuthentication.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}",
LinuxConfiguration = new LinuxConfiguration
{
IsPasswordAuthenticationDisabled = true,
SshPublicKeys = {new SshPublicKeyConfiguration
{
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",
}},
},
},
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": {
"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": []
},
"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": []
},
"vmId": "e0de9b84-a506-4b95-9623-00a425d05c90",
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a VM with Uefi Settings of secureBoot and vTPM.
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": {
"uefiSettings": {
"secureBootEnabled": true,
"vTpmEnabled": true
},
"securityType": "TrustedLaunch"
},
"storageProfile": {
"imageReference": {
"sku": "windows10-tvm",
"publisher": "MicrosoftWindowsServer",
"version": "18363.592.2001092016",
"offer": "windowsserver-gen2preview-preview"
},
"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.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.SecurityProfile;
import com.azure.resourcemanager.compute.models.SecurityTypes;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.UefiSettings;
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_WithUefiSettings.json
*/
/**
* Sample code: Create a VM with Uefi Settings of secureBoot and vTPM.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void
createAVMWithUefiSettingsOfSecureBootAndVTPM(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-gen2preview-preview")
.withSku("windows10-tvm").withVersion("18363.592.2001092016"))
.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()
.withUefiSettings(new UefiSettings().withSecureBootEnabled(true).withVTpmEnabled(true))
.withSecurityType(SecurityTypes.TRUSTED_LAUNCH)),
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 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_uefi_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": {
"securityType": "TrustedLaunch",
"uefiSettings": {"secureBootEnabled": True, "vTpmEnabled": True},
},
"storageProfile": {
"imageReference": {
"offer": "windowsserver-gen2preview-preview",
"publisher": "MicrosoftWindowsServer",
"sku": "windows10-tvm",
"version": "18363.592.2001092016",
},
"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_WithUefiSettings.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithUefiSettings.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithUefiSettingsOfSecureBootAndVTpm() {
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{
SecurityType: to.Ptr(armcompute.SecurityTypesTrustedLaunch),
UefiSettings: &armcompute.UefiSettings{
SecureBootEnabled: to.Ptr(true),
VTpmEnabled: to.Ptr(true),
},
},
StorageProfile: &armcompute.StorageProfile{
ImageReference: &armcompute.ImageReference{
Offer: to.Ptr("windowsserver-gen2preview-preview"),
Publisher: to.Ptr("MicrosoftWindowsServer"),
SKU: to.Ptr("windows10-tvm"),
Version: to.Ptr("18363.592.2001092016"),
},
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{
// SecurityType: to.Ptr(armcompute.SecurityTypesTrustedLaunch),
// UefiSettings: &armcompute.UefiSettings{
// SecureBootEnabled: to.Ptr(true),
// VTpmEnabled: to.Ptr(true),
// },
// },
// StorageProfile: &armcompute.StorageProfile{
// DataDisks: []*armcompute.DataDisk{
// },
// ImageReference: &armcompute.ImageReference{
// Offer: to.Ptr("windowsserver-gen2preview-preview"),
// Publisher: to.Ptr("MicrosoftWindowsServer"),
// SKU: to.Ptr("windows10-tvm"),
// Version: to.Ptr("18363.592.2001092016"),
// },
// 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_WithUefiSettings.json
*/
async function createAVMWithUefiSettingsOfSecureBootAndVTpm() {
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: {
securityType: "TrustedLaunch",
uefiSettings: { secureBootEnabled: true, vTpmEnabled: true },
},
storageProfile: {
imageReference: {
offer: "windowsserver-gen2preview-preview",
publisher: "MicrosoftWindowsServer",
sku: "windows10-tvm",
version: "18363.592.2001092016",
},
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_WithUefiSettings.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-gen2preview-preview",
Sku = "windows10-tvm",
Version = "18363.592.2001092016",
},
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
{
UefiSettings = new UefiSettings
{
IsSecureBootEnabled = true,
IsVirtualTpmEnabled = true,
},
SecurityType = SecurityType.TrustedLaunch,
},
};
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": "windows10-tvm",
"publisher": "MicrosoftWindowsServer",
"version": "18363.592.2001092016",
"offer": "windowsserver-gen2preview-preview"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"uefiSettings": {
"secureBootEnabled": true,
"vTpmEnabled": true
},
"securityType": "TrustedLaunch"
},
"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": {
"sku": "windows10-tvm",
"publisher": "MicrosoftWindowsServer",
"version": "18363.592.2001092016",
"offer": "windowsserver-gen2preview-preview"
},
"osDisk": {
"osType": "Windows",
"caching": "ReadOnly",
"managedDisk": {
"storageAccountType": "StandardSSD_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
},
"dataDisks": []
},
"securityProfile": {
"uefiSettings": {
"secureBootEnabled": true,
"vTpmEnabled": true
},
"securityType": "TrustedLaunch"
},
"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 UserData
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": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"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
}
},
"userData": "RXhhbXBsZSBVc2VyRGF0YQ=="
}
}
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_WithUserData.json
*/
/**
* Sample code: Create a VM with UserData.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVMWithUserData(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()
.withImageReference(new ImageReference().withPublisher("MicrosoftWindowsServer")
.withOffer("WindowsServer").withSku("2016-Datacenter").withVersion("latest"))
.withOsDisk(new OSDisk().withName("vmOSdisk").withCaching(CachingTypes.READ_WRITE)
.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE).withManagedDisk(
new ManagedDiskParameters().withStorageAccountType(StorageAccountTypes.STANDARD_LRS))))
.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")))
.withUserData("RXhhbXBsZSBVc2VyRGF0YQ=="),
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 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_user_data.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": {
"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": "{vm-name}",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "vmOSdisk",
},
},
"userData": "RXhhbXBsZSBVc2VyRGF0YQ==",
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithUserData.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithUserData.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithUserData() {
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{
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("{vm-name}"),
},
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("vmOSdisk"),
Caching: to.Ptr(armcompute.CachingTypesReadWrite),
CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),
ManagedDisk: &armcompute.ManagedDiskParameters{
StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),
},
},
},
UserData: to.Ptr("RXhhbXBsZSBVc2VyRGF0YQ=="),
},
}, &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("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("{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("2016-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_WithUserData.json
*/
async function createAVMWithUserData() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "{vm-name}";
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: "{vm-name}",
},
storageProfile: {
imageReference: {
offer: "WindowsServer",
publisher: "MicrosoftWindowsServer",
sku: "2016-Datacenter",
version: "latest",
},
osDisk: {
name: "vmOSdisk",
caching: "ReadWrite",
createOption: "FromImage",
managedDisk: { storageAccountType: "Standard_LRS" },
},
},
userData: "RXhhbXBsZSBVc2VyRGF0YQ==",
};
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_WithUserData.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
{
ImageReference = new ImageReference
{
Publisher = "MicrosoftWindowsServer",
Offer = "WindowsServer",
Sku = "2016-Datacenter",
Version = "latest",
},
OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
{
Name = "vmOSdisk",
Caching = CachingType.ReadWrite,
ManagedDisk = new VirtualMachineManagedDisk
{
StorageAccountType = StorageAccountType.StandardLrs,
},
},
},
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"),
},
UserData = "RXhhbXBsZSBVc2VyRGF0YQ==",
};
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": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"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_D1_v2"
},
"provisioningState": "Creating"
},
"name": "{vm-name}",
"location": "westus"
}
{
"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": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"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_D1_v2"
},
"provisioningState": "Creating"
},
"name": "{vm-name}",
"location": "westus"
}
Create a VM with VM Size Properties
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",
"vmSizeProperties": {
"vCPUsAvailable": 1,
"vCPUsPerCore": 1
}
},
"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
}
},
"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.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.VMSizeProperties;
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_WithVMSizeProperties.json
*/
/**
* Sample code: Create a VM with VM Size Properties.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAVMWithVMSizeProperties(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)
.withVmSizeProperties(new VMSizeProperties().withVCpusAvailable(1).withVCpusPerCore(1)))
.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")))
.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 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_vm_size_properties.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",
"vmSizeProperties": {"vCPUsAvailable": 1, "vCPUsPerCore": 1},
},
"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",
},
},
"userData": "U29tZSBDdXN0b20gRGF0YQ==",
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithVMSizeProperties.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithVMSizeProperties.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAVmWithVmSizeProperties() {
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),
VMSizeProperties: &armcompute.VMSizeProperties{
VCPUsAvailable: to.Ptr[int32](1),
VCPUsPerCore: to.Ptr[int32](1),
},
},
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),
},
},
},
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),
// VMSizeProperties: &armcompute.VMSizeProperties{
// VCPUsAvailable: to.Ptr[int32](1),
// VCPUsPerCore: to.Ptr[int32](1),
// },
// },
// 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_WithVMSizeProperties.json
*/
async function createAVMWithVMSizeProperties() {
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",
vmSizeProperties: { vCPUsAvailable: 1, vCPUsPerCore: 1 },
},
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" },
},
},
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_WithVMSizeProperties.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,
VmSizeProperties = new VirtualMachineSizeProperties
{
VCpusAvailable = 1,
VCpusPerCore = 1,
},
},
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"),
},
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": []
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://nsgdiagnostic.blob.core.windows.net",
"enabled": true
}
},
"vmId": "676420ba-7a24-4bfe-80bd-9c841ee184fa",
"hardwareProfile": {
"vmSize": "Standard_D4_v3",
"vmSizeProperties": {
"vCPUsAvailable": 1,
"vCPUsPerCore": 1
}
},
"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": []
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://nsgdiagnostic.blob.core.windows.net",
"enabled": true
}
},
"vmId": "676420ba-7a24-4bfe-80bd-9c841ee184fa",
"hardwareProfile": {
"vmSize": "Standard_D4_v3",
"vmSizeProperties": {
"vCPUsAvailable": 1,
"vCPUsPerCore": 1
}
},
"provisioningState": "Creating"
},
"name": "myVM",
"location": "westus"
}
Create a Windows 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_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}",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": 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.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.PatchSettings;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import com.azure.resourcemanager.compute.models.WindowsConfiguration;
import com.azure.resourcemanager.compute.models.WindowsPatchAssessmentMode;
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_WindowsVmWithPatchSettingAssessmentModeOfImageDefault.json
*/
/**
* Sample code: Create a Windows vm with a patch setting assessmentMode of ImageDefault.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAWindowsVmWithAPatchSettingAssessmentModeOfImageDefault(
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")
.withWindowsConfiguration(new WindowsConfiguration().withProvisionVMAgent(true)
.withEnableAutomaticUpdates(true).withPatchSettings(
new PatchSettings().withAssessmentMode(WindowsPatchAssessmentMode.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 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_windows_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_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",
"windowsConfiguration": {
"enableAutomaticUpdates": True,
"patchSettings": {"assessmentMode": "ImageDefault"},
"provisionVMAgent": True,
},
},
"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_WindowsVmWithPatchSettingAssessmentModeOfImageDefault.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WindowsVmWithPatchSettingAssessmentModeOfImageDefault.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAWindowsVmWithAPatchSettingAssessmentModeOfImageDefault() {
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"),
WindowsConfiguration: &armcompute.WindowsConfiguration{
EnableAutomaticUpdates: to.Ptr(true),
PatchSettings: &armcompute.PatchSettings{
AssessmentMode: to.Ptr(armcompute.WindowsPatchAssessmentModeImageDefault),
},
ProvisionVMAgent: to.Ptr(true),
},
},
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),
// PatchSettings: &armcompute.PatchSettings{
// AssessmentMode: to.Ptr(armcompute.WindowsPatchAssessmentModeImageDefault),
// },
// 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_WindowsVmWithPatchSettingAssessmentModeOfImageDefault.json
*/
async function createAWindowsVMWithAPatchSettingAssessmentModeOfImageDefault() {
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",
windowsConfiguration: {
enableAutomaticUpdates: true,
patchSettings: { assessmentMode: "ImageDefault" },
provisionVMAgent: true,
},
},
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_WindowsVmWithPatchSettingAssessmentModeOfImageDefault.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}",
WindowsConfiguration = new WindowsConfiguration
{
ProvisionVmAgent = true,
IsAutomaticUpdatesEnabled = true,
PatchSettings = new PatchSettings
{
AssessmentMode = WindowsPatchAssessmentMode.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",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true,
"patchSettings": {
"assessmentMode": "ImageDefault"
}
}
},
"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": false,
"patchSettings": {
"assessmentMode": "ImageDefault"
}
}
},
"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 Windows vm with a patch setting patchMode of AutomaticByOS.
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}",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true,
"patchSettings": {
"patchMode": "AutomaticByOS"
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic",
"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.PatchSettings;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import com.azure.resourcemanager.compute.models.WindowsConfiguration;
import com.azure.resourcemanager.compute.models.WindowsVMGuestPatchMode;
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_WindowsVmWithPatchSettingModeOfAutomaticByOS.json
*/
/**
* Sample code: Create a Windows vm with a patch setting patchMode of AutomaticByOS.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAWindowsVmWithAPatchSettingPatchModeOfAutomaticByOS(
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")
.withWindowsConfiguration(new WindowsConfiguration().withProvisionVMAgent(true)
.withEnableAutomaticUpdates(true)
.withPatchSettings(new PatchSettings().withPatchMode(WindowsVMGuestPatchMode.AUTOMATIC_BY_OS))))
.withNetworkProfile(
new NetworkProfile().withNetworkInterfaces(Arrays.asList(new NetworkInterfaceReference().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic")
.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 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_windows_vm_with_patch_setting_mode_of_automatic_by_os.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/nsgExistingNic",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
"windowsConfiguration": {
"enableAutomaticUpdates": True,
"patchSettings": {"patchMode": "AutomaticByOS"},
"provisionVMAgent": True,
},
},
"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_WindowsVmWithPatchSettingModeOfAutomaticByOS.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WindowsVmWithPatchSettingModeOfAutomaticByOS.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAWindowsVmWithAPatchSettingPatchModeOfAutomaticByOs() {
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/nsgExistingNic"),
Properties: &armcompute.NetworkInterfaceReferenceProperties{
Primary: to.Ptr(true),
},
}},
},
OSProfile: &armcompute.OSProfile{
AdminPassword: to.Ptr("{your-password}"),
AdminUsername: to.Ptr("{your-username}"),
ComputerName: to.Ptr("myVM"),
WindowsConfiguration: &armcompute.WindowsConfiguration{
EnableAutomaticUpdates: to.Ptr(true),
PatchSettings: &armcompute.PatchSettings{
PatchMode: to.Ptr(armcompute.WindowsVMGuestPatchModeAutomaticByOS),
},
ProvisionVMAgent: to.Ptr(true),
},
},
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),
// PatchSettings: &armcompute.PatchSettings{
// PatchMode: to.Ptr(armcompute.WindowsVMGuestPatchModeAutomaticByOS),
// },
// 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_WindowsVmWithPatchSettingModeOfAutomaticByOS.json
*/
async function createAWindowsVMWithAPatchSettingPatchModeOfAutomaticByOS() {
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/nsgExistingNic",
primary: true,
},
],
},
osProfile: {
adminPassword: "{your-password}",
adminUsername: "{your-username}",
computerName: "myVM",
windowsConfiguration: {
enableAutomaticUpdates: true,
patchSettings: { patchMode: "AutomaticByOS" },
provisionVMAgent: true,
},
},
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_WindowsVmWithPatchSettingModeOfAutomaticByOS.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}",
WindowsConfiguration = new WindowsConfiguration
{
ProvisionVmAgent = true,
IsAutomaticUpdatesEnabled = true,
PatchSettings = new PatchSettings
{
PatchMode = WindowsVmGuestPatchMode.AutomaticByOS,
},
},
},
NetworkProfile = new VirtualMachineNetworkProfile
{
NetworkInterfaces = {new VirtualMachineNetworkInterfaceReference
{
Primary = true,
Id = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nsgExistingNic"),
}},
},
};
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,
"patchSettings": {
"patchMode": "AutomaticByOS"
}
}
},
"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,
"patchSettings": {
"patchMode": "AutomaticByOS"
}
}
},
"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"
}
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}",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true,
"patchSettings": {
"patchMode": "AutomaticByPlatform",
"assessmentMode": "AutomaticByPlatform",
"automaticByPlatformSettings": {
"rebootSetting": "Never",
"bypassPlatformSafetyChecksOnUserSchedule": false
}
}
}
},
"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.PatchSettings;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import com.azure.resourcemanager.compute.models.WindowsConfiguration;
import com.azure.resourcemanager.compute.models.WindowsPatchAssessmentMode;
import com.azure.resourcemanager.compute.models.WindowsVMGuestPatchAutomaticByPlatformRebootSetting;
import com.azure.resourcemanager.compute.models.WindowsVMGuestPatchAutomaticByPlatformSettings;
import com.azure.resourcemanager.compute.models.WindowsVMGuestPatchMode;
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_WindowsVmWithAutomaticByPlatformSettings.json
*/
/**
* Sample code: Create a Windows 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 createAWindowsVmWithAPatchSettingPatchModeOfAutomaticByPlatformAndAutomaticByPlatformSettings(
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").withWindowsConfiguration(
new WindowsConfiguration().withProvisionVMAgent(true).withEnableAutomaticUpdates(true)
.withPatchSettings(new PatchSettings()
.withPatchMode(WindowsVMGuestPatchMode.AUTOMATIC_BY_PLATFORM)
.withAssessmentMode(WindowsPatchAssessmentMode.AUTOMATIC_BY_PLATFORM)
.withAutomaticByPlatformSettings(new WindowsVMGuestPatchAutomaticByPlatformSettings()
.withRebootSetting(WindowsVMGuestPatchAutomaticByPlatformRebootSetting.NEVER)
.withBypassPlatformSafetyChecksOnUserSchedule(false)))))
.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 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_windows_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_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",
"windowsConfiguration": {
"enableAutomaticUpdates": True,
"patchSettings": {
"assessmentMode": "AutomaticByPlatform",
"automaticByPlatformSettings": {
"bypassPlatformSafetyChecksOnUserSchedule": False,
"rebootSetting": "Never",
},
"patchMode": "AutomaticByPlatform",
},
"provisionVMAgent": True,
},
},
"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_WindowsVmWithAutomaticByPlatformSettings.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WindowsVmWithAutomaticByPlatformSettings.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAWindowsVmWithAPatchSettingPatchModeOfAutomaticByPlatformAndAutomaticByPlatformSettings() {
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"),
WindowsConfiguration: &armcompute.WindowsConfiguration{
EnableAutomaticUpdates: to.Ptr(true),
PatchSettings: &armcompute.PatchSettings{
AssessmentMode: to.Ptr(armcompute.WindowsPatchAssessmentModeAutomaticByPlatform),
AutomaticByPlatformSettings: &armcompute.WindowsVMGuestPatchAutomaticByPlatformSettings{
BypassPlatformSafetyChecksOnUserSchedule: to.Ptr(false),
RebootSetting: to.Ptr(armcompute.WindowsVMGuestPatchAutomaticByPlatformRebootSettingNever),
},
PatchMode: to.Ptr(armcompute.WindowsVMGuestPatchModeAutomaticByPlatform),
},
ProvisionVMAgent: to.Ptr(true),
},
},
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),
// PatchSettings: &armcompute.PatchSettings{
// AssessmentMode: to.Ptr(armcompute.WindowsPatchAssessmentModeAutomaticByPlatform),
// AutomaticByPlatformSettings: &armcompute.WindowsVMGuestPatchAutomaticByPlatformSettings{
// BypassPlatformSafetyChecksOnUserSchedule: to.Ptr(false),
// RebootSetting: to.Ptr(armcompute.WindowsVMGuestPatchAutomaticByPlatformRebootSettingNever),
// },
// PatchMode: to.Ptr(armcompute.WindowsVMGuestPatchModeAutomaticByPlatform),
// },
// 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_WindowsVmWithAutomaticByPlatformSettings.json
*/
async function createAWindowsVMWithAPatchSettingPatchModeOfAutomaticByPlatformAndAutomaticByPlatformSettings() {
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",
windowsConfiguration: {
enableAutomaticUpdates: true,
patchSettings: {
assessmentMode: "AutomaticByPlatform",
automaticByPlatformSettings: {
bypassPlatformSafetyChecksOnUserSchedule: false,
rebootSetting: "Never",
},
patchMode: "AutomaticByPlatform",
},
provisionVMAgent: true,
},
},
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_WindowsVmWithAutomaticByPlatformSettings.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}",
WindowsConfiguration = new WindowsConfiguration
{
ProvisionVmAgent = true,
IsAutomaticUpdatesEnabled = true,
PatchSettings = new PatchSettings
{
PatchMode = WindowsVmGuestPatchMode.AutomaticByPlatform,
AssessmentMode = WindowsPatchAssessmentMode.AutomaticByPlatform,
AutomaticByPlatformSettings = new WindowsVmGuestPatchAutomaticByPlatformSettings
{
RebootSetting = WindowsVmGuestPatchAutomaticByPlatformRebootSetting.Never,
BypassPlatformSafetyChecksOnUserSchedule = false,
},
},
},
},
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,
"patchSettings": {
"patchMode": "AutomaticByPlatform",
"assessmentMode": "AutomaticByPlatform",
"automaticByPlatformSettings": {
"rebootSetting": "Never",
"bypassPlatformSafetyChecksOnUserSchedule": false
}
}
}
},
"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,
"patchSettings": {
"patchMode": "AutomaticByPlatform",
"assessmentMode": "AutomaticByPlatform",
"automaticByPlatformSettings": {
"rebootSetting": "Never",
"bypassPlatformSafetyChecksOnUserSchedule": false
}
}
}
},
"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"
}
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}",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true,
"patchSettings": {
"patchMode": "AutomaticByPlatform",
"enableHotpatching": 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.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.PatchSettings;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import com.azure.resourcemanager.compute.models.WindowsConfiguration;
import com.azure.resourcemanager.compute.models.WindowsVMGuestPatchMode;
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_WindowsVmWithPatchSettingModeOfAutomaticByPlatformAndEnableHotPatchingTrue.json
*/
/**
* Sample code: Create a Windows vm with a patch setting patchMode of AutomaticByPlatform and enableHotpatching set
* to true.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAWindowsVmWithAPatchSettingPatchModeOfAutomaticByPlatformAndEnableHotpatchingSetToTrue(
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")
.withWindowsConfiguration(new WindowsConfiguration().withProvisionVMAgent(true)
.withEnableAutomaticUpdates(true)
.withPatchSettings(new PatchSettings()
.withPatchMode(WindowsVMGuestPatchMode.AUTOMATIC_BY_PLATFORM).withEnableHotpatching(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 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_windows_vm_with_patch_setting_mode_of_automatic_by_platform_and_enable_hot_patching_true.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",
"windowsConfiguration": {
"enableAutomaticUpdates": True,
"patchSettings": {"enableHotpatching": True, "patchMode": "AutomaticByPlatform"},
"provisionVMAgent": True,
},
},
"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_WindowsVmWithPatchSettingModeOfAutomaticByPlatformAndEnableHotPatchingTrue.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WindowsVmWithPatchSettingModeOfAutomaticByPlatformAndEnableHotPatchingTrue.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAWindowsVmWithAPatchSettingPatchModeOfAutomaticByPlatformAndEnableHotpatchingSetToTrue() {
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"),
WindowsConfiguration: &armcompute.WindowsConfiguration{
EnableAutomaticUpdates: to.Ptr(true),
PatchSettings: &armcompute.PatchSettings{
EnableHotpatching: to.Ptr(true),
PatchMode: to.Ptr(armcompute.WindowsVMGuestPatchModeAutomaticByPlatform),
},
ProvisionVMAgent: to.Ptr(true),
},
},
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),
// PatchSettings: &armcompute.PatchSettings{
// EnableHotpatching: to.Ptr(true),
// PatchMode: to.Ptr(armcompute.WindowsVMGuestPatchModeAutomaticByPlatform),
// },
// 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_WindowsVmWithPatchSettingModeOfAutomaticByPlatformAndEnableHotPatchingTrue.json
*/
async function createAWindowsVMWithAPatchSettingPatchModeOfAutomaticByPlatformAndEnableHotpatchingSetToTrue() {
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",
windowsConfiguration: {
enableAutomaticUpdates: true,
patchSettings: {
enableHotpatching: true,
patchMode: "AutomaticByPlatform",
},
provisionVMAgent: true,
},
},
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_WindowsVmWithPatchSettingModeOfAutomaticByPlatformAndEnableHotPatchingTrue.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}",
WindowsConfiguration = new WindowsConfiguration
{
ProvisionVmAgent = true,
IsAutomaticUpdatesEnabled = true,
PatchSettings = new PatchSettings
{
PatchMode = WindowsVmGuestPatchMode.AutomaticByPlatform,
EnableHotpatching = 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",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true,
"patchSettings": {
"patchMode": "AutomaticByPlatform",
"enableHotpatching": 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,
"patchSettings": {
"patchMode": "AutomaticByPlatform",
"enableHotpatching": 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 Windows vm with a patch setting patchMode of Manual.
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}",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true,
"patchSettings": {
"patchMode": "Manual"
}
}
},
"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.PatchSettings;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import com.azure.resourcemanager.compute.models.WindowsConfiguration;
import com.azure.resourcemanager.compute.models.WindowsVMGuestPatchMode;
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_WindowsVmWithPatchSettingModeOfManual.json
*/
/**
* Sample code: Create a Windows vm with a patch setting patchMode of Manual.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void
createAWindowsVmWithAPatchSettingPatchModeOfManual(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").withWindowsConfiguration(
new WindowsConfiguration().withProvisionVMAgent(true).withEnableAutomaticUpdates(true)
.withPatchSettings(new PatchSettings().withPatchMode(WindowsVMGuestPatchMode.MANUAL))))
.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 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_windows_vm_with_patch_setting_mode_of_manual.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",
"windowsConfiguration": {
"enableAutomaticUpdates": True,
"patchSettings": {"patchMode": "Manual"},
"provisionVMAgent": True,
},
},
"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_WindowsVmWithPatchSettingModeOfManual.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WindowsVmWithPatchSettingModeOfManual.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAWindowsVmWithAPatchSettingPatchModeOfManual() {
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"),
WindowsConfiguration: &armcompute.WindowsConfiguration{
EnableAutomaticUpdates: to.Ptr(true),
PatchSettings: &armcompute.PatchSettings{
PatchMode: to.Ptr(armcompute.WindowsVMGuestPatchModeManual),
},
ProvisionVMAgent: to.Ptr(true),
},
},
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),
// PatchSettings: &armcompute.PatchSettings{
// PatchMode: to.Ptr(armcompute.WindowsVMGuestPatchModeManual),
// },
// 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_WindowsVmWithPatchSettingModeOfManual.json
*/
async function createAWindowsVMWithAPatchSettingPatchModeOfManual() {
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",
windowsConfiguration: {
enableAutomaticUpdates: true,
patchSettings: { patchMode: "Manual" },
provisionVMAgent: true,
},
},
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_WindowsVmWithPatchSettingModeOfManual.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}",
WindowsConfiguration = new WindowsConfiguration
{
ProvisionVmAgent = true,
IsAutomaticUpdatesEnabled = true,
PatchSettings = new PatchSettings
{
PatchMode = WindowsVmGuestPatchMode.Manual,
},
},
},
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,
"patchSettings": {
"patchMode": "Manual"
}
}
},
"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": false,
"patchSettings": {
"patchMode": "Manual"
}
}
},
"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"
}
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}",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": 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.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.PatchSettings;
import com.azure.resourcemanager.compute.models.StorageAccountTypes;
import com.azure.resourcemanager.compute.models.StorageProfile;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
import com.azure.resourcemanager.compute.models.WindowsConfiguration;
import com.azure.resourcemanager.compute.models.WindowsPatchAssessmentMode;
import com.azure.resourcemanager.compute.models.WindowsVMGuestPatchMode;
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_WindowsVmWithPatchSettingModesOfAutomaticByPlatform.json
*/
/**
* Sample code: Create a Windows vm with patch settings patchMode and assessmentMode set to AutomaticByPlatform.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createAWindowsVmWithPatchSettingsPatchModeAndAssessmentModeSetToAutomaticByPlatform(
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")
.withWindowsConfiguration(new WindowsConfiguration().withProvisionVMAgent(true)
.withEnableAutomaticUpdates(true).withPatchSettings(
new PatchSettings().withPatchMode(WindowsVMGuestPatchMode.AUTOMATIC_BY_PLATFORM)
.withAssessmentMode(WindowsPatchAssessmentMode.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 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_windows_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_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",
"windowsConfiguration": {
"enableAutomaticUpdates": True,
"patchSettings": {"assessmentMode": "AutomaticByPlatform", "patchMode": "AutomaticByPlatform"},
"provisionVMAgent": True,
},
},
"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_WindowsVmWithPatchSettingModesOfAutomaticByPlatform.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WindowsVmWithPatchSettingModesOfAutomaticByPlatform.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createAWindowsVmWithPatchSettingsPatchModeAndAssessmentModeSetToAutomaticByPlatform() {
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"),
WindowsConfiguration: &armcompute.WindowsConfiguration{
EnableAutomaticUpdates: to.Ptr(true),
PatchSettings: &armcompute.PatchSettings{
AssessmentMode: to.Ptr(armcompute.WindowsPatchAssessmentModeAutomaticByPlatform),
PatchMode: to.Ptr(armcompute.WindowsVMGuestPatchModeAutomaticByPlatform),
},
ProvisionVMAgent: to.Ptr(true),
},
},
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),
// PatchSettings: &armcompute.PatchSettings{
// AssessmentMode: to.Ptr(armcompute.WindowsPatchAssessmentModeAutomaticByPlatform),
// PatchMode: to.Ptr(armcompute.WindowsVMGuestPatchModeAutomaticByPlatform),
// },
// 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_WindowsVmWithPatchSettingModesOfAutomaticByPlatform.json
*/
async function createAWindowsVMWithPatchSettingsPatchModeAndAssessmentModeSetToAutomaticByPlatform() {
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",
windowsConfiguration: {
enableAutomaticUpdates: true,
patchSettings: {
assessmentMode: "AutomaticByPlatform",
patchMode: "AutomaticByPlatform",
},
provisionVMAgent: true,
},
},
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_WindowsVmWithPatchSettingModesOfAutomaticByPlatform.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}",
WindowsConfiguration = new WindowsConfiguration
{
ProvisionVmAgent = true,
IsAutomaticUpdatesEnabled = true,
PatchSettings = new PatchSettings
{
PatchMode = WindowsVmGuestPatchMode.AutomaticByPlatform,
AssessmentMode = WindowsPatchAssessmentMode.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",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": 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": "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,
"patchSettings": {
"patchMode": "AutomaticByPlatform",
"assessmentMode": "AutomaticByPlatform"
}
}
},
"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 or update a VM with capacity reservation
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",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage",
"name": "myVMosdisk"
}
},
"capacityReservation": {
"capacityReservationGroup": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/CapacityReservationGroups/{crgName}"
}
},
"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.core.management.SubResource;
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.CapacityReservationProfile;
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_WithCapacityReservation.json
*/
/**
* Sample code: Create or update a VM with capacity reservation.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createOrUpdateAVMWithCapacityReservation(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))))
.withCapacityReservation(
new CapacityReservationProfile().withCapacityReservationGroup(new SubResource().withId(
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/CapacityReservationGroups/{crgName}"))),
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 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_capacity_reservation.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": {
"capacityReservation": {
"capacityReservationGroup": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/CapacityReservationGroups/{crgName}"
}
},
"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",
"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_WithCapacityReservation.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/069a65e8a6d1a6c0c58d9a9d97610b7103b6e8a5/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-07-01/examples/virtualMachineExamples/VirtualMachine_Create_WithCapacityReservation.json
func ExampleVirtualMachinesClient_BeginCreateOrUpdate_createOrUpdateAVmWithCapacityReservation() {
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{
CapacityReservation: &armcompute.CapacityReservationProfile{
CapacityReservationGroup: &armcompute.SubResource{
ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/CapacityReservationGroups/{crgName}"),
},
},
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),
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{
// CapacityReservation: &armcompute.CapacityReservationProfile{
// CapacityReservationGroup: &armcompute.SubResource{
// ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/CapacityReservationGroups/{crgName}"),
// },
// },
// 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),
// 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_WithCapacityReservation.json
*/
async function createOrUpdateAVMWithCapacityReservation() {
const subscriptionId = process.env["COMPUTE_SUBSCRIPTION_ID"] || "{subscription-id}";
const resourceGroupName = process.env["COMPUTE_RESOURCE_GROUP"] || "myResourceGroup";
const vmName = "myVM";
const parameters = {
capacityReservation: {
capacityReservationGroup: {
id: "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/CapacityReservationGroups/{crgName}",
},
},
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",
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_WithCapacityReservation.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}"),
}},
},
CapacityReservationGroupId = new ResourceIdentifier("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/CapacityReservationGroups/{crgName}"),
};
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
}
},
"capacityReservation": {
"capacityReservationGroup": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/CapacityReservationGroups/{crgName}"
}
},
"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": []
},
"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
}
},
"capacityReservation": {
"capacityReservationGroup": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/CapacityReservationGroups/{crgName}"
}
},
"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": []
},
"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"
}
Definitions
Name |
Description |
AdditionalCapabilities
|
Specifies additional capabilities enabled or disabled on the virtual machine.
|
AdditionalUnattendContent
|
Specifies additional base-64 encoded XML formatted information that can be included in the Unattend.xml file, which is used by Windows Setup.
|
ApiEntityReference
|
The source resource identifier. It can be a snapshot, or disk restore point from which to create a disk.
|
ApiError
|
Api error.
|
ApiErrorBase
|
Api error base.
|
ApplicationProfile
|
Specifies the gallery applications that should be made available to the VM/VMSS.
|
AvailablePatchSummary
|
The available patch summary of the latest assessment operation for the virtual machine.
|
BillingProfile
|
Specifies the billing related details of a Azure Spot virtual machine. Minimum api-version: 2019-03-01.
|
BootDiagnostics
|
Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. NOTE: If storageUri is being specified then ensure that the storage account is in the same region and subscription as the VM. You can easily view the output of your console log. Azure also enables you to see a screenshot of the VM from the hypervisor.
|
BootDiagnosticsInstanceView
|
Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. You can easily view the output of your console log. Azure also enables you to see a screenshot of the VM from the hypervisor.
|
CachingTypes
|
Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The defaulting behavior is: None for Standard storage. ReadOnly for Premium storage.
|
CapacityReservationProfile
|
Specifies information about the capacity reservation that is used to allocate virtual machine. Minimum api-version: 2021-04-01.
|
CloudError
|
An error response from the Compute service.
|
ComponentNames
|
The component name. Currently, the only allowable value is Microsoft-Windows-Shell-Setup.
|
DataDisk
|
Specifies the parameters that are used to add a data disk to a virtual machine. For more information about disks, see About disks and VHDs for Azure virtual machines.
|
DeleteOptions
|
Specify what happens to the network interface when the VM is deleted
|
DiagnosticsProfile
|
Specifies the boot diagnostic settings state. Minimum api-version: 2015-06-15.
|
DiffDiskOptions
|
Specifies the ephemeral disk settings for operating system disk.
|
DiffDiskPlacement
|
Specifies the ephemeral disk placement for operating system disk. Possible values are: CacheDisk, ResourceDisk, NvmeDisk. The defaulting behavior is: CacheDisk if one is configured for the VM size otherwise ResourceDisk or NvmeDisk is used. Refer to the VM size documentation for Windows VM at https://docs.microsoft.com/azure/virtual-machines/windows/sizes and Linux VM at https://docs.microsoft.com/azure/virtual-machines/linux/sizes to check which VM sizes exposes a cache disk. Minimum api-version for NvmeDisk: 2024-03-01.
|
DiffDiskSettings
|
Specifies the ephemeral Disk Settings for the operating system disk used by the virtual machine.
|
DiskControllerTypes
|
Specifies the disk controller type configured for the VM. Note: This property will be set to the default disk controller type if not specified provided virtual machine is being created with 'hyperVGeneration' set to V2 based on the capabilities of the operating system disk and VM size from the the specified minimum api version. You need to deallocate the VM before updating its disk controller type unless you are updating the VM size in the VM configuration which implicitly deallocates and reallocates the VM. Minimum api-version: 2022-08-01.
|
DiskCreateOptionTypes
|
Specifies how the virtual machine disk should be created. Possible values are Attach: This value is used when you are using a specialized disk to create the virtual machine. FromImage: This value is used when you are using an image to create the virtual machine. If you are using a platform image, you should also use the imageReference element described above. If you are using a marketplace image, you should also use the plan element previously described.
|
DiskDeleteOptionTypes
|
Specifies whether OS Disk should be deleted or detached upon VM deletion. Possible values are: Delete. If this value is used, the OS disk is deleted when VM is deleted. Detach. If this value is used, the os disk is retained after VM is deleted. The default value is set to Detach. For an ephemeral OS Disk, the default value is set to Delete. The user cannot change the delete option for an ephemeral OS Disk.
|
DiskDetachOptionTypes
|
Specifies the detach behavior to be used while detaching a disk or which is already in the process of detachment from the virtual machine. Supported values: ForceDetach. detachOption: ForceDetach is applicable only for managed data disks. If a previous detachment attempt of the data disk did not complete due to an unexpected failure from the virtual machine and the disk is still not released then use force-detach as a last resort option to detach the disk forcibly from the VM. All writes might not have been flushed when using this detach behavior. To force-detach a data disk update toBeDetached to 'true' along with setting detachOption: 'ForceDetach'.
|
DiskEncryptionSetParameters
|
Specifies the customer managed disk encryption set resource id for the managed disk.
|
DiskEncryptionSettings
|
Specifies the encryption settings for the OS Disk. Minimum api-version: 2015-06-15.
|
DiskInstanceView
|
The virtual machine disk information.
|
DomainNameLabelScopeTypes
|
The Domain name label scope of the PublicIPAddress resources that will be created. The generated name label is the concatenation of the hashed domain name label with policy according to the domain name label scope and vm network profile unique ID.
|
EncryptionIdentity
|
Specifies the Managed Identity used by ADE to get access token for keyvault operations.
|
EventGridAndResourceGraph
|
The configuration parameters used while creating eventGridAndResourceGraph Scheduled Event setting.
|
ExtendedLocation
|
The extended location of the Virtual Machine.
|
ExtendedLocationTypes
|
The type of the extended location.
|
HardwareProfile
|
Specifies the hardware settings for the virtual machine.
|
HyperVGenerationType
|
Specifies the HyperVGeneration Type associated with a resource
|
ImageReference
|
Specifies information about the image to use. You can specify information about platform images, marketplace images, or virtual machine images. This element is required when you want to use a platform image, marketplace image, or virtual machine image, but is not used in other creation operations.
|
InnerError
|
Inner error details.
|
InstanceViewStatus
|
Instance view status.
|
IPVersions
|
Available from Api-Version 2019-07-01 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'.
|
KeyVaultKeyReference
|
Specifies the location of the key encryption key in Key Vault.
|
KeyVaultSecretReference
|
The extensions protected settings that are passed by reference, and consumed from key vault
|
LastPatchInstallationSummary
|
The installation summary of the latest installation operation for the virtual machine.
|
LinuxConfiguration
|
Specifies the Linux operating system settings on the virtual machine. For a list of supported Linux distributions, see Linux on Azure-Endorsed Distributions.
|
LinuxPatchAssessmentMode
|
Specifies the mode of VM Guest Patch Assessment for the IaaS virtual machine.
Possible values are:
ImageDefault - You control the timing of patch assessments on a virtual machine.
AutomaticByPlatform - The platform will trigger periodic patch assessments. The property provisionVMAgent must be true.
|
LinuxPatchSettings
|
[Preview Feature] Specifies settings related to VM Guest Patching on Linux.
|
LinuxVMGuestPatchAutomaticByPlatformRebootSetting
|
Specifies the reboot setting for all AutomaticByPlatform patch installation operations.
|
LinuxVMGuestPatchAutomaticByPlatformSettings
|
Specifies additional settings for patch mode AutomaticByPlatform in VM Guest Patching on Linux.
|
LinuxVMGuestPatchMode
|
Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated to virtual machine scale set with OrchestrationMode as Flexible.
Possible values are:
ImageDefault - The virtual machine's default patching configuration is used.
AutomaticByPlatform - The virtual machine will be automatically updated by the platform. The property provisionVMAgent must be true
|
MaintenanceOperationResultCodeTypes
|
The Last Maintenance Operation Result Code.
|
MaintenanceRedeployStatus
|
The Maintenance Operation status on the virtual machine.
|
ManagedDiskParameters
|
The managed disk parameters.
|
Mode
|
Specifies the mode that ProxyAgent will execute on if the feature is enabled. ProxyAgent will start to audit or monitor but not enforce access control over requests to host endpoints in Audit mode, while in Enforce mode it will enforce access control. The default value is Enforce mode.
|
NetworkApiVersion
|
specifies the Microsoft.Network API version used when creating networking resources in the Network Interface Configurations
|
NetworkInterfaceAuxiliaryMode
|
Specifies whether the Auxiliary mode is enabled for the Network Interface resource.
|
NetworkInterfaceAuxiliarySku
|
Specifies whether the Auxiliary sku is enabled for the Network Interface resource.
|
NetworkInterfaceReference
|
Specifies the list of resource Ids for the network interfaces associated with the virtual machine.
|
NetworkProfile
|
Specifies the network interfaces of the virtual machine.
|
OperatingSystemTypes
|
The Operating System type.
|
OSDisk
|
Specifies information about the operating system disk used by the virtual machine. For more information about disks, see About disks and VHDs for Azure virtual machines.
|
OSImageNotificationProfile
|
Specifies OS Image Scheduled Event related configurations.
|
OSProfile
|
Specifies the operating system settings used while creating the virtual machine. Some of the settings cannot be changed once VM is provisioned.
|
PassNames
|
The pass name. Currently, the only allowable value is OobeSystem.
|
PatchOperationStatus
|
The overall success or failure status of the operation. It remains "InProgress" until the operation completes. At that point it will become "Unknown", "Failed", "Succeeded", or "CompletedWithWarnings."
|
PatchSettings
|
[Preview Feature] Specifies settings related to VM Guest Patching on Windows.
|
Plan
|
Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click Want to deploy programmatically, Get Started ->. Enter any required information and then click Save.
|
ProtocolTypes
|
Specifies the protocol of WinRM listener. Possible values are: http, https.
|
ProxyAgentSettings
|
Specifies ProxyAgent settings while creating the virtual machine. Minimum api-version: 2023-09-01.
|
PublicIPAddressSku
|
Describes the public IP Sku. It can only be set with OrchestrationMode as Flexible.
|
PublicIPAddressSkuName
|
Specify public IP sku name
|
PublicIPAddressSkuTier
|
Specify public IP sku tier
|
PublicIPAllocationMethod
|
Specify the public IP allocation type
|
ResourceIdentityType
|
The type of identity used for the virtual machine. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine.
|
ScheduledEventsAdditionalPublishingTargets
|
The configuration parameters used while publishing scheduledEventsAdditionalPublishingTargets.
|
ScheduledEventsPolicy
|
Specifies Redeploy, Reboot and ScheduledEventsAdditionalPublishingTargets Scheduled Event related configurations for the virtual machine.
|
ScheduledEventsProfile
|
Specifies Scheduled Event related configurations.
|
securityEncryptionTypes
|
Specifies the EncryptionType of the managed disk. It is set to DiskWithVMGuestState for encryption of the managed disk along with VMGuestState blob, VMGuestStateOnly for encryption of just the VMGuestState blob, and NonPersistedTPM for not persisting firmware state in the VMGuestState blob.. Note: It can be set for only Confidential VMs.
|
SecurityProfile
|
Specifies the Security related profile settings for the virtual machine.
|
SecurityTypes
|
Specifies the SecurityType of the virtual machine. It has to be set to any specified value to enable UefiSettings. The default behavior is: UefiSettings will not be enabled unless this property is set.
|
SettingNames
|
Specifies the name of the setting to which the content applies. Possible values are: FirstLogonCommands and AutoLogon.
|
SshConfiguration
|
Specifies the ssh key configuration for a Linux OS.
|
SshPublicKey
|
The list of SSH public keys used to authenticate with linux based VMs.
|
StatusLevelTypes
|
The level code.
|
StorageAccountTypes
|
Specifies the storage account type for the managed disk. NOTE: UltraSSD_LRS can only be used with data disks, it cannot be used with OS Disk.
|
StorageProfile
|
Specifies the storage settings for the virtual machine disks.
|
SubResource
|
The relative URL of the Key Vault containing the secret.
|
TerminateNotificationProfile
|
Specifies Terminate Scheduled Event related configurations.
|
UefiSettings
|
Specifies the security settings like secure boot and vTPM used while creating the virtual machine. Minimum api-version: 2020-12-01.
|
UserAssignedIdentities
|
The list of user identities associated with the Virtual Machine. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
|
UserInitiatedReboot
|
The configuration parameters used while creating userInitiatedReboot scheduled event setting creation.
|
UserInitiatedRedeploy
|
The configuration parameters used while creating userInitiatedRedeploy scheduled event setting creation.
|
VaultCertificate
|
The list of key vault references in SourceVault which contain certificates.
|
VaultSecretGroup
|
Specifies set of certificates that should be installed onto the virtual machine. To install certificates on a virtual machine it is recommended to use the Azure Key Vault virtual machine extension for Linux or the Azure Key Vault virtual machine extension for Windows.
|
VirtualHardDisk
|
The virtual hard disk.
|
VirtualMachine
|
Describes a Virtual Machine.
|
VirtualMachineAgentInstanceView
|
The VM Agent running on the virtual machine.
|
VirtualMachineEvictionPolicyTypes
|
Specifies the eviction policy for the Azure Spot virtual machine and Azure Spot scale set. For Azure Spot virtual machines, both 'Deallocate' and 'Delete' are supported and the minimum api-version is 2019-03-01. For Azure Spot scale sets, both 'Deallocate' and 'Delete' are supported and the minimum api-version is 2017-10-30-preview.
|
VirtualMachineExtension
|
The virtual machine child extension resources.
|
VirtualMachineExtensionHandlerInstanceView
|
The virtual machine extension handler instance view.
|
VirtualMachineExtensionInstanceView
|
The virtual machine extension instance view.
|
VirtualMachineHealthStatus
|
The health status for the VM.
|
VirtualMachineIdentity
|
The identity of the virtual machine, if configured.
|
VirtualMachineInstanceView
|
The virtual machine instance view.
|
VirtualMachineIpTag
|
The list of IP tags associated with the public IP address.
|
VirtualMachineNetworkInterfaceConfiguration
|
Specifies the networking configurations that will be used to create the virtual machine networking resources.
|
VirtualMachineNetworkInterfaceDnsSettingsConfiguration
|
The dns settings to be applied on the network interfaces.
|
VirtualMachineNetworkInterfaceIPConfiguration
|
Specifies the IP configurations of the network interface.
|
VirtualMachinePatchStatus
|
[Preview Feature] The status of virtual machine patch operations.
|
VirtualMachinePriorityTypes
|
Specifies the priority for the virtual machine. Minimum api-version: 2019-03-01
|
VirtualMachinePublicIPAddressConfiguration
|
The publicIPAddressConfiguration.
|
VirtualMachinePublicIPAddressDnsSettingsConfiguration
|
The dns settings to be applied on the publicIP addresses .
|
VirtualMachineSizeTypes
|
Specifies the size of the virtual machine. The enum data type is currently deprecated and will be removed by December 23rd 2023. The recommended way to get the list of available sizes is using these APIs: List all available virtual machine sizes in an availability set, List all available virtual machine sizes in a region, List all available virtual machine sizes for resizing. For more information about virtual machine sizes, see Sizes for virtual machines. The available VM sizes depend on region and availability set.
|
VMDiskSecurityProfile
|
Specifies the security profile for the managed disk.
|
VMGalleryApplication
|
Specifies the gallery applications that should be made available to the VM/VMSS
|
VMSizeProperties
|
Specifies the properties for customizing the size of the virtual machine. Minimum api-version: 2021-07-01. This feature is still in preview mode and is not supported for VirtualMachineScaleSet. Please follow the instructions in VM Customization for more details.
|
WindowsConfiguration
|
Specifies Windows operating system settings on the virtual machine.
|
WindowsPatchAssessmentMode
|
Specifies the mode of VM Guest patch assessment for the IaaS virtual machine.
Possible values are:
ImageDefault - You control the timing of patch assessments on a virtual machine.
AutomaticByPlatform - The platform will trigger periodic patch assessments. The property provisionVMAgent must be true.
|
WindowsVMGuestPatchAutomaticByPlatformRebootSetting
|
Specifies the reboot setting for all AutomaticByPlatform patch installation operations.
|
WindowsVMGuestPatchAutomaticByPlatformSettings
|
Specifies additional settings for patch mode AutomaticByPlatform in VM Guest Patching on Windows.
|
WindowsVMGuestPatchMode
|
Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated to virtual machine scale set with OrchestrationMode as Flexible.
Possible values are:
Manual - You control the application of patches to a virtual machine. You do this by applying patches manually inside the VM. In this mode, automatic updates are disabled; the property WindowsConfiguration.enableAutomaticUpdates must be false
AutomaticByOS - The virtual machine will automatically be updated by the OS. The property WindowsConfiguration.enableAutomaticUpdates must be true.
AutomaticByPlatform - the virtual machine will automatically updated by the platform. The properties provisionVMAgent and WindowsConfiguration.enableAutomaticUpdates must be true
|
WinRMConfiguration
|
Specifies the Windows Remote Management listeners. This enables remote Windows PowerShell.
|
WinRMListener
|
The list of Windows Remote Management listeners
|
AdditionalCapabilities
Specifies additional capabilities enabled or disabled on the virtual machine.
Name |
Type |
Description |
hibernationEnabled
|
boolean
|
The flag that enables or disables hibernation capability on the VM.
|
ultraSSDEnabled
|
boolean
|
The flag that enables or disables a capability to have one or more managed data disks with UltraSSD_LRS storage account type on the VM or VMSS. Managed disks with storage account type UltraSSD_LRS can be added to a virtual machine or virtual machine scale set only if this property is enabled.
|
AdditionalUnattendContent
Specifies additional base-64 encoded XML formatted information that can be included in the Unattend.xml file, which is used by Windows Setup.
Name |
Type |
Description |
componentName
|
ComponentNames
|
The component name. Currently, the only allowable value is Microsoft-Windows-Shell-Setup.
|
content
|
string
|
Specifies the XML formatted content that is added to the unattend.xml file for the specified path and component. The XML must be less than 4KB and must include the root element for the setting or feature that is being inserted.
|
passName
|
PassNames
|
The pass name. Currently, the only allowable value is OobeSystem.
|
settingName
|
SettingNames
|
Specifies the name of the setting to which the content applies. Possible values are: FirstLogonCommands and AutoLogon.
|
ApiEntityReference
The source resource identifier. It can be a snapshot, or disk restore point from which to create a disk.
Name |
Type |
Description |
id
|
string
|
The ARM resource id in the form of /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/...
|
ApiError
Api error.
Name |
Type |
Description |
code
|
string
|
The error code.
|
details
|
ApiErrorBase[]
|
The Api error details
|
innererror
|
InnerError
|
The Api inner error
|
message
|
string
|
The error message.
|
target
|
string
|
The target of the particular error.
|
ApiErrorBase
Api error base.
Name |
Type |
Description |
code
|
string
|
The error code.
|
message
|
string
|
The error message.
|
target
|
string
|
The target of the particular error.
|
ApplicationProfile
Specifies the gallery applications that should be made available to the VM/VMSS.
Name |
Type |
Description |
galleryApplications
|
VMGalleryApplication[]
|
Specifies the gallery applications that should be made available to the VM/VMSS
|
AvailablePatchSummary
The available patch summary of the latest assessment operation for the virtual machine.
Name |
Type |
Description |
assessmentActivityId
|
string
|
The activity ID of the operation that produced this result. It is used to correlate across CRP and extension logs.
|
criticalAndSecurityPatchCount
|
integer
|
The number of critical or security patches that have been detected as available and not yet installed.
|
error
|
ApiError
|
The errors that were encountered during execution of the operation. The details array contains the list of them.
|
lastModifiedTime
|
string
|
The UTC timestamp when the operation began.
|
otherPatchCount
|
integer
|
The number of all available patches excluding critical and security.
|
rebootPending
|
boolean
|
The overall reboot status of the VM. It will be true when partially installed patches require a reboot to complete installation but the reboot has not yet occurred.
|
startTime
|
string
|
The UTC timestamp when the operation began.
|
status
|
PatchOperationStatus
|
The overall success or failure status of the operation. It remains "InProgress" until the operation completes. At that point it will become "Unknown", "Failed", "Succeeded", or "CompletedWithWarnings."
|
BillingProfile
Specifies the billing related details of a Azure Spot virtual machine. Minimum api-version: 2019-03-01.
Name |
Type |
Description |
maxPrice
|
number
|
Specifies the maximum price you are willing to pay for a Azure Spot VM/VMSS. This price is in US Dollars.
This price will be compared with the current Azure Spot price for the VM size. Also, the prices are compared at the time of create/update of Azure Spot VM/VMSS and the operation will only succeed if the maxPrice is greater than the current Azure Spot price.
The maxPrice will also be used for evicting a Azure Spot VM/VMSS if the current Azure Spot price goes beyond the maxPrice after creation of VM/VMSS.
Possible values are:
- Any decimal value greater than zero. Example: 0.01538
-1 – indicates default price to be up-to on-demand.
You can set the maxPrice to -1 to indicate that the Azure Spot VM/VMSS should not be evicted for price reasons. Also, the default max price is -1 if it is not provided by you.
Minimum api-version: 2019-03-01.
|
BootDiagnostics
Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. NOTE: If storageUri is being specified then ensure that the storage account is in the same region and subscription as the VM. You can easily view the output of your console log. Azure also enables you to see a screenshot of the VM from the hypervisor.
Name |
Type |
Description |
enabled
|
boolean
|
Whether boot diagnostics should be enabled on the Virtual Machine.
|
storageUri
|
string
|
Uri of the storage account to use for placing the console output and screenshot. If storageUri is not specified while enabling boot diagnostics, managed storage will be used.
|
BootDiagnosticsInstanceView
Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. You can easily view the output of your console log. Azure also enables you to see a screenshot of the VM from the hypervisor.
Name |
Type |
Description |
consoleScreenshotBlobUri
|
string
|
The console screenshot blob URI. Note: This will not be set if boot diagnostics is currently enabled with managed storage.
|
serialConsoleLogBlobUri
|
string
|
The serial console log blob Uri. Note: This will not be set if boot diagnostics is currently enabled with managed storage.
|
status
|
InstanceViewStatus
|
The boot diagnostics status information for the VM. Note: It will be set only if there are errors encountered in enabling boot diagnostics.
|
CachingTypes
Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The defaulting behavior is: None for Standard storage. ReadOnly for Premium storage.
Name |
Type |
Description |
None
|
string
|
|
ReadOnly
|
string
|
|
ReadWrite
|
string
|
|
CapacityReservationProfile
Specifies information about the capacity reservation that is used to allocate virtual machine. Minimum api-version: 2021-04-01.
Name |
Type |
Description |
capacityReservationGroup
|
SubResource
|
Specifies the capacity reservation group resource id that should be used for allocating the virtual machine or scaleset vm instances provided enough capacity has been reserved. Please refer to https://aka.ms/CapacityReservation for more details.
|
CloudError
An error response from the Compute service.
Name |
Type |
Description |
error
|
ApiError
|
Api error.
|
ComponentNames
The component name. Currently, the only allowable value is Microsoft-Windows-Shell-Setup.
Name |
Type |
Description |
Microsoft-Windows-Shell-Setup
|
string
|
|
DataDisk
Specifies the parameters that are used to add a data disk to a virtual machine. For more information about disks, see About disks and VHDs for Azure virtual machines.
Name |
Type |
Description |
caching
|
CachingTypes
|
Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The defaulting behavior is: None for Standard storage. ReadOnly for Premium storage.
|
createOption
|
DiskCreateOptionTypes
|
Specifies how the virtual machine disk should be created. Possible values are Attach: This value is used when you are using a specialized disk to create the virtual machine. FromImage: This value is used when you are using an image to create the virtual machine data disk. If you are using a platform image, you should also use the imageReference element described above. If you are using a marketplace image, you should also use the plan element previously described. Empty: This value is used when creating an empty data disk. Copy: This value is used to create a data disk from a snapshot or another disk. Restore: This value is used to create a data disk from a disk restore point.
|
deleteOption
|
DiskDeleteOptionTypes
|
Specifies whether data disk should be deleted or detached upon VM deletion. Possible values are: Delete. If this value is used, the data disk is deleted when VM is deleted. Detach. If this value is used, the data disk is retained after VM is deleted. The default value is set to Detach.
|
detachOption
|
DiskDetachOptionTypes
|
Specifies the detach behavior to be used while detaching a disk or which is already in the process of detachment from the virtual machine. Supported values: ForceDetach. detachOption: ForceDetach is applicable only for managed data disks. If a previous detachment attempt of the data disk did not complete due to an unexpected failure from the virtual machine and the disk is still not released then use force-detach as a last resort option to detach the disk forcibly from the VM. All writes might not have been flushed when using this detach behavior. To force-detach a data disk update toBeDetached to 'true' along with setting detachOption: 'ForceDetach'.
|
diskIOPSReadWrite
|
integer
|
Specifies the Read-Write IOPS for the managed disk when StorageAccountType is UltraSSD_LRS. Returned only for VirtualMachine ScaleSet VM disks. Can be updated only via updates to the VirtualMachine Scale Set.
|
diskMBpsReadWrite
|
integer
|
Specifies the bandwidth in MB per second for the managed disk when StorageAccountType is UltraSSD_LRS. Returned only for VirtualMachine ScaleSet VM disks. Can be updated only via updates to the VirtualMachine Scale Set.
|
diskSizeGB
|
integer
|
Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image. The property 'diskSizeGB' is the number of bytes x 1024^3 for the disk and the value cannot be larger than 1023.
|
image
|
VirtualHardDisk
|
The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. If SourceImage is provided, the destination virtual hard drive must not exist.
|
lun
|
integer
|
Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM.
|
managedDisk
|
ManagedDiskParameters
|
The managed disk parameters.
|
name
|
string
|
The disk name.
|
sourceResource
|
ApiEntityReference
|
The source resource identifier. It can be a snapshot, or disk restore point from which to create a disk.
|
toBeDetached
|
boolean
|
Specifies whether the data disk is in process of detachment from the VirtualMachine/VirtualMachineScaleset
|
vhd
|
VirtualHardDisk
|
The virtual hard disk.
|
writeAcceleratorEnabled
|
boolean
|
Specifies whether writeAccelerator should be enabled or disabled on the disk.
|
DeleteOptions
Specify what happens to the network interface when the VM is deleted
Name |
Type |
Description |
Delete
|
string
|
|
Detach
|
string
|
|
DiagnosticsProfile
Specifies the boot diagnostic settings state. Minimum api-version: 2015-06-15.
Name |
Type |
Description |
bootDiagnostics
|
BootDiagnostics
|
Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. NOTE: If storageUri is being specified then ensure that the storage account is in the same region and subscription as the VM. You can easily view the output of your console log. Azure also enables you to see a screenshot of the VM from the hypervisor.
|
DiffDiskOptions
Specifies the ephemeral disk settings for operating system disk.
Name |
Type |
Description |
Local
|
string
|
|
DiffDiskPlacement
Specifies the ephemeral disk placement for operating system disk. Possible values are: CacheDisk, ResourceDisk, NvmeDisk. The defaulting behavior is: CacheDisk if one is configured for the VM size otherwise ResourceDisk or NvmeDisk is used. Refer to the VM size documentation for Windows VM at https://docs.microsoft.com/azure/virtual-machines/windows/sizes and Linux VM at https://docs.microsoft.com/azure/virtual-machines/linux/sizes to check which VM sizes exposes a cache disk. Minimum api-version for NvmeDisk: 2024-03-01.
Name |
Type |
Description |
CacheDisk
|
string
|
|
NvmeDisk
|
string
|
|
ResourceDisk
|
string
|
|
DiffDiskSettings
Specifies the ephemeral Disk Settings for the operating system disk used by the virtual machine.
DiskControllerTypes
Specifies the disk controller type configured for the VM. Note: This property will be set to the default disk controller type if not specified provided virtual machine is being created with 'hyperVGeneration' set to V2 based on the capabilities of the operating system disk and VM size from the the specified minimum api version. You need to deallocate the VM before updating its disk controller type unless you are updating the VM size in the VM configuration which implicitly deallocates and reallocates the VM. Minimum api-version: 2022-08-01.
Name |
Type |
Description |
NVMe
|
string
|
|
SCSI
|
string
|
|
DiskCreateOptionTypes
Specifies how the virtual machine disk should be created. Possible values are Attach: This value is used when you are using a specialized disk to create the virtual machine. FromImage: This value is used when you are using an image to create the virtual machine. If you are using a platform image, you should also use the imageReference element described above. If you are using a marketplace image, you should also use the plan element previously described.
Name |
Type |
Description |
Attach
|
string
|
|
Copy
|
string
|
|
Empty
|
string
|
|
FromImage
|
string
|
|
Restore
|
string
|
|
DiskDeleteOptionTypes
Specifies whether OS Disk should be deleted or detached upon VM deletion. Possible values are: Delete. If this value is used, the OS disk is deleted when VM is deleted. Detach. If this value is used, the os disk is retained after VM is deleted. The default value is set to Detach. For an ephemeral OS Disk, the default value is set to Delete. The user cannot change the delete option for an ephemeral OS Disk.
Name |
Type |
Description |
Delete
|
string
|
|
Detach
|
string
|
|
DiskDetachOptionTypes
Specifies the detach behavior to be used while detaching a disk or which is already in the process of detachment from the virtual machine. Supported values: ForceDetach. detachOption: ForceDetach is applicable only for managed data disks. If a previous detachment attempt of the data disk did not complete due to an unexpected failure from the virtual machine and the disk is still not released then use force-detach as a last resort option to detach the disk forcibly from the VM. All writes might not have been flushed when using this detach behavior. To force-detach a data disk update toBeDetached to 'true' along with setting detachOption: 'ForceDetach'.
Name |
Type |
Description |
ForceDetach
|
string
|
|
DiskEncryptionSetParameters
Specifies the customer managed disk encryption set resource id for the managed disk.
Name |
Type |
Description |
id
|
string
|
Resource Id
|
DiskEncryptionSettings
Specifies the encryption settings for the OS Disk. Minimum api-version: 2015-06-15.
Name |
Type |
Description |
diskEncryptionKey
|
KeyVaultSecretReference
|
Specifies the location of the disk encryption key, which is a Key Vault Secret.
|
enabled
|
boolean
|
Specifies whether disk encryption should be enabled on the virtual machine.
|
keyEncryptionKey
|
KeyVaultKeyReference
|
Specifies the location of the key encryption key in Key Vault.
|
DiskInstanceView
The virtual machine disk information.
Name |
Type |
Description |
encryptionSettings
|
DiskEncryptionSettings[]
|
Specifies the encryption settings for the OS Disk.
Minimum api-version: 2015-06-15
|
name
|
string
|
The disk name.
|
statuses
|
InstanceViewStatus[]
|
The resource status information.
|
DomainNameLabelScopeTypes
The Domain name label scope of the PublicIPAddress resources that will be created. The generated name label is the concatenation of the hashed domain name label with policy according to the domain name label scope and vm network profile unique ID.
Name |
Type |
Description |
NoReuse
|
string
|
|
ResourceGroupReuse
|
string
|
|
SubscriptionReuse
|
string
|
|
TenantReuse
|
string
|
|
EncryptionIdentity
Specifies the Managed Identity used by ADE to get access token for keyvault operations.
Name |
Type |
Description |
userAssignedIdentityResourceId
|
string
|
Specifies ARM Resource ID of one of the user identities associated with the VM.
|
EventGridAndResourceGraph
The configuration parameters used while creating eventGridAndResourceGraph Scheduled Event setting.
Name |
Type |
Description |
enable
|
boolean
|
Specifies if event grid and resource graph is enabled for Scheduled event related configurations.
|
ExtendedLocation
The extended location of the Virtual Machine.
Name |
Type |
Description |
name
|
string
|
The name of the extended location.
|
type
|
ExtendedLocationTypes
|
The type of the extended location.
|
ExtendedLocationTypes
The type of the extended location.
Name |
Type |
Description |
EdgeZone
|
string
|
|
HardwareProfile
Specifies the hardware settings for the virtual machine.
HyperVGenerationType
Specifies the HyperVGeneration Type associated with a resource
Name |
Type |
Description |
V1
|
string
|
|
V2
|
string
|
|
ImageReference
Specifies information about the image to use. You can specify information about platform images, marketplace images, or virtual machine images. This element is required when you want to use a platform image, marketplace image, or virtual machine image, but is not used in other creation operations.
Name |
Type |
Description |
communityGalleryImageId
|
string
|
Specified the community gallery image unique id for vm deployment. This can be fetched from community gallery image GET call.
|
exactVersion
|
string
|
Specifies in decimal numbers, the version of platform image or marketplace image used to create the virtual machine. This readonly field differs from 'version', only if the value specified in 'version' field is 'latest'.
|
id
|
string
|
Resource Id
|
offer
|
string
|
Specifies the offer of the platform image or marketplace image used to create the virtual machine.
|
publisher
|
string
|
The image publisher.
|
sharedGalleryImageId
|
string
|
Specified the shared gallery image unique id for vm deployment. This can be fetched from shared gallery image GET call.
|
sku
|
string
|
The image SKU.
|
version
|
string
|
Specifies the version of the platform image or marketplace image used to create the virtual machine. The allowed formats are Major.Minor.Build or 'latest'. Major, Minor, and Build are decimal numbers. Specify 'latest' to use the latest version of an image available at deploy time. Even if you use 'latest', the VM image will not automatically update after deploy time even if a new version becomes available. Please do not use field 'version' for gallery image deployment, gallery image should always use 'id' field for deployment, to use 'latest' version of gallery image, just set '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageName}' in the 'id' field without version input.
|
InnerError
Inner error details.
Name |
Type |
Description |
errordetail
|
string
|
The internal error message or exception dump.
|
exceptiontype
|
string
|
The exception type.
|
InstanceViewStatus
Instance view status.
Name |
Type |
Description |
code
|
string
|
The status code.
|
displayStatus
|
string
|
The short localizable label for the status.
|
level
|
StatusLevelTypes
|
The level code.
|
message
|
string
|
The detailed status message, including for alerts and error messages.
|
time
|
string
|
The time of the status.
|
IPVersions
Available from Api-Version 2019-07-01 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'.
Name |
Type |
Description |
IPv4
|
string
|
|
IPv6
|
string
|
|
KeyVaultKeyReference
Specifies the location of the key encryption key in Key Vault.
Name |
Type |
Description |
keyUrl
|
string
|
The URL referencing a key encryption key in Key Vault.
|
sourceVault
|
SubResource
|
The relative URL of the Key Vault containing the key.
|
KeyVaultSecretReference
The extensions protected settings that are passed by reference, and consumed from key vault
Name |
Type |
Description |
secretUrl
|
string
|
The URL referencing a secret in a Key Vault.
|
sourceVault
|
SubResource
|
The relative URL of the Key Vault containing the secret.
|
LastPatchInstallationSummary
The installation summary of the latest installation operation for the virtual machine.
Name |
Type |
Description |
error
|
ApiError
|
The errors that were encountered during execution of the operation. The details array contains the list of them.
|
excludedPatchCount
|
integer
|
The number of all available patches but excluded explicitly by a customer-specified exclusion list match.
|
failedPatchCount
|
integer
|
The count of patches that failed installation.
|
installationActivityId
|
string
|
The activity ID of the operation that produced this result. It is used to correlate across CRP and extension logs.
|
installedPatchCount
|
integer
|
The count of patches that successfully installed.
|
lastModifiedTime
|
string
|
The UTC timestamp when the operation began.
|
maintenanceWindowExceeded
|
boolean
|
Describes whether the operation ran out of time before it completed all its intended actions
|
notSelectedPatchCount
|
integer
|
The number of all available patches but not going to be installed because it didn't match a classification or inclusion list entry.
|
pendingPatchCount
|
integer
|
The number of all available patches expected to be installed over the course of the patch installation operation.
|
startTime
|
string
|
The UTC timestamp when the operation began.
|
status
|
PatchOperationStatus
|
The overall success or failure status of the operation. It remains "InProgress" until the operation completes. At that point it will become "Unknown", "Failed", "Succeeded", or "CompletedWithWarnings."
|
LinuxConfiguration
Specifies the Linux operating system settings on the virtual machine. For a list of supported Linux distributions, see Linux on Azure-Endorsed Distributions.
Name |
Type |
Description |
disablePasswordAuthentication
|
boolean
|
Specifies whether password authentication should be disabled.
|
enableVMAgentPlatformUpdates
|
boolean
|
Indicates whether VMAgent Platform Updates is enabled for the Linux virtual machine. Default value is false.
|
patchSettings
|
LinuxPatchSettings
|
[Preview Feature] Specifies settings related to VM Guest Patching on Linux.
|
provisionVMAgent
|
boolean
|
Indicates whether virtual machine agent should be provisioned on the virtual machine. When this property is not specified in the request body, default behavior is to set it to true. This will ensure that VM Agent is installed on the VM so that extensions can be added to the VM later.
|
ssh
|
SshConfiguration
|
Specifies the ssh key configuration for a Linux OS.
|
LinuxPatchAssessmentMode
Specifies the mode of VM Guest Patch Assessment for the IaaS virtual machine.
Possible values are:
ImageDefault - You control the timing of patch assessments on a virtual machine.
AutomaticByPlatform - The platform will trigger periodic patch assessments. The property provisionVMAgent must be true.
Name |
Type |
Description |
AutomaticByPlatform
|
string
|
|
ImageDefault
|
string
|
|
LinuxPatchSettings
[Preview Feature] Specifies settings related to VM Guest Patching on Linux.
Name |
Type |
Description |
assessmentMode
|
LinuxPatchAssessmentMode
|
Specifies the mode of VM Guest Patch Assessment for the IaaS virtual machine.
Possible values are:
ImageDefault - You control the timing of patch assessments on a virtual machine.
AutomaticByPlatform - The platform will trigger periodic patch assessments. The property provisionVMAgent must be true.
|
automaticByPlatformSettings
|
LinuxVMGuestPatchAutomaticByPlatformSettings
|
Specifies additional settings for patch mode AutomaticByPlatform in VM Guest Patching on Linux.
|
patchMode
|
LinuxVMGuestPatchMode
|
Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated to virtual machine scale set with OrchestrationMode as Flexible.
Possible values are:
ImageDefault - The virtual machine's default patching configuration is used.
AutomaticByPlatform - The virtual machine will be automatically updated by the platform. The property provisionVMAgent must be true
|
Specifies the reboot setting for all AutomaticByPlatform patch installation operations.
Name |
Type |
Description |
Always
|
string
|
|
IfRequired
|
string
|
|
Never
|
string
|
|
Unknown
|
string
|
|
Specifies additional settings for patch mode AutomaticByPlatform in VM Guest Patching on Linux.
Name |
Type |
Description |
bypassPlatformSafetyChecksOnUserSchedule
|
boolean
|
Enables customer to schedule patching without accidental upgrades
|
rebootSetting
|
LinuxVMGuestPatchAutomaticByPlatformRebootSetting
|
Specifies the reboot setting for all AutomaticByPlatform patch installation operations.
|
LinuxVMGuestPatchMode
Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated to virtual machine scale set with OrchestrationMode as Flexible.
Possible values are:
ImageDefault - The virtual machine's default patching configuration is used.
AutomaticByPlatform - The virtual machine will be automatically updated by the platform. The property provisionVMAgent must be true
Name |
Type |
Description |
AutomaticByPlatform
|
string
|
|
ImageDefault
|
string
|
|
MaintenanceOperationResultCodeTypes
The Last Maintenance Operation Result Code.
Name |
Type |
Description |
MaintenanceAborted
|
string
|
|
MaintenanceCompleted
|
string
|
|
None
|
string
|
|
RetryLater
|
string
|
|
MaintenanceRedeployStatus
The Maintenance Operation status on the virtual machine.
Name |
Type |
Description |
isCustomerInitiatedMaintenanceAllowed
|
boolean
|
True, if customer is allowed to perform Maintenance.
|
lastOperationMessage
|
string
|
Message returned for the last Maintenance Operation.
|
lastOperationResultCode
|
MaintenanceOperationResultCodeTypes
|
The Last Maintenance Operation Result Code.
|
maintenanceWindowEndTime
|
string
|
End Time for the Maintenance Window.
|
maintenanceWindowStartTime
|
string
|
Start Time for the Maintenance Window.
|
preMaintenanceWindowEndTime
|
string
|
End Time for the Pre Maintenance Window.
|
preMaintenanceWindowStartTime
|
string
|
Start Time for the Pre Maintenance Window.
|
ManagedDiskParameters
The managed disk parameters.
Name |
Type |
Description |
diskEncryptionSet
|
DiskEncryptionSetParameters
|
Specifies the customer managed disk encryption set resource id for the managed disk.
|
id
|
string
|
Resource Id
|
securityProfile
|
VMDiskSecurityProfile
|
Specifies the security profile for the managed disk.
|
storageAccountType
|
StorageAccountTypes
|
Specifies the storage account type for the managed disk. NOTE: UltraSSD_LRS can only be used with data disks, it cannot be used with OS Disk.
|
Mode
Specifies the mode that ProxyAgent will execute on if the feature is enabled. ProxyAgent will start to audit or monitor but not enforce access control over requests to host endpoints in Audit mode, while in Enforce mode it will enforce access control. The default value is Enforce mode.
Name |
Type |
Description |
Audit
|
string
|
|
Enforce
|
string
|
|
NetworkApiVersion
specifies the Microsoft.Network API version used when creating networking resources in the Network Interface Configurations
Name |
Type |
Description |
2020-11-01
|
string
|
|
NetworkInterfaceAuxiliaryMode
Specifies whether the Auxiliary mode is enabled for the Network Interface resource.
Name |
Type |
Description |
AcceleratedConnections
|
string
|
|
Floating
|
string
|
|
None
|
string
|
|
NetworkInterfaceAuxiliarySku
Specifies whether the Auxiliary sku is enabled for the Network Interface resource.
Name |
Type |
Description |
A1
|
string
|
|
A2
|
string
|
|
A4
|
string
|
|
A8
|
string
|
|
None
|
string
|
|
NetworkInterfaceReference
Specifies the list of resource Ids for the network interfaces associated with the virtual machine.
Name |
Type |
Description |
id
|
string
|
Resource Id
|
properties.deleteOption
|
DeleteOptions
|
Specify what happens to the network interface when the VM is deleted
|
properties.primary
|
boolean
|
Specifies the primary network interface in case the virtual machine has more than 1 network interface.
|
NetworkProfile
Specifies the network interfaces of the virtual machine.
Name |
Type |
Description |
networkApiVersion
|
NetworkApiVersion
|
specifies the Microsoft.Network API version used when creating networking resources in the Network Interface Configurations
|
networkInterfaceConfigurations
|
VirtualMachineNetworkInterfaceConfiguration[]
|
Specifies the networking configurations that will be used to create the virtual machine networking resources.
|
networkInterfaces
|
NetworkInterfaceReference[]
|
Specifies the list of resource Ids for the network interfaces associated with the virtual machine.
|
OperatingSystemTypes
The Operating System type.
Name |
Type |
Description |
Linux
|
string
|
|
Windows
|
string
|
|
OSDisk
Specifies information about the operating system disk used by the virtual machine. For more information about disks, see About disks and VHDs for Azure virtual machines.
Name |
Type |
Description |
caching
|
CachingTypes
|
Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The defaulting behavior is: None for Standard storage. ReadOnly for Premium storage.
|
createOption
|
DiskCreateOptionTypes
|
Specifies how the virtual machine disk should be created. Possible values are Attach: This value is used when you are using a specialized disk to create the virtual machine. FromImage: This value is used when you are using an image to create the virtual machine. If you are using a platform image, you should also use the imageReference element described above. If you are using a marketplace image, you should also use the plan element previously described.
|
deleteOption
|
DiskDeleteOptionTypes
|
Specifies whether OS Disk should be deleted or detached upon VM deletion. Possible values are: Delete. If this value is used, the OS disk is deleted when VM is deleted. Detach. If this value is used, the os disk is retained after VM is deleted. The default value is set to Detach. For an ephemeral OS Disk, the default value is set to Delete. The user cannot change the delete option for an ephemeral OS Disk.
|
diffDiskSettings
|
DiffDiskSettings
|
Specifies the ephemeral Disk Settings for the operating system disk used by the virtual machine.
|
diskSizeGB
|
integer
|
Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image. The property 'diskSizeGB' is the number of bytes x 1024^3 for the disk and the value cannot be larger than 1023.
|
encryptionSettings
|
DiskEncryptionSettings
|
Specifies the encryption settings for the OS Disk. Minimum api-version: 2015-06-15.
|
image
|
VirtualHardDisk
|
The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. If SourceImage is provided, the destination virtual hard drive must not exist.
|
managedDisk
|
ManagedDiskParameters
|
The managed disk parameters.
|
name
|
string
|
The disk name.
|
osType
|
OperatingSystemTypes
|
This property allows you to specify the type of the OS that is included in the disk if creating a VM from user-image or a specialized VHD. Possible values are: Windows, Linux.
|
vhd
|
VirtualHardDisk
|
The virtual hard disk.
|
writeAcceleratorEnabled
|
boolean
|
Specifies whether writeAccelerator should be enabled or disabled on the disk.
|
OSImageNotificationProfile
Specifies OS Image Scheduled Event related configurations.
Name |
Type |
Description |
enable
|
boolean
|
Specifies whether the OS Image Scheduled event is enabled or disabled.
|
notBeforeTimeout
|
string
|
Length of time a Virtual Machine being reimaged or having its OS upgraded will have to potentially approve the OS Image Scheduled Event before the event is auto approved (timed out). The configuration is specified in ISO 8601 format, and the value must be 15 minutes (PT15M)
|
OSProfile
Specifies the operating system settings used while creating the virtual machine. Some of the settings cannot be changed once VM is provisioned.
Name |
Type |
Description |
adminPassword
|
string
|
Specifies the password of the administrator account.
Minimum-length (Windows): 8 characters
Minimum-length (Linux): 6 characters
Max-length (Windows): 123 characters
Max-length (Linux): 72 characters
Complexity requirements: 3 out of 4 conditions below need to be fulfilled Has lower characters Has upper characters Has a digit Has a special character (Regex match [\W_])
Disallowed values: "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", "Password22", "iloveyou!"
For resetting the password, see How to reset the Remote Desktop service or its login password in a Windows VM
For resetting root password, see Manage users, SSH, and check or repair disks on Azure Linux VMs using the VMAccess Extension
|
adminUsername
|
string
|
Specifies the name of the administrator account.
This property cannot be updated after the VM is created.
Windows-only restriction: Cannot end in "."
Disallowed values: "administrator", "admin", "user", "user1", "test", "user2", "test1", "user3", "admin1", "1", "123", "a", "actuser", "adm", "admin2", "aspnet", "backup", "console", "david", "guest", "john", "owner", "root", "server", "sql", "support", "support_388945a0", "sys", "test2", "test3", "user4", "user5".
Minimum-length (Linux): 1 character
Max-length (Linux): 64 characters
Max-length (Windows): 20 characters.
|
allowExtensionOperations
|
boolean
|
Specifies whether extension operations should be allowed on the virtual machine. This may only be set to False when no extensions are present on the virtual machine.
|
computerName
|
string
|
Specifies the host OS name of the virtual machine. This name cannot be updated after the VM is created. Max-length (Windows): 15 characters. Max-length (Linux): 64 characters. For naming conventions and restrictions see Azure infrastructure services implementation guidelines.
|
customData
|
string
|
Specifies a base-64 encoded string of custom data. The base-64 encoded string is decoded to a binary array that is saved as a file on the Virtual Machine. The maximum length of the binary array is 65535 bytes. Note: Do not pass any secrets or passwords in customData property. This property cannot be updated after the VM is created. The property 'customData' is passed to the VM to be saved as a file, for more information see Custom Data on Azure VMs. For using cloud-init for your Linux VM, see Using cloud-init to customize a Linux VM during creation.
|
linuxConfiguration
|
LinuxConfiguration
|
Specifies the Linux operating system settings on the virtual machine. For a list of supported Linux distributions, see Linux on Azure-Endorsed Distributions.
|
requireGuestProvisionSignal
|
boolean
|
Optional property which must either be set to True or omitted.
|
secrets
|
VaultSecretGroup[]
|
Specifies set of certificates that should be installed onto the virtual machine. To install certificates on a virtual machine it is recommended to use the Azure Key Vault virtual machine extension for Linux or the Azure Key Vault virtual machine extension for Windows.
|
windowsConfiguration
|
WindowsConfiguration
|
Specifies Windows operating system settings on the virtual machine.
|
PassNames
The pass name. Currently, the only allowable value is OobeSystem.
Name |
Type |
Description |
OobeSystem
|
string
|
|
PatchOperationStatus
The overall success or failure status of the operation. It remains "InProgress" until the operation completes. At that point it will become "Unknown", "Failed", "Succeeded", or "CompletedWithWarnings."
Name |
Type |
Description |
CompletedWithWarnings
|
string
|
|
Failed
|
string
|
|
InProgress
|
string
|
|
Succeeded
|
string
|
|
Unknown
|
string
|
|
PatchSettings
[Preview Feature] Specifies settings related to VM Guest Patching on Windows.
Name |
Type |
Description |
assessmentMode
|
WindowsPatchAssessmentMode
|
Specifies the mode of VM Guest patch assessment for the IaaS virtual machine.
Possible values are:
ImageDefault - You control the timing of patch assessments on a virtual machine.
AutomaticByPlatform - The platform will trigger periodic patch assessments. The property provisionVMAgent must be true.
|
automaticByPlatformSettings
|
WindowsVMGuestPatchAutomaticByPlatformSettings
|
Specifies additional settings for patch mode AutomaticByPlatform in VM Guest Patching on Windows.
|
enableHotpatching
|
boolean
|
Enables customers to patch their Azure VMs without requiring a reboot. For enableHotpatching, the 'provisionVMAgent' must be set to true and 'patchMode' must be set to 'AutomaticByPlatform'.
|
patchMode
|
WindowsVMGuestPatchMode
|
Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated to virtual machine scale set with OrchestrationMode as Flexible.
Possible values are:
Manual - You control the application of patches to a virtual machine. You do this by applying patches manually inside the VM. In this mode, automatic updates are disabled; the property WindowsConfiguration.enableAutomaticUpdates must be false
AutomaticByOS - The virtual machine will automatically be updated by the OS. The property WindowsConfiguration.enableAutomaticUpdates must be true.
AutomaticByPlatform - the virtual machine will automatically updated by the platform. The properties provisionVMAgent and WindowsConfiguration.enableAutomaticUpdates must be true
|
Plan
Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click Want to deploy programmatically, Get Started ->. Enter any required information and then click Save.
Name |
Type |
Description |
name
|
string
|
The plan ID.
|
product
|
string
|
Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element.
|
promotionCode
|
string
|
The promotion code.
|
publisher
|
string
|
The publisher ID.
|
ProtocolTypes
Specifies the protocol of WinRM listener. Possible values are: http, https.
Name |
Type |
Description |
Http
|
string
|
|
Https
|
string
|
|
ProxyAgentSettings
Specifies ProxyAgent settings while creating the virtual machine. Minimum api-version: 2023-09-01.
Name |
Type |
Description |
enabled
|
boolean
|
Specifies whether ProxyAgent feature should be enabled on the virtual machine or virtual machine scale set.
|
keyIncarnationId
|
integer
|
Increase the value of this property allows user to reset the key used for securing communication channel between guest and host.
|
mode
|
Mode
|
Specifies the mode that ProxyAgent will execute on if the feature is enabled. ProxyAgent will start to audit or monitor but not enforce access control over requests to host endpoints in Audit mode, while in Enforce mode it will enforce access control. The default value is Enforce mode.
|
PublicIPAddressSku
Describes the public IP Sku. It can only be set with OrchestrationMode as Flexible.
PublicIPAddressSkuName
Specify public IP sku name
Name |
Type |
Description |
Basic
|
string
|
|
Standard
|
string
|
|
PublicIPAddressSkuTier
Specify public IP sku tier
Name |
Type |
Description |
Global
|
string
|
|
Regional
|
string
|
|
PublicIPAllocationMethod
Specify the public IP allocation type
Name |
Type |
Description |
Dynamic
|
string
|
|
Static
|
string
|
|
ResourceIdentityType
The type of identity used for the virtual machine. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine.
Name |
Type |
Description |
None
|
string
|
|
SystemAssigned
|
string
|
|
SystemAssigned, UserAssigned
|
string
|
|
UserAssigned
|
string
|
|
ScheduledEventsAdditionalPublishingTargets
The configuration parameters used while publishing scheduledEventsAdditionalPublishingTargets.
Name |
Type |
Description |
eventGridAndResourceGraph
|
EventGridAndResourceGraph
|
The configuration parameters used while creating eventGridAndResourceGraph Scheduled Event setting.
|
ScheduledEventsPolicy
Specifies Redeploy, Reboot and ScheduledEventsAdditionalPublishingTargets Scheduled Event related configurations for the virtual machine.
Name |
Type |
Description |
scheduledEventsAdditionalPublishingTargets
|
ScheduledEventsAdditionalPublishingTargets
|
The configuration parameters used while publishing scheduledEventsAdditionalPublishingTargets.
|
userInitiatedReboot
|
UserInitiatedReboot
|
The configuration parameters used while creating userInitiatedReboot scheduled event setting creation.
|
userInitiatedRedeploy
|
UserInitiatedRedeploy
|
The configuration parameters used while creating userInitiatedRedeploy scheduled event setting creation.
|
ScheduledEventsProfile
Specifies Scheduled Event related configurations.
securityEncryptionTypes
Specifies the EncryptionType of the managed disk. It is set to DiskWithVMGuestState for encryption of the managed disk along with VMGuestState blob, VMGuestStateOnly for encryption of just the VMGuestState blob, and NonPersistedTPM for not persisting firmware state in the VMGuestState blob.. Note: It can be set for only Confidential VMs.
Name |
Type |
Description |
DiskWithVMGuestState
|
string
|
|
NonPersistedTPM
|
string
|
|
VMGuestStateOnly
|
string
|
|
SecurityProfile
Specifies the Security related profile settings for the virtual machine.
Name |
Type |
Description |
encryptionAtHost
|
boolean
|
This property can be used by user in the request to enable or disable the Host Encryption for the virtual machine or virtual machine scale set. This will enable the encryption for all the disks including Resource/Temp disk at host itself. The default behavior is: The Encryption at host will be disabled unless this property is set to true for the resource.
|
encryptionIdentity
|
EncryptionIdentity
|
Specifies the Managed Identity used by ADE to get access token for keyvault operations.
|
proxyAgentSettings
|
ProxyAgentSettings
|
Specifies ProxyAgent settings while creating the virtual machine. Minimum api-version: 2023-09-01.
|
securityType
|
SecurityTypes
|
Specifies the SecurityType of the virtual machine. It has to be set to any specified value to enable UefiSettings. The default behavior is: UefiSettings will not be enabled unless this property is set.
|
uefiSettings
|
UefiSettings
|
Specifies the security settings like secure boot and vTPM used while creating the virtual machine. Minimum api-version: 2020-12-01.
|
SecurityTypes
Specifies the SecurityType of the virtual machine. It has to be set to any specified value to enable UefiSettings. The default behavior is: UefiSettings will not be enabled unless this property is set.
Name |
Type |
Description |
ConfidentialVM
|
string
|
|
TrustedLaunch
|
string
|
|
SettingNames
Specifies the name of the setting to which the content applies. Possible values are: FirstLogonCommands and AutoLogon.
Name |
Type |
Description |
AutoLogon
|
string
|
|
FirstLogonCommands
|
string
|
|
SshConfiguration
Specifies the ssh key configuration for a Linux OS.
Name |
Type |
Description |
publicKeys
|
SshPublicKey[]
|
The list of SSH public keys used to authenticate with linux based VMs.
|
SshPublicKey
The list of SSH public keys used to authenticate with linux based VMs.
Name |
Type |
Description |
keyData
|
string
|
SSH public key certificate used to authenticate with the VM through ssh. The key needs to be at least 2048-bit and in ssh-rsa format. For creating ssh keys, see [Create SSH keys on Linux and Mac for Linux VMs in Azure]https://docs.microsoft.com/azure/virtual-machines/linux/create-ssh-keys-detailed).
|
path
|
string
|
Specifies the full path on the created VM where ssh public key is stored. If the file already exists, the specified key is appended to the file. Example: /home/user/.ssh/authorized_keys
|
StatusLevelTypes
The level code.
Name |
Type |
Description |
Error
|
string
|
|
Info
|
string
|
|
Warning
|
string
|
|
StorageAccountTypes
Specifies the storage account type for the managed disk. NOTE: UltraSSD_LRS can only be used with data disks, it cannot be used with OS Disk.
Name |
Type |
Description |
PremiumV2_LRS
|
string
|
|
Premium_LRS
|
string
|
|
Premium_ZRS
|
string
|
|
StandardSSD_LRS
|
string
|
|
StandardSSD_ZRS
|
string
|
|
Standard_LRS
|
string
|
|
UltraSSD_LRS
|
string
|
|
StorageProfile
Specifies the storage settings for the virtual machine disks.
Name |
Type |
Description |
dataDisks
|
DataDisk[]
|
Specifies the parameters that are used to add a data disk to a virtual machine. For more information about disks, see About disks and VHDs for Azure virtual machines.
|
diskControllerType
|
DiskControllerTypes
|
Specifies the disk controller type configured for the VM. Note: This property will be set to the default disk controller type if not specified provided virtual machine is being created with 'hyperVGeneration' set to V2 based on the capabilities of the operating system disk and VM size from the the specified minimum api version. You need to deallocate the VM before updating its disk controller type unless you are updating the VM size in the VM configuration which implicitly deallocates and reallocates the VM. Minimum api-version: 2022-08-01.
|
imageReference
|
ImageReference
|
Specifies information about the image to use. You can specify information about platform images, marketplace images, or virtual machine images. This element is required when you want to use a platform image, marketplace image, or virtual machine image, but is not used in other creation operations.
|
osDisk
|
OSDisk
|
Specifies information about the operating system disk used by the virtual machine. For more information about disks, see About disks and VHDs for Azure virtual machines.
|
SubResource
The relative URL of the Key Vault containing the secret.
Name |
Type |
Description |
id
|
string
|
Resource Id
|
TerminateNotificationProfile
Specifies Terminate Scheduled Event related configurations.
Name |
Type |
Description |
enable
|
boolean
|
Specifies whether the Terminate Scheduled event is enabled or disabled.
|
notBeforeTimeout
|
string
|
Configurable length of time a Virtual Machine being deleted will have to potentially approve the Terminate Scheduled Event before the event is auto approved (timed out). The configuration must be specified in ISO 8601 format, the default value is 5 minutes (PT5M)
|
UefiSettings
Specifies the security settings like secure boot and vTPM used while creating the virtual machine. Minimum api-version: 2020-12-01.
Name |
Type |
Description |
secureBootEnabled
|
boolean
|
Specifies whether secure boot should be enabled on the virtual machine. Minimum api-version: 2020-12-01.
|
vTpmEnabled
|
boolean
|
Specifies whether vTPM should be enabled on the virtual machine. Minimum api-version: 2020-12-01.
|
UserAssignedIdentities
The list of user identities associated with the Virtual Machine. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
UserInitiatedReboot
The configuration parameters used while creating userInitiatedReboot scheduled event setting creation.
Name |
Type |
Description |
automaticallyApprove
|
boolean
|
Specifies Reboot Scheduled Event related configurations.
|
UserInitiatedRedeploy
The configuration parameters used while creating userInitiatedRedeploy scheduled event setting creation.
Name |
Type |
Description |
automaticallyApprove
|
boolean
|
Specifies Redeploy Scheduled Event related configurations.
|
VaultCertificate
The list of key vault references in SourceVault which contain certificates.
Name |
Type |
Description |
certificateStore
|
string
|
For Windows VMs, specifies the certificate store on the Virtual Machine to which the certificate should be added. The specified certificate store is implicitly in the LocalMachine account. For Linux VMs, the certificate file is placed under the /var/lib/waagent directory, with the file name <UppercaseThumbprint>.crt for the X509 certificate file and <UppercaseThumbprint>.prv for private key. Both of these files are .pem formatted.
|
certificateUrl
|
string
|
This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, see Add a key or secret to the key vault. In this case, your certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded in UTF-8:
{ "data":"", "dataType":"pfx", "password":"" } To install certificates on a virtual machine it is recommended to use the Azure Key Vault virtual machine extension for Linux or the Azure Key Vault virtual machine extension for Windows.
|
VaultSecretGroup
Specifies set of certificates that should be installed onto the virtual machine. To install certificates on a virtual machine it is recommended to use the Azure Key Vault virtual machine extension for Linux or the Azure Key Vault virtual machine extension for Windows.
Name |
Type |
Description |
sourceVault
|
SubResource
|
The relative URL of the Key Vault containing all of the certificates in VaultCertificates.
|
vaultCertificates
|
VaultCertificate[]
|
The list of key vault references in SourceVault which contain certificates.
|
VirtualHardDisk
The virtual hard disk.
Name |
Type |
Description |
uri
|
string
|
Specifies the virtual hard disk's uri.
|
VirtualMachine
Describes a Virtual Machine.
Name |
Type |
Description |
etag
|
string
|
Etag is property returned in Create/Update/Get response of the VM, so that customer can supply it in the header to ensure optimistic updates.
|
extendedLocation
|
ExtendedLocation
|
The extended location of the Virtual Machine.
|
id
|
string
|
Resource Id
|
identity
|
VirtualMachineIdentity
|
The identity of the virtual machine, if configured.
|
location
|
string
|
Resource location
|
managedBy
|
string
|
ManagedBy is set to Virtual Machine Scale Set(VMSS) flex ARM resourceID, if the VM is part of the VMSS. This property is used by platform for internal resource group delete optimization.
|
name
|
string
|
Resource name
|
plan
|
Plan
|
Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click Want to deploy programmatically, Get Started ->. Enter any required information and then click Save.
|
properties.additionalCapabilities
|
AdditionalCapabilities
|
Specifies additional capabilities enabled or disabled on the virtual machine.
|
properties.applicationProfile
|
ApplicationProfile
|
Specifies the gallery applications that should be made available to the VM/VMSS.
|
properties.availabilitySet
|
SubResource
|
Specifies information about the availability set that the virtual machine should be assigned to. Virtual machines specified in the same availability set are allocated to different nodes to maximize availability. For more information about availability sets, see Availability sets overview. For more information on Azure planned maintenance, see Maintenance and updates for Virtual Machines in Azure. Currently, a VM can only be added to availability set at creation time. The availability set to which the VM is being added should be under the same resource group as the availability set resource. An existing VM cannot be added to an availability set. This property cannot exist along with a non-null properties.virtualMachineScaleSet reference.
|
properties.billingProfile
|
BillingProfile
|
Specifies the billing related details of a Azure Spot virtual machine. Minimum api-version: 2019-03-01.
|
properties.capacityReservation
|
CapacityReservationProfile
|
Specifies information about the capacity reservation that is used to allocate virtual machine. Minimum api-version: 2021-04-01.
|
properties.diagnosticsProfile
|
DiagnosticsProfile
|
Specifies the boot diagnostic settings state. Minimum api-version: 2015-06-15.
|
properties.evictionPolicy
|
VirtualMachineEvictionPolicyTypes
|
Specifies the eviction policy for the Azure Spot virtual machine and Azure Spot scale set. For Azure Spot virtual machines, both 'Deallocate' and 'Delete' are supported and the minimum api-version is 2019-03-01. For Azure Spot scale sets, both 'Deallocate' and 'Delete' are supported and the minimum api-version is 2017-10-30-preview.
|
properties.extensionsTimeBudget
|
string
|
Specifies the time alloted for all extensions to start. The time duration should be between 15 minutes and 120 minutes (inclusive) and should be specified in ISO 8601 format. The default value is 90 minutes (PT1H30M). Minimum api-version: 2020-06-01.
|
properties.hardwareProfile
|
HardwareProfile
|
Specifies the hardware settings for the virtual machine.
|
properties.host
|
SubResource
|
Specifies information about the dedicated host that the virtual machine resides in. Minimum api-version: 2018-10-01.
|
properties.hostGroup
|
SubResource
|
Specifies information about the dedicated host group that the virtual machine resides in. Note: User cannot specify both host and hostGroup properties. Minimum api-version: 2020-06-01.
|
properties.instanceView
|
VirtualMachineInstanceView
|
The virtual machine instance view.
|
properties.licenseType
|
string
|
Specifies that the image or disk that is being used was licensed on-premises.
Possible values for Windows Server operating system are:
Windows_Client
Windows_Server
Possible values for Linux Server operating system are:
RHEL_BYOS (for RHEL)
SLES_BYOS (for SUSE)
For more information, see Azure Hybrid Use Benefit for Windows Server
Azure Hybrid Use Benefit for Linux Server
Minimum api-version: 2015-06-15
|
properties.networkProfile
|
NetworkProfile
|
Specifies the network interfaces of the virtual machine.
|
properties.osProfile
|
OSProfile
|
Specifies the operating system settings used while creating the virtual machine. Some of the settings cannot be changed once VM is provisioned.
|
properties.platformFaultDomain
|
integer
|
Specifies the scale set logical fault domain into which the Virtual Machine will be created. By default, the Virtual Machine will by automatically assigned to a fault domain that best maintains balance across available fault domains. This is applicable only if the 'virtualMachineScaleSet' property of this Virtual Machine is set. The Virtual Machine Scale Set that is referenced, must have 'platformFaultDomainCount' greater than 1. This property cannot be updated once the Virtual Machine is created. Fault domain assignment can be viewed in the Virtual Machine Instance View. Minimum api‐version: 2020‐12‐01.
|
properties.priority
|
VirtualMachinePriorityTypes
|
Specifies the priority for the virtual machine. Minimum api-version: 2019-03-01
|
properties.provisioningState
|
string
|
The provisioning state, which only appears in the response.
|
properties.proximityPlacementGroup
|
SubResource
|
Specifies information about the proximity placement group that the virtual machine should be assigned to. Minimum api-version: 2018-04-01.
|
properties.scheduledEventsPolicy
|
ScheduledEventsPolicy
|
Specifies Redeploy, Reboot and ScheduledEventsAdditionalPublishingTargets Scheduled Event related configurations for the virtual machine.
|
properties.scheduledEventsProfile
|
ScheduledEventsProfile
|
Specifies Scheduled Event related configurations.
|
properties.securityProfile
|
SecurityProfile
|
Specifies the Security related profile settings for the virtual machine.
|
properties.storageProfile
|
StorageProfile
|
Specifies the storage settings for the virtual machine disks.
|
properties.timeCreated
|
string
|
Specifies the time at which the Virtual Machine resource was created. Minimum api-version: 2021-11-01.
|
properties.userData
|
string
|
UserData for the VM, which must be base-64 encoded. Customer should not pass any secrets in here. Minimum api-version: 2021-03-01.
|
properties.virtualMachineScaleSet
|
SubResource
|
Specifies information about the virtual machine scale set that the virtual machine should be assigned to. Virtual machines specified in the same virtual machine scale set are allocated to different nodes to maximize availability. Currently, a VM can only be added to virtual machine scale set at creation time. An existing VM cannot be added to a virtual machine scale set. This property cannot exist along with a non-null properties.availabilitySet reference. Minimum api‐version: 2019‐03‐01.
|
properties.vmId
|
string
|
Specifies the VM unique ID which is a 128-bits identifier that is encoded and stored in all Azure IaaS VMs SMBIOS and can be read using platform BIOS commands.
|
resources
|
VirtualMachineExtension[]
|
The virtual machine child extension resources.
|
tags
|
object
|
Resource tags
|
type
|
string
|
Resource type
|
zones
|
string[]
|
The virtual machine zones.
|
VirtualMachineAgentInstanceView
The VM Agent running on the virtual machine.
VirtualMachineEvictionPolicyTypes
Specifies the eviction policy for the Azure Spot virtual machine and Azure Spot scale set. For Azure Spot virtual machines, both 'Deallocate' and 'Delete' are supported and the minimum api-version is 2019-03-01. For Azure Spot scale sets, both 'Deallocate' and 'Delete' are supported and the minimum api-version is 2017-10-30-preview.
Name |
Type |
Description |
Deallocate
|
string
|
|
Delete
|
string
|
|
VirtualMachineExtension
The virtual machine child extension resources.
Name |
Type |
Description |
id
|
string
|
Resource Id
|
location
|
string
|
Resource location
|
name
|
string
|
Resource name
|
properties.autoUpgradeMinorVersion
|
boolean
|
Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true.
|
properties.enableAutomaticUpgrade
|
boolean
|
Indicates whether the extension should be automatically upgraded by the platform if there is a newer version of the extension available.
|
properties.forceUpdateTag
|
string
|
How the extension handler should be forced to update even if the extension configuration has not changed.
|
properties.instanceView
|
VirtualMachineExtensionInstanceView
|
The virtual machine extension instance view.
|
properties.protectedSettings
|
object
|
The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all.
|
properties.protectedSettingsFromKeyVault
|
KeyVaultSecretReference
|
The extensions protected settings that are passed by reference, and consumed from key vault
|
properties.provisionAfterExtensions
|
string[]
|
Collection of extension names after which this extension needs to be provisioned.
|
properties.provisioningState
|
string
|
The provisioning state, which only appears in the response.
|
properties.publisher
|
string
|
The name of the extension handler publisher.
|
properties.settings
|
object
|
Json formatted public settings for the extension.
|
properties.suppressFailures
|
boolean
|
Indicates whether failures stemming from the extension will be suppressed (Operational failures such as not connecting to the VM will not be suppressed regardless of this value). The default is false.
|
properties.type
|
string
|
Specifies the type of the extension; an example is "CustomScriptExtension".
|
properties.typeHandlerVersion
|
string
|
Specifies the version of the script handler.
|
tags
|
object
|
Resource tags
|
type
|
string
|
Resource type
|
VirtualMachineExtensionHandlerInstanceView
The virtual machine extension handler instance view.
Name |
Type |
Description |
status
|
InstanceViewStatus
|
The extension handler status.
|
type
|
string
|
Specifies the type of the extension; an example is "CustomScriptExtension".
|
typeHandlerVersion
|
string
|
Specifies the version of the script handler.
|
VirtualMachineExtensionInstanceView
The virtual machine extension instance view.
Name |
Type |
Description |
name
|
string
|
The virtual machine extension name.
|
statuses
|
InstanceViewStatus[]
|
The resource status information.
|
substatuses
|
InstanceViewStatus[]
|
The resource status information.
|
type
|
string
|
Specifies the type of the extension; an example is "CustomScriptExtension".
|
typeHandlerVersion
|
string
|
Specifies the version of the script handler.
|
VirtualMachineHealthStatus
The health status for the VM.
VirtualMachineIdentity
The identity of the virtual machine, if configured.
Name |
Type |
Description |
principalId
|
string
|
The principal id of virtual machine identity. This property will only be provided for a system assigned identity.
|
tenantId
|
string
|
The tenant id associated with the virtual machine. This property will only be provided for a system assigned identity.
|
type
|
ResourceIdentityType
|
The type of identity used for the virtual machine. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine.
|
userAssignedIdentities
|
UserAssignedIdentities
|
The list of user identities associated with the Virtual Machine. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
|
VirtualMachineInstanceView
The virtual machine instance view.
Name |
Type |
Description |
assignedHost
|
string
|
Resource id of the dedicated host, on which the virtual machine is allocated through automatic placement, when the virtual machine is associated with a dedicated host group that has automatic placement enabled. Minimum api-version: 2020-06-01.
|
bootDiagnostics
|
BootDiagnosticsInstanceView
|
Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. You can easily view the output of your console log. Azure also enables you to see a screenshot of the VM from the hypervisor.
|
computerName
|
string
|
The computer name assigned to the virtual machine.
|
disks
|
DiskInstanceView[]
|
The virtual machine disk information.
|
extensions
|
VirtualMachineExtensionInstanceView[]
|
The extensions information.
|
hyperVGeneration
|
HyperVGenerationType
|
Specifies the HyperVGeneration Type associated with a resource
|
isVMInStandbyPool
|
boolean
|
[Preview Feature] Specifies whether the VM is currently in or out of the Standby Pool.
|
maintenanceRedeployStatus
|
MaintenanceRedeployStatus
|
The Maintenance Operation status on the virtual machine.
|
osName
|
string
|
The Operating System running on the virtual machine.
|
osVersion
|
string
|
The version of Operating System running on the virtual machine.
|
patchStatus
|
VirtualMachinePatchStatus
|
[Preview Feature] The status of virtual machine patch operations.
|
platformFaultDomain
|
integer
|
Specifies the fault domain of the virtual machine.
|
platformUpdateDomain
|
integer
|
Specifies the update domain of the virtual machine.
|
rdpThumbPrint
|
string
|
The Remote desktop certificate thumbprint.
|
statuses
|
InstanceViewStatus[]
|
The resource status information.
|
vmAgent
|
VirtualMachineAgentInstanceView
|
The VM Agent running on the virtual machine.
|
vmHealth
|
VirtualMachineHealthStatus
|
The health status for the VM.
|
VirtualMachineIpTag
The list of IP tags associated with the public IP address.
Name |
Type |
Description |
ipTagType
|
string
|
IP tag type. Example: FirstPartyUsage.
|
tag
|
string
|
IP tag associated with the public IP. Example: SQL, Storage etc.
|
VirtualMachineNetworkInterfaceConfiguration
Specifies the networking configurations that will be used to create the virtual machine networking resources.
Name |
Type |
Description |
name
|
string
|
The network interface configuration name.
|
properties.auxiliaryMode
|
NetworkInterfaceAuxiliaryMode
|
Specifies whether the Auxiliary mode is enabled for the Network Interface resource.
|
properties.auxiliarySku
|
NetworkInterfaceAuxiliarySku
|
Specifies whether the Auxiliary sku is enabled for the Network Interface resource.
|
properties.deleteOption
|
DeleteOptions
|
Specify what happens to the network interface when the VM is deleted
|
properties.disableTcpStateTracking
|
boolean
|
Specifies whether the network interface is disabled for tcp state tracking.
|
properties.dnsSettings
|
VirtualMachineNetworkInterfaceDnsSettingsConfiguration
|
The dns settings to be applied on the network interfaces.
|
properties.dscpConfiguration
|
SubResource
|
|
properties.enableAcceleratedNetworking
|
boolean
|
Specifies whether the network interface is accelerated networking-enabled.
|
properties.enableFpga
|
boolean
|
Specifies whether the network interface is FPGA networking-enabled.
|
properties.enableIPForwarding
|
boolean
|
Whether IP forwarding enabled on this NIC.
|
properties.ipConfigurations
|
VirtualMachineNetworkInterfaceIPConfiguration[]
|
Specifies the IP configurations of the network interface.
|
properties.networkSecurityGroup
|
SubResource
|
The network security group.
|
properties.primary
|
boolean
|
Specifies the primary network interface in case the virtual machine has more than 1 network interface.
|
VirtualMachineNetworkInterfaceDnsSettingsConfiguration
The dns settings to be applied on the network interfaces.
Name |
Type |
Description |
dnsServers
|
string[]
|
List of DNS servers IP addresses
|
VirtualMachineNetworkInterfaceIPConfiguration
Specifies the IP configurations of the network interface.
Name |
Type |
Description |
name
|
string
|
The IP configuration name.
|
properties.applicationGatewayBackendAddressPools
|
SubResource[]
|
Specifies an array of references to backend address pools of application gateways. A virtual machine can reference backend address pools of multiple application gateways. Multiple virtual machines cannot use the same application gateway.
|
properties.applicationSecurityGroups
|
SubResource[]
|
Specifies an array of references to application security group.
|
properties.loadBalancerBackendAddressPools
|
SubResource[]
|
Specifies an array of references to backend address pools of load balancers. A virtual machine can reference backend address pools of one public and one internal load balancer. [Multiple virtual machines cannot use the same basic sku load balancer].
|
properties.primary
|
boolean
|
Specifies the primary network interface in case the virtual machine has more than 1 network interface.
|
properties.privateIPAddressVersion
|
IPVersions
|
Available from Api-Version 2017-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'.
|
properties.publicIPAddressConfiguration
|
VirtualMachinePublicIPAddressConfiguration
|
The publicIPAddressConfiguration.
|
properties.subnet
|
SubResource
|
Specifies the identifier of the subnet.
|
VirtualMachinePatchStatus
[Preview Feature] The status of virtual machine patch operations.
Name |
Type |
Description |
availablePatchSummary
|
AvailablePatchSummary
|
The available patch summary of the latest assessment operation for the virtual machine.
|
configurationStatuses
|
InstanceViewStatus[]
|
The enablement status of the specified patchMode
|
lastPatchInstallationSummary
|
LastPatchInstallationSummary
|
The installation summary of the latest installation operation for the virtual machine.
|
VirtualMachinePriorityTypes
Specifies the priority for the virtual machine. Minimum api-version: 2019-03-01
Name |
Type |
Description |
Low
|
string
|
|
Regular
|
string
|
|
Spot
|
string
|
|
VirtualMachinePublicIPAddressConfiguration
The publicIPAddressConfiguration.
Name |
Type |
Description |
name
|
string
|
The publicIP address configuration name.
|
properties.deleteOption
|
DeleteOptions
|
Specify what happens to the public IP address when the VM is deleted
|
properties.dnsSettings
|
VirtualMachinePublicIPAddressDnsSettingsConfiguration
|
The dns settings to be applied on the publicIP addresses .
|
properties.idleTimeoutInMinutes
|
integer
|
The idle timeout of the public IP address.
|
properties.ipTags
|
VirtualMachineIpTag[]
|
The list of IP tags associated with the public IP address.
|
properties.publicIPAddressVersion
|
IPVersions
|
Available from Api-Version 2019-07-01 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'.
|
properties.publicIPAllocationMethod
|
PublicIPAllocationMethod
|
Specify the public IP allocation type
|
properties.publicIPPrefix
|
SubResource
|
The PublicIPPrefix from which to allocate publicIP addresses.
|
sku
|
PublicIPAddressSku
|
Describes the public IP Sku. It can only be set with OrchestrationMode as Flexible.
|
VirtualMachinePublicIPAddressDnsSettingsConfiguration
The dns settings to be applied on the publicIP addresses .
Name |
Type |
Description |
domainNameLabel
|
string
|
The Domain name label prefix of the PublicIPAddress resources that will be created. The generated name label is the concatenation of the domain name label and vm network profile unique ID.
|
domainNameLabelScope
|
DomainNameLabelScopeTypes
|
The Domain name label scope of the PublicIPAddress resources that will be created. The generated name label is the concatenation of the hashed domain name label with policy according to the domain name label scope and vm network profile unique ID.
|
VirtualMachineSizeTypes
Specifies the size of the virtual machine. The enum data type is currently deprecated and will be removed by December 23rd 2023. The recommended way to get the list of available sizes is using these APIs: List all available virtual machine sizes in an availability set, List all available virtual machine sizes in a region, List all available virtual machine sizes for resizing. For more information about virtual machine sizes, see Sizes for virtual machines. The available VM sizes depend on region and availability set.
Name |
Type |
Description |
Basic_A0
|
string
|
|
Basic_A1
|
string
|
|
Basic_A2
|
string
|
|
Basic_A3
|
string
|
|
Basic_A4
|
string
|
|
Standard_A0
|
string
|
|
Standard_A1
|
string
|
|
Standard_A10
|
string
|
|
Standard_A11
|
string
|
|
Standard_A1_v2
|
string
|
|
Standard_A2
|
string
|
|
Standard_A2_v2
|
string
|
|
Standard_A2m_v2
|
string
|
|
Standard_A3
|
string
|
|
Standard_A4
|
string
|
|
Standard_A4_v2
|
string
|
|
Standard_A4m_v2
|
string
|
|
Standard_A5
|
string
|
|
Standard_A6
|
string
|
|
Standard_A7
|
string
|
|
Standard_A8
|
string
|
|
Standard_A8_v2
|
string
|
|
Standard_A8m_v2
|
string
|
|
Standard_A9
|
string
|
|
Standard_B1ms
|
string
|
|
Standard_B1s
|
string
|
|
Standard_B2ms
|
string
|
|
Standard_B2s
|
string
|
|
Standard_B4ms
|
string
|
|
Standard_B8ms
|
string
|
|
Standard_D1
|
string
|
|
Standard_D11
|
string
|
|
Standard_D11_v2
|
string
|
|
Standard_D12
|
string
|
|
Standard_D12_v2
|
string
|
|
Standard_D13
|
string
|
|
Standard_D13_v2
|
string
|
|
Standard_D14
|
string
|
|
Standard_D14_v2
|
string
|
|
Standard_D15_v2
|
string
|
|
Standard_D16_v3
|
string
|
|
Standard_D16s_v3
|
string
|
|
Standard_D1_v2
|
string
|
|
Standard_D2
|
string
|
|
Standard_D2_v2
|
string
|
|
Standard_D2_v3
|
string
|
|
Standard_D2s_v3
|
string
|
|
Standard_D3
|
string
|
|
Standard_D32_v3
|
string
|
|
Standard_D32s_v3
|
string
|
|
Standard_D3_v2
|
string
|
|
Standard_D4
|
string
|
|
Standard_D4_v2
|
string
|
|
Standard_D4_v3
|
string
|
|
Standard_D4s_v3
|
string
|
|
Standard_D5_v2
|
string
|
|
Standard_D64_v3
|
string
|
|
Standard_D64s_v3
|
string
|
|
Standard_D8_v3
|
string
|
|
Standard_D8s_v3
|
string
|
|
Standard_DS1
|
string
|
|
Standard_DS11
|
string
|
|
Standard_DS11_v2
|
string
|
|
Standard_DS12
|
string
|
|
Standard_DS12_v2
|
string
|
|
Standard_DS13
|
string
|
|
Standard_DS13-2_v2
|
string
|
|
Standard_DS13-4_v2
|
string
|
|
Standard_DS13_v2
|
string
|
|
Standard_DS14
|
string
|
|
Standard_DS14-4_v2
|
string
|
|
Standard_DS14-8_v2
|
string
|
|
Standard_DS14_v2
|
string
|
|
Standard_DS15_v2
|
string
|
|
Standard_DS1_v2
|
string
|
|
Standard_DS2
|
string
|
|
Standard_DS2_v2
|
string
|
|
Standard_DS3
|
string
|
|
Standard_DS3_v2
|
string
|
|
Standard_DS4
|
string
|
|
Standard_DS4_v2
|
string
|
|
Standard_DS5_v2
|
string
|
|
Standard_E16_v3
|
string
|
|
Standard_E16s_v3
|
string
|
|
Standard_E2_v3
|
string
|
|
Standard_E2s_v3
|
string
|
|
Standard_E32-16_v3
|
string
|
|
Standard_E32-8s_v3
|
string
|
|
Standard_E32_v3
|
string
|
|
Standard_E32s_v3
|
string
|
|
Standard_E4_v3
|
string
|
|
Standard_E4s_v3
|
string
|
|
Standard_E64-16s_v3
|
string
|
|
Standard_E64-32s_v3
|
string
|
|
Standard_E64_v3
|
string
|
|
Standard_E64s_v3
|
string
|
|
Standard_E8_v3
|
string
|
|
Standard_E8s_v3
|
string
|
|
Standard_F1
|
string
|
|
Standard_F16
|
string
|
|
Standard_F16s
|
string
|
|
Standard_F16s_v2
|
string
|
|
Standard_F1s
|
string
|
|
Standard_F2
|
string
|
|
Standard_F2s
|
string
|
|
Standard_F2s_v2
|
string
|
|
Standard_F32s_v2
|
string
|
|
Standard_F4
|
string
|
|
Standard_F4s
|
string
|
|
Standard_F4s_v2
|
string
|
|
Standard_F64s_v2
|
string
|
|
Standard_F72s_v2
|
string
|
|
Standard_F8
|
string
|
|
Standard_F8s
|
string
|
|
Standard_F8s_v2
|
string
|
|
Standard_G1
|
string
|
|
Standard_G2
|
string
|
|
Standard_G3
|
string
|
|
Standard_G4
|
string
|
|
Standard_G5
|
string
|
|
Standard_GS1
|
string
|
|
Standard_GS2
|
string
|
|
Standard_GS3
|
string
|
|
Standard_GS4
|
string
|
|
Standard_GS4-4
|
string
|
|
Standard_GS4-8
|
string
|
|
Standard_GS5
|
string
|
|
Standard_GS5-16
|
string
|
|
Standard_GS5-8
|
string
|
|
Standard_H16
|
string
|
|
Standard_H16m
|
string
|
|
Standard_H16mr
|
string
|
|
Standard_H16r
|
string
|
|
Standard_H8
|
string
|
|
Standard_H8m
|
string
|
|
Standard_L16s
|
string
|
|
Standard_L32s
|
string
|
|
Standard_L4s
|
string
|
|
Standard_L8s
|
string
|
|
Standard_M128-32ms
|
string
|
|
Standard_M128-64ms
|
string
|
|
Standard_M128ms
|
string
|
|
Standard_M128s
|
string
|
|
Standard_M64-16ms
|
string
|
|
Standard_M64-32ms
|
string
|
|
Standard_M64ms
|
string
|
|
Standard_M64s
|
string
|
|
Standard_NC12
|
string
|
|
Standard_NC12s_v2
|
string
|
|
Standard_NC12s_v3
|
string
|
|
Standard_NC24
|
string
|
|
Standard_NC24r
|
string
|
|
Standard_NC24rs_v2
|
string
|
|
Standard_NC24rs_v3
|
string
|
|
Standard_NC24s_v2
|
string
|
|
Standard_NC24s_v3
|
string
|
|
Standard_NC6
|
string
|
|
Standard_NC6s_v2
|
string
|
|
Standard_NC6s_v3
|
string
|
|
Standard_ND12s
|
string
|
|
Standard_ND24rs
|
string
|
|
Standard_ND24s
|
string
|
|
Standard_ND6s
|
string
|
|
Standard_NV12
|
string
|
|
Standard_NV24
|
string
|
|
Standard_NV6
|
string
|
|
VMDiskSecurityProfile
Specifies the security profile for the managed disk.
Name |
Type |
Description |
diskEncryptionSet
|
DiskEncryptionSetParameters
|
Specifies the customer managed disk encryption set resource id for the managed disk that is used for Customer Managed Key encrypted ConfidentialVM OS Disk and VMGuest blob.
|
securityEncryptionType
|
securityEncryptionTypes
|
Specifies the EncryptionType of the managed disk. It is set to DiskWithVMGuestState for encryption of the managed disk along with VMGuestState blob, VMGuestStateOnly for encryption of just the VMGuestState blob, and NonPersistedTPM for not persisting firmware state in the VMGuestState blob.. Note: It can be set for only Confidential VMs.
|
VMGalleryApplication
Specifies the gallery applications that should be made available to the VM/VMSS
Name |
Type |
Description |
configurationReference
|
string
|
Optional, Specifies the uri to an azure blob that will replace the default configuration for the package if provided
|
enableAutomaticUpgrade
|
boolean
|
If set to true, when a new Gallery Application version is available in PIR/SIG, it will be automatically updated for the VM/VMSS
|
order
|
integer
|
Optional, Specifies the order in which the packages have to be installed
|
packageReferenceId
|
string
|
Specifies the GalleryApplicationVersion resource id on the form of /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{application}/versions/{version}
|
tags
|
string
|
Optional, Specifies a passthrough value for more generic context.
|
treatFailureAsDeploymentFailure
|
boolean
|
Optional, If true, any failure for any operation in the VmApplication will fail the deployment
|
VMSizeProperties
Specifies the properties for customizing the size of the virtual machine. Minimum api-version: 2021-07-01. This feature is still in preview mode and is not supported for VirtualMachineScaleSet. Please follow the instructions in VM Customization for more details.
Name |
Type |
Description |
vCPUsAvailable
|
integer
|
Specifies the number of vCPUs available for the VM. When this property is not specified in the request body the default behavior is to set it to the value of vCPUs available for that VM size exposed in api response of List all available virtual machine sizes in a region.
|
vCPUsPerCore
|
integer
|
Specifies the vCPU to physical core ratio. When this property is not specified in the request body the default behavior is set to the value of vCPUsPerCore for the VM Size exposed in api response of List all available virtual machine sizes in a region. Setting this property to 1 also means that hyper-threading is disabled.
|
WindowsConfiguration
Specifies Windows operating system settings on the virtual machine.
Name |
Type |
Description |
additionalUnattendContent
|
AdditionalUnattendContent[]
|
Specifies additional base-64 encoded XML formatted information that can be included in the Unattend.xml file, which is used by Windows Setup.
|
enableAutomaticUpdates
|
boolean
|
Indicates whether Automatic Updates is enabled for the Windows virtual machine. Default value is true. For virtual machine scale sets, this property can be updated and updates will take effect on OS reprovisioning.
|
enableVMAgentPlatformUpdates
|
boolean
|
Indicates whether VMAgent Platform Updates are enabled for the Windows Virtual Machine.
|
patchSettings
|
PatchSettings
|
[Preview Feature] Specifies settings related to VM Guest Patching on Windows.
|
provisionVMAgent
|
boolean
|
Indicates whether virtual machine agent should be provisioned on the virtual machine. When this property is not specified in the request body, it is set to true by default. This will ensure that VM Agent is installed on the VM so that extensions can be added to the VM later.
|
timeZone
|
string
|
Specifies the time zone of the virtual machine. e.g. "Pacific Standard Time". Possible values can be TimeZoneInfo.Id value from time zones returned by TimeZoneInfo.GetSystemTimeZones.
|
winRM
|
WinRMConfiguration
|
Specifies the Windows Remote Management listeners. This enables remote Windows PowerShell.
|
WindowsPatchAssessmentMode
Specifies the mode of VM Guest patch assessment for the IaaS virtual machine.
Possible values are:
ImageDefault - You control the timing of patch assessments on a virtual machine.
AutomaticByPlatform - The platform will trigger periodic patch assessments. The property provisionVMAgent must be true.
Name |
Type |
Description |
AutomaticByPlatform
|
string
|
|
ImageDefault
|
string
|
|
Specifies the reboot setting for all AutomaticByPlatform patch installation operations.
Name |
Type |
Description |
Always
|
string
|
|
IfRequired
|
string
|
|
Never
|
string
|
|
Unknown
|
string
|
|
Specifies additional settings for patch mode AutomaticByPlatform in VM Guest Patching on Windows.
Name |
Type |
Description |
bypassPlatformSafetyChecksOnUserSchedule
|
boolean
|
Enables customer to schedule patching without accidental upgrades
|
rebootSetting
|
WindowsVMGuestPatchAutomaticByPlatformRebootSetting
|
Specifies the reboot setting for all AutomaticByPlatform patch installation operations.
|
WindowsVMGuestPatchMode
Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated to virtual machine scale set with OrchestrationMode as Flexible.
Possible values are:
Manual - You control the application of patches to a virtual machine. You do this by applying patches manually inside the VM. In this mode, automatic updates are disabled; the property WindowsConfiguration.enableAutomaticUpdates must be false
AutomaticByOS - The virtual machine will automatically be updated by the OS. The property WindowsConfiguration.enableAutomaticUpdates must be true.
AutomaticByPlatform - the virtual machine will automatically updated by the platform. The properties provisionVMAgent and WindowsConfiguration.enableAutomaticUpdates must be true
Name |
Type |
Description |
AutomaticByOS
|
string
|
|
AutomaticByPlatform
|
string
|
|
Manual
|
string
|
|
WinRMConfiguration
Specifies the Windows Remote Management listeners. This enables remote Windows PowerShell.
Name |
Type |
Description |
listeners
|
WinRMListener[]
|
The list of Windows Remote Management listeners
|
WinRMListener
The list of Windows Remote Management listeners