Операция создания или обновления виртуальной машины. Обратите внимание, что некоторые свойства можно задать только во время создания виртуальной машины.
PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}?api-version=2024-03-01
Параметры URI
Имя |
В |
Обязательно |
Тип |
Описание |
resourceGroupName
|
path |
True
|
string
|
Имя группы ресурсов.
|
subscriptionId
|
path |
True
|
string
|
Учетные данные подписки, которые однозначно идентифицируют подписку Microsoft Azure. Идентификатор подписки формирует часть URI для каждого вызова службы.
|
vmName
|
path |
True
|
string
|
Имя виртуальной машины.
|
api-version
|
query |
True
|
string
|
Версия API клиента.
|
Имя |
Обязательно |
Тип |
Описание |
If-Match
|
|
string
|
ETag преобразования. Опустите это значение, чтобы всегда перезаписывать текущий ресурс. Укажите последнее значение ETag, чтобы предотвратить случайную перезапись параллельных изменений.
|
If-None-Match
|
|
string
|
Задайте значение "*", чтобы разрешить создание нового набора записей, но предотвратить обновление существующего набора записей. Другие значения приведут к ошибке сервера, так как они не поддерживаются.
|
Текст запроса
Имя |
Тип |
Описание |
parameters
|
VirtualMachine
|
Параметры, предоставленные для операции Создания виртуальной машины.
|
Ответы
Безопасность
azure_auth
Поток OAuth2 в Azure Active Directory
Тип:
oauth2
Flow:
implicit
URL-адрес авторизации:
https://login.microsoftonline.com/common/oauth2/authorize
Области
Имя |
Описание |
user_impersonation
|
олицетворения учетной записи пользователя
|
Примеры
Create a custom-image vm from an unmanaged generalized os image.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/{vm-name}?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_custom_image_vm_from_an_unmanaged_generalized_os_image.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="{vm-name}",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"image": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/{existing-generalized-os-image-blob-name}.vhd"
},
"name": "myVMosdisk",
"osType": "Windows",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd"
},
}
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_linux_vm_with_patch_setting_assessment_mode_of_image_default.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
"linuxConfiguration": {
"patchSettings": {"assessmentMode": "ImageDefault"},
"provisionVMAgent": True,
},
},
"storageProfile": {
"imageReference": {
"offer": "UbuntuServer",
"publisher": "Canonical",
"sku": "16.04-LTS",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Premium_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
import com.azure.core.management.SubResource;
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.AdditionalCapabilities;
import com.azure.resourcemanager.compute.models.ApiEntityReference;
import com.azure.resourcemanager.compute.models.ApplicationProfile;
import com.azure.resourcemanager.compute.models.BootDiagnostics;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DataDisk;
import com.azure.resourcemanager.compute.models.DeleteOptions;
import com.azure.resourcemanager.compute.models.DiagnosticsProfile;
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.DiskControllerTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.DiskEncryptionSetParameters;
import com.azure.resourcemanager.compute.models.DomainNameLabelScopeTypes;
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.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.Mode;
import com.azure.resourcemanager.compute.models.NetworkApiVersion;
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.OperatingSystemTypes;
import com.azure.resourcemanager.compute.models.PatchSettings;
import com.azure.resourcemanager.compute.models.Plan;
import com.azure.resourcemanager.compute.models.ProxyAgentSettings;
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.ScheduledEventsAdditionalPublishingTargets;
import com.azure.resourcemanager.compute.models.ScheduledEventsPolicy;
import com.azure.resourcemanager.compute.models.ScheduledEventsProfile;
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.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.TerminateNotificationProfile;
import com.azure.resourcemanager.compute.models.UefiSettings;
import com.azure.resourcemanager.compute.models.UserInitiatedReboot;
import com.azure.resourcemanager.compute.models.UserInitiatedRedeploy;
import com.azure.resourcemanager.compute.models.VMDiskSecurityProfile;
import com.azure.resourcemanager.compute.models.VMGalleryApplication;
import com.azure.resourcemanager.compute.models.VMSizeProperties;
import com.azure.resourcemanager.compute.models.VirtualHardDisk;
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 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-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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
Пример ответа
{
"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"
}
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_linux_vm_with_automatic_by_platform_settings.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
"linuxConfiguration": {
"patchSettings": {
"assessmentMode": "AutomaticByPlatform",
"automaticByPlatformSettings": {
"bypassPlatformSafetyChecksOnUserSchedule": True,
"rebootSetting": "Never",
},
"patchMode": "AutomaticByPlatform",
},
"provisionVMAgent": True,
},
},
"storageProfile": {
"imageReference": {
"offer": "UbuntuServer",
"publisher": "Canonical",
"sku": "16.04-LTS",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Premium_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_linux_vm_with_patch_setting_mode_of_image_default.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
"linuxConfiguration": {"patchSettings": {"patchMode": "ImageDefault"}, "provisionVMAgent": True},
},
"storageProfile": {
"imageReference": {
"offer": "UbuntuServer",
"publisher": "Canonical",
"sku": "16.04-LTS",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Premium_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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"
}
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_linux_vm_with_patch_setting_modes_of_automatic_by_platform.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
"linuxConfiguration": {
"patchSettings": {"assessmentMode": "AutomaticByPlatform", "patchMode": "AutomaticByPlatform"},
"provisionVMAgent": True,
},
},
"storageProfile": {
"imageReference": {
"offer": "UbuntuServer",
"publisher": "Canonical",
"sku": "16.04-LTS",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Premium_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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"
}
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/{vm-name}?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_platform_image_vm_with_unmanaged_os_and_data_disks.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="{vm-name}",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"dataDisks": [
{
"createOption": "Empty",
"diskSizeGB": 1023,
"lun": 0,
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk0.vhd"
},
},
{
"createOption": "Empty",
"diskSizeGB": 1023,
"lun": 1,
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk1.vhd"
},
},
],
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "myVMosdisk",
"vhd": {
"uri": "http://{existing-storage-account-name}.blob.core.windows.net/{existing-container-name}/myDisk.vhd"
},
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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"
}
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_from_acommunity_gallery_image.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"communityGalleryImageId": "/CommunityGalleries/galleryPublicName/Images/communityGalleryImageName/Versions/communityGalleryImageVersionName"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_from_acustom_image.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_from_ageneralized_shared_image.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_from_ashared_gallery_image.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"sharedGalleryImageId": "/SharedGalleries/sharedGalleryName/Images/sharedGalleryImageName/Versions/sharedGalleryImageVersionName"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_from_aspecialized_shared_image.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/mySharedGallery/images/mySharedImage"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_in_avmss_with_customer_assigned_platform_fault_domain.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"platformFaultDomain": 1,
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
"virtualMachineScaleSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/{existing-flex-vmss-name-with-platformFaultDomainCount-greater-than-1}"
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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}"
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_in_an_availability_set.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"availabilitySet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/{existing-availability-set-name}"
},
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_amarketplace_image_plan.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"plan": {"name": "windows2016", "product": "windows-data-science-vm", "publisher": "microsoft-ads"},
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "windows-data-science-vm",
"publisher": "microsoft-ads",
"sku": "windows2016",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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"
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_extensions_time_budget.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": True,
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
}
},
"extensionsTimeBudget": "PT30M",
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_application_profile.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"applicationProfile": {
"galleryApplications": [
{
"configurationReference": "https://mystorageaccount.blob.core.windows.net/configurations/settings.config",
"enableAutomaticUpgrade": False,
"order": 1,
"packageReferenceId": "/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdb/resourceGroups/myresourceGroupName2/providers/Microsoft.Compute/galleries/myGallery1/applications/MyApplication1/versions/1.0",
"tags": "myTag1",
"treatFailureAsDeploymentFailure": False,
},
{
"packageReferenceId": "/subscriptions/32c17a9e-aa7b-4ba5-a45b-e324116b6fdg/resourceGroups/myresourceGroupName3/providers/Microsoft.Compute/galleries/myGallery2/applications/MyApplication2/versions/1.1"
},
]
},
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "{image_offer}",
"publisher": "{image_publisher}",
"sku": "{image_sku}",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_boot_diagnostics.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": True,
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
}
},
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_data_disks_from_source_resource.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"dataDisks": [
{
"createOption": "Copy",
"diskSizeGB": 1023,
"lun": 0,
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/{existing-snapshot-name}"
},
},
{
"createOption": "Copy",
"diskSizeGB": 1023,
"lun": 1,
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-disk-name}"
},
},
{
"createOption": "Restore",
"diskSizeGB": 1023,
"lun": 2,
"sourceResource": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/restorePointCollections/{existing-rpc-name}/restorePoints/{existing-rp-name}/diskRestorePoints/{existing-disk-restore-point-name}"
},
},
],
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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=="
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_disk_controller_type.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": True,
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
}
},
"hardwareProfile": {"vmSize": "Standard_D4_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"scheduledEventsPolicy": {
"scheduledEventsAdditionalPublishingTargets": {"eventGridAndResourceGraph": {"enable": True}},
"userInitiatedReboot": {"automaticallyApprove": True},
"userInitiatedRedeploy": {"automaticallyApprove": True},
},
"storageProfile": {
"diskControllerType": "NVMe",
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
"userData": "U29tZSBDdXN0b20gRGF0YQ==",
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_disk_encryption_set_resource.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"dataDisks": [
{
"caching": "ReadWrite",
"createOption": "Empty",
"diskSizeGB": 1023,
"lun": 0,
"managedDisk": {
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
},
"storageAccountType": "Standard_LRS",
},
},
{
"caching": "ReadWrite",
"createOption": "Attach",
"diskSizeGB": 1023,
"lun": 1,
"managedDisk": {
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
},
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/{existing-managed-disk-name}",
"storageAccountType": "Standard_LRS",
},
},
],
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {
"diskEncryptionSet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/diskEncryptionSets/{existing-diskEncryptionSet-name}"
},
"storageAccountType": "Standard_LRS",
},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_empty_data_disks.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"dataDisks": [
{"createOption": "Empty", "diskSizeGB": 1023, "lun": 0},
{"createOption": "Empty", "diskSizeGB": 1023, "lun": 1},
],
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_encryption_identity.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity": {}
},
},
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"securityProfile": {
"encryptionIdentity": {
"userAssignedIdentityResourceId": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity"
}
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2019-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "StandardSSD_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
import com.azure.core.management.SubResource;
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.AdditionalCapabilities;
import com.azure.resourcemanager.compute.models.ApiEntityReference;
import com.azure.resourcemanager.compute.models.ApplicationProfile;
import com.azure.resourcemanager.compute.models.BootDiagnostics;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DataDisk;
import com.azure.resourcemanager.compute.models.DeleteOptions;
import com.azure.resourcemanager.compute.models.DiagnosticsProfile;
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.DiskControllerTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.DiskEncryptionSetParameters;
import com.azure.resourcemanager.compute.models.DomainNameLabelScopeTypes;
import com.azure.resourcemanager.compute.models.EncryptionIdentity;
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.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.Mode;
import com.azure.resourcemanager.compute.models.NetworkApiVersion;
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.OperatingSystemTypes;
import com.azure.resourcemanager.compute.models.PatchSettings;
import com.azure.resourcemanager.compute.models.Plan;
import com.azure.resourcemanager.compute.models.ProxyAgentSettings;
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.ResourceIdentityType;
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.SecurityEncryptionTypes;
import com.azure.resourcemanager.compute.models.SecurityProfile;
import com.azure.resourcemanager.compute.models.SecurityTypes;
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.TerminateNotificationProfile;
import com.azure.resourcemanager.compute.models.UefiSettings;
import com.azure.resourcemanager.compute.models.UserInitiatedReboot;
import com.azure.resourcemanager.compute.models.UserInitiatedRedeploy;
import com.azure.resourcemanager.compute.models.VMDiskSecurityProfile;
import com.azure.resourcemanager.compute.models.VMGalleryApplication;
import com.azure.resourcemanager.compute.models.VMSizeProperties;
import com.azure.resourcemanager.compute.models.VirtualHardDisk;
import com.azure.resourcemanager.compute.models.VirtualMachineIdentity;
import com.azure.resourcemanager.compute.models.VirtualMachineIdentityUserAssignedIdentities;
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 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-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_adiff_os_disk_using_diff_disk_placement_as_cache_disk.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"plan": {"name": "windows2016", "product": "windows-data-science-vm", "publisher": "microsoft-ads"},
"properties": {
"hardwareProfile": {"vmSize": "Standard_DS1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "windows-data-science-vm",
"publisher": "microsoft-ads",
"sku": "windows2016",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"diffDiskSettings": {"option": "Local", "placement": "CacheDisk"},
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
import com.azure.core.management.SubResource;
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.AdditionalCapabilities;
import com.azure.resourcemanager.compute.models.ApiEntityReference;
import com.azure.resourcemanager.compute.models.ApplicationProfile;
import com.azure.resourcemanager.compute.models.BootDiagnostics;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DataDisk;
import com.azure.resourcemanager.compute.models.DeleteOptions;
import com.azure.resourcemanager.compute.models.DiagnosticsProfile;
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.DiskControllerTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.DiskEncryptionSetParameters;
import com.azure.resourcemanager.compute.models.DomainNameLabelScopeTypes;
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.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.Mode;
import com.azure.resourcemanager.compute.models.NetworkApiVersion;
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.OperatingSystemTypes;
import com.azure.resourcemanager.compute.models.PatchSettings;
import com.azure.resourcemanager.compute.models.Plan;
import com.azure.resourcemanager.compute.models.ProxyAgentSettings;
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.ScheduledEventsAdditionalPublishingTargets;
import com.azure.resourcemanager.compute.models.ScheduledEventsPolicy;
import com.azure.resourcemanager.compute.models.ScheduledEventsProfile;
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.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.TerminateNotificationProfile;
import com.azure.resourcemanager.compute.models.UefiSettings;
import com.azure.resourcemanager.compute.models.UserInitiatedReboot;
import com.azure.resourcemanager.compute.models.UserInitiatedRedeploy;
import com.azure.resourcemanager.compute.models.VMDiskSecurityProfile;
import com.azure.resourcemanager.compute.models.VMGalleryApplication;
import com.azure.resourcemanager.compute.models.VMSizeProperties;
import com.azure.resourcemanager.compute.models.VirtualHardDisk;
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 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-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_adiff_os_disk_using_diff_disk_placement_as_nvme_disk.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"plan": {"name": "windows2016", "product": "windows-data-science-vm", "publisher": "microsoft-ads"},
"properties": {
"hardwareProfile": {"vmSize": "Standard_DS1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "windows-data-science-vm",
"publisher": "microsoft-ads",
"sku": "windows2016",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"diffDiskSettings": {"option": "Local", "placement": "NvmeDisk"},
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_adiff_os_disk_using_diff_disk_placement_as_resource_disk.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"plan": {"name": "windows2016", "product": "windows-data-science-vm", "publisher": "microsoft-ads"},
"properties": {
"hardwareProfile": {"vmSize": "Standard_DS1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "windows-data-science-vm",
"publisher": "microsoft-ads",
"sku": "windows2016",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"diffDiskSettings": {"option": "Local", "placement": "ResourceDisk"},
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_adiff_os_disk.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"plan": {"name": "windows2016", "product": "windows-data-science-vm", "publisher": "microsoft-ads"},
"properties": {
"hardwareProfile": {"vmSize": "Standard_DS1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "windows-data-science-vm",
"publisher": "microsoft-ads",
"sku": "windows2016",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"diffDiskSettings": {"option": "Local"},
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/{vm-name}?api-version=2024-03-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
}
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_hibernation_enabled.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="{vm-name}",
parameters={
"location": "eastus2euap",
"properties": {
"additionalCapabilities": {"hibernationEnabled": True},
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": True,
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
}
},
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "{vm-name}",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2019-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "vmOSdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_encryption_at_host.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"plan": {"name": "windows2016", "product": "windows-data-science-vm", "publisher": "microsoft-ads"},
"properties": {
"hardwareProfile": {"vmSize": "Standard_DS1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"securityProfile": {"encryptionAtHost": True},
"storageProfile": {
"imageReference": {
"offer": "windows-data-science-vm",
"publisher": "microsoft-ads",
"sku": "windows2016",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_managed_boot_diagnostics.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"diagnosticsProfile": {"bootDiagnostics": {"enabled": True}},
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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}"
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_network_interface_configuration.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkApiVersion": "2020-11-01",
"networkInterfaceConfigurations": [
{
"name": "{nic-config-name}",
"properties": {
"deleteOption": "Delete",
"ipConfigurations": [
{
"name": "{ip-config-name}",
"properties": {
"primary": True,
"publicIPAddressConfiguration": {
"name": "{publicIP-config-name}",
"properties": {
"deleteOption": "Detach",
"publicIPAllocationMethod": "Static",
},
"sku": {"name": "Basic", "tier": "Global"},
},
},
}
],
"primary": True,
},
}
],
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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}"
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_network_interface_configuration_dns_settings.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkApiVersion": "2020-11-01",
"networkInterfaceConfigurations": [
{
"name": "{nic-config-name}",
"properties": {
"deleteOption": "Delete",
"ipConfigurations": [
{
"name": "{ip-config-name}",
"properties": {
"primary": True,
"publicIPAddressConfiguration": {
"name": "{publicIP-config-name}",
"properties": {
"deleteOption": "Detach",
"dnsSettings": {
"domainNameLabel": "aaaaa",
"domainNameLabelScope": "TenantReuse",
},
"publicIPAllocationMethod": "Static",
},
"sku": {"name": "Basic", "tier": "Global"},
},
},
}
],
"primary": True,
},
}
],
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_password_authentication.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_premium_storage.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Premium_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
import com.azure.core.management.SubResource;
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.AdditionalCapabilities;
import com.azure.resourcemanager.compute.models.ApiEntityReference;
import com.azure.resourcemanager.compute.models.ApplicationProfile;
import com.azure.resourcemanager.compute.models.BootDiagnostics;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DataDisk;
import com.azure.resourcemanager.compute.models.DeleteOptions;
import com.azure.resourcemanager.compute.models.DiagnosticsProfile;
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.DiskControllerTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.DiskEncryptionSetParameters;
import com.azure.resourcemanager.compute.models.DomainNameLabelScopeTypes;
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.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.Mode;
import com.azure.resourcemanager.compute.models.NetworkApiVersion;
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.OperatingSystemTypes;
import com.azure.resourcemanager.compute.models.PatchSettings;
import com.azure.resourcemanager.compute.models.Plan;
import com.azure.resourcemanager.compute.models.ProxyAgentSettings;
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.ScheduledEventsAdditionalPublishingTargets;
import com.azure.resourcemanager.compute.models.ScheduledEventsPolicy;
import com.azure.resourcemanager.compute.models.ScheduledEventsProfile;
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.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.TerminateNotificationProfile;
import com.azure.resourcemanager.compute.models.UefiSettings;
import com.azure.resourcemanager.compute.models.UserInitiatedReboot;
import com.azure.resourcemanager.compute.models.UserInitiatedRedeploy;
import com.azure.resourcemanager.compute.models.VMDiskSecurityProfile;
import com.azure.resourcemanager.compute.models.VMGalleryApplication;
import com.azure.resourcemanager.compute.models.VMSizeProperties;
import com.azure.resourcemanager.compute.models.VirtualHardDisk;
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 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-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_proxy_agent_settings.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"hardwareProfile": {"vmSize": "Standard_D2s_v3"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"securityProfile": {"proxyAgentSettings": {"enabled": True, "mode": "Enforce"}},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2019-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "StandardSSD_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_scheduled_events_profile.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machines.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_name="myVM",
parameters={
"location": "westus",
"properties": {
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": True,
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
}
},
"hardwareProfile": {"vmSize": "Standard_D1_v2"},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {"primary": True},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"scheduledEventsPolicy": {
"scheduledEventsAdditionalPublishingTargets": {"eventGridAndResourceGraph": {"enable": True}},
"userInitiatedReboot": {"automaticallyApprove": True},
"userInitiatedRedeploy": {"automaticallyApprove": True},
},
"scheduledEventsProfile": {
"osImageNotificationProfile": {"enable": True, "notBeforeTimeout": "PT15M"},
"terminateNotificationProfile": {"enable": True, "notBeforeTimeout": "PT10M"},
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {"storageAccountType": "Standard_LRS"},
"name": "myVMosdisk",
},
},
},
},
).result()
print(response)
# x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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"
}
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/{vm-name}?api-version=2024-03-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=="
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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=="
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
import com.azure.core.management.SubResource;
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.AdditionalCapabilities;
import com.azure.resourcemanager.compute.models.ApiEntityReference;
import com.azure.resourcemanager.compute.models.ApplicationProfile;
import com.azure.resourcemanager.compute.models.BootDiagnostics;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DataDisk;
import com.azure.resourcemanager.compute.models.DeleteOptions;
import com.azure.resourcemanager.compute.models.DiagnosticsProfile;
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.DiskControllerTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.DiskEncryptionSetParameters;
import com.azure.resourcemanager.compute.models.DomainNameLabelScopeTypes;
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.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.Mode;
import com.azure.resourcemanager.compute.models.NetworkApiVersion;
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.OperatingSystemTypes;
import com.azure.resourcemanager.compute.models.PatchSettings;
import com.azure.resourcemanager.compute.models.Plan;
import com.azure.resourcemanager.compute.models.ProxyAgentSettings;
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.ScheduledEventsAdditionalPublishingTargets;
import com.azure.resourcemanager.compute.models.ScheduledEventsPolicy;
import com.azure.resourcemanager.compute.models.ScheduledEventsProfile;
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.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.TerminateNotificationProfile;
import com.azure.resourcemanager.compute.models.UefiSettings;
import com.azure.resourcemanager.compute.models.UserInitiatedReboot;
import com.azure.resourcemanager.compute.models.UserInitiatedRedeploy;
import com.azure.resourcemanager.compute.models.VMDiskSecurityProfile;
import com.azure.resourcemanager.compute.models.VMGalleryApplication;
import com.azure.resourcemanager.compute.models.VMSizeProperties;
import com.azure.resourcemanager.compute.models.VirtualHardDisk;
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 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-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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
Пример ответа
{
"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"
}
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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"
}
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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.
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
Пример ответа
{
"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"
}
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
import com.azure.core.management.SubResource;
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.AdditionalCapabilities;
import com.azure.resourcemanager.compute.models.ApiEntityReference;
import com.azure.resourcemanager.compute.models.ApplicationProfile;
import com.azure.resourcemanager.compute.models.BootDiagnostics;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.DataDisk;
import com.azure.resourcemanager.compute.models.DeleteOptions;
import com.azure.resourcemanager.compute.models.DiagnosticsProfile;
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.DiskControllerTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.DiskEncryptionSetParameters;
import com.azure.resourcemanager.compute.models.DomainNameLabelScopeTypes;
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.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.Mode;
import com.azure.resourcemanager.compute.models.NetworkApiVersion;
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.OperatingSystemTypes;
import com.azure.resourcemanager.compute.models.PatchSettings;
import com.azure.resourcemanager.compute.models.Plan;
import com.azure.resourcemanager.compute.models.ProxyAgentSettings;
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.ScheduledEventsAdditionalPublishingTargets;
import com.azure.resourcemanager.compute.models.ScheduledEventsPolicy;
import com.azure.resourcemanager.compute.models.ScheduledEventsProfile;
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.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.TerminateNotificationProfile;
import com.azure.resourcemanager.compute.models.UefiSettings;
import com.azure.resourcemanager.compute.models.UserInitiatedReboot;
import com.azure.resourcemanager.compute.models.UserInitiatedRedeploy;
import com.azure.resourcemanager.compute.models.VMDiskSecurityProfile;
import com.azure.resourcemanager.compute.models.VMGalleryApplication;
import com.azure.resourcemanager.compute.models.VMSizeProperties;
import com.azure.resourcemanager.compute.models.VirtualHardDisk;
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 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-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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
Пример ответа
{
"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
Образец запроса
PUT https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM?api-version=2024-03-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
}
}
]
}
}
}
from typing import Any, IO, Union
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-compute
# USAGE
python virtual_machine_create_with_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-03-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/v5"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/92de53a5f1e0e03c94b40475d2135d97148ed014/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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-03-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
import com.azure.core.management.SubResource;
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineInner;
import com.azure.resourcemanager.compute.models.AdditionalCapabilities;
import com.azure.resourcemanager.compute.models.ApiEntityReference;
import com.azure.resourcemanager.compute.models.ApplicationProfile;
import com.azure.resourcemanager.compute.models.BootDiagnostics;
import com.azure.resourcemanager.compute.models.CachingTypes;
import com.azure.resourcemanager.compute.models.CapacityReservationProfile;
import com.azure.resourcemanager.compute.models.DataDisk;
import com.azure.resourcemanager.compute.models.DeleteOptions;
import com.azure.resourcemanager.compute.models.DiagnosticsProfile;
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.DiskControllerTypes;
import com.azure.resourcemanager.compute.models.DiskCreateOptionTypes;
import com.azure.resourcemanager.compute.models.DiskEncryptionSetParameters;
import com.azure.resourcemanager.compute.models.DomainNameLabelScopeTypes;
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.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.Mode;
import com.azure.resourcemanager.compute.models.NetworkApiVersion;
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.OperatingSystemTypes;
import com.azure.resourcemanager.compute.models.PatchSettings;
import com.azure.resourcemanager.compute.models.Plan;
import com.azure.resourcemanager.compute.models.ProxyAgentSettings;
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.ScheduledEventsAdditionalPublishingTargets;
import com.azure.resourcemanager.compute.models.ScheduledEventsPolicy;
import com.azure.resourcemanager.compute.models.ScheduledEventsProfile;
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.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.TerminateNotificationProfile;
import com.azure.resourcemanager.compute.models.UefiSettings;
import com.azure.resourcemanager.compute.models.UserInitiatedReboot;
import com.azure.resourcemanager.compute.models.UserInitiatedRedeploy;
import com.azure.resourcemanager.compute.models.VMDiskSecurityProfile;
import com.azure.resourcemanager.compute.models.VMGalleryApplication;
import com.azure.resourcemanager.compute.models.VMSizeProperties;
import com.azure.resourcemanager.compute.models.VirtualHardDisk;
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 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-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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);
}
/*
* x-ms-original-file:
* specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2024-03-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
Пример ответа
{
"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"
}
Определения
Имя |
Описание |
AdditionalCapabilities
|
Указывает дополнительные возможности, включенные или отключенные на виртуальной машине.
|
AdditionalUnattendContent
|
Задает дополнительные сведения в кодировке base-64 и в формате XML, которые могут включаться в файл Unattend.xml, используемый программой установки Windows.
|
ApiEntityReference
|
Идентификатор исходного ресурса. Это может быть snapshot или точка восстановления диска, из которой создается диск.
|
ApiError
|
Ошибка API.
|
ApiErrorBase
|
База ошибок API.
|
ApplicationProfile
|
Указывает приложения коллекции, которые должны быть доступны для виртуальной машины или VMSS.
|
AvailablePatchSummary
|
Сводка доступных исправлений последней операции оценки для виртуальной машины.
|
BillingProfile
|
Указывает сведения о выставлении счетов для точечных виртуальных машин Azure. Минимальная версия API: 2019-03-01.
|
BootDiagnostics
|
Диагностика загрузки — это функция отладки, которая позволяет просматривать выходные данные консоли и снимок экрана для диагностики состояния виртуальной машины.
Примечание. Если указан параметр storageUri, убедитесь, что учетная запись хранения находится в том же регионе и подписке, что и виртуальная машина. Вы можете легко просмотреть выходные данные журнала консоли. Azure также позволяет просмотреть снимок экрана виртуальной машины из низкоуровневой оболочки.
|
BootDiagnosticsInstanceView
|
Диагностика загрузки — это функция отладки, которая позволяет просматривать выходные данные консоли и снимок экрана для диагностики состояния виртуальной машины. Вы можете легко просмотреть выходные данные журнала консоли. Azure также позволяет просмотреть снимок экрана виртуальной машины из низкоуровневой оболочки.
|
CachingTypes
|
Указывает требования к кэшированию. Возможные значения: None,ReadOnly,ReadWrite. Поведение по умолчанию: Нет для хранилища уровня "Стандартный". ReadOnly для хранилища класса Premium.
|
CapacityReservationProfile
|
Указывает сведения о резервировании емкости, используемом для выделения виртуальной машины. Минимальная версия API: 2021-04-01.
|
CloudError
|
Ответ об ошибке от службы вычислений.
|
ComponentNames
|
Имя компонента. В настоящее время единственным допустимым значением является Microsoft-Windows-Shell-Setup.
|
DataDisk
|
Задает параметры, используемые для добавления диска данных к виртуальной машине. Дополнительные сведения о дисках см. в статье Сведения о дисках и виртуальных жестких дисках для виртуальных машин Azure.
|
DeleteOptions
|
Укажите, что происходит с сетевым интерфейсом при удалении виртуальной машины
|
DiagnosticsProfile
|
Указывает состояние параметров диагностики загрузки. Минимальная версия API: 15.06.2015.
|
DiffDiskOptions
|
Указывает временные параметры диска для диска операционной системы.
|
DiffDiskPlacement
|
Указывает временное размещение диска для диска операционной системы. Возможные значения: CacheDisk,ResourceDisk,NvmeDisk. Поведение по умолчанию: CacheDisk, если он настроен для размера виртуальной машины, в противном случае используется ResourceDisk или NvmeDisk. Сведения о том, проверка какие размеры виртуальных машин предоставляют диск кэша, см. в документации по размеру виртуальной машины Windows в https://docs.microsoft.com/azure/virtual-machines/windows/sizes и виртуальной машине Linux по адресуhttps://docs.microsoft.com/azure/virtual-machines/linux/sizes. Минимальная версия API для NvmeDisk: 2024-03-01.
|
DiffDiskSettings
|
Указывает временные параметры диска для диска операционной системы, используемого виртуальной машиной.
|
DiskControllerTypes
|
Указывает тип контроллера диска, настроенный для виртуальной машины.
Примечание: Для этого свойства будет задан тип дискового контроллера по умолчанию, если не указана виртуальная машина при условии, что для параметра hyperVGeneration задано значение V2, в зависимости от возможностей диска операционной системы и размера виртуальной машины из указанной минимальной версии API. Перед обновлением типа контроллера диска необходимо освободить виртуальную машину, если только размер виртуальной машины не обновляется в конфигурации виртуальной машины, которая неявно освобождает и перераспределяет виртуальную машину. Минимальная версия API: 2022-08-01.
|
DiskCreateOptionTypes
|
Указывает способ создания диска виртуальной машины. Возможные значения: Присоединить. Это значение используется при использовании специализированного диска для создания виртуальной машины.
FromImage: Это значение используется при использовании образа для создания виртуальной машины. Если вы используете образ платформы, следует также использовать элемент imageReference, описанный выше. Если вы используете образ Marketplace, следует также использовать элемент плана, описанный выше.
|
DiskDeleteOptionTypes
|
Указывает, следует ли удалять или отсоединять диск ОС при удалении виртуальной машины. Возможные значения: Delete. Если это значение используется, диск ОС удаляется при удалении виртуальной машины. Отсоединить. Если используется это значение, диск ос сохраняется после удаления виртуальной машины. Значение по умолчанию — Отсоединение. Для эфемерного диска ОС по умолчанию устанавливается значение Delete. Пользователь не может изменить параметр удаления для временного диска ОС.
|
DiskDetachOptionTypes
|
Указывает поведение отсоединения, используемое при отсоединение диска или уже находится в процессе отсоединения от виртуальной машины. Поддерживаемые значения: ForceDetach. detachOption: ForceDetach применяется только для управляемых дисков данных. Если предыдущая попытка отсоединения диска данных не завершилась из-за неожиданного сбоя виртуальной машины и диск по-прежнему не освобожден, используйте принудительное отсоединение в качестве крайнего средства, чтобы принудительно отсоединить диск от виртуальной машины. При использовании этого поведения отсоединения все операции записи не были удалены.
Эта функция по-прежнему находится в режиме предварительной версии и не поддерживается для VirtualMachineScaleSet. Для принудительного отсоединения обновления диска данных toBeDetached до true вместе с параметром detachOption: ForceDetach.
|
DiskEncryptionSetParameters
|
Указывает идентификатор ресурса набора шифрования управляемых пользователем дисков для управляемого диска.
|
DiskEncryptionSettings
|
Задает параметры шифрования для диска ОС. Минимальная версия API: 15.06.2015.
|
DiskInstanceView
|
Сведения о диске виртуальной машины.
|
DomainNameLabelScopeTypes
|
Метка доменного имени область ресурсов PublicIPAddress, которые будут созданы. Созданная метка имени — это объединение хэшированных меток доменного имени с политикой в соответствии с меткой доменного имени область и уникальным идентификатором сетевого профиля виртуальной машины.
|
EncryptionIdentity
|
Указывает управляемое удостоверение, используемое ADE для получения маркера доступа для операций хранилища ключей.
|
EventGridAndResourceGraph
|
Параметры конфигурации, используемые при создании параметра eventGridAndResourceGraph Scheduled Event.
|
ExtendedLocation
|
Расширенное расположение виртуальной машины.
|
ExtendedLocationTypes
|
Тип расширенного расположения.
|
HardwareProfile
|
Указывает параметры оборудования виртуальной машины.
|
HyperVGenerationType
|
Указывает тип HyperVGeneration, связанный с ресурсом.
|
ImageReference
|
Указывает сведения об используемом образе. Вы можете указать сведения об образах платформы, образах Marketplace или виртуальных машинах. Этот элемент является обязательным, если вы хотите использовать образ платформы, образ Marketplace или образ виртуальной машины, но не используется в других операциях создания.
|
InnerError
|
Сведения о внутренней ошибке.
|
InstanceViewStatus
|
Состояние представления экземпляра.
|
IPVersions
|
Доступно с Api-Version 2019-07-01, он указывает, является ли конкретная ip-конфигурация IPv4 или IPv6. Значение по умолчанию принимается как IPv4. Возможные значения: IPv4 и IPv6.
|
KeyVaultKeyReference
|
Указывает расположение ключа шифрования ключа в Key Vault.
|
KeyVaultSecretReference
|
Расширения защищают параметры, передаваемые по ссылке и используемые из хранилища ключей.
|
LastPatchInstallationSummary
|
Сводка по последней операции установки виртуальной машины.
|
LinuxConfiguration
|
Задает параметры операционной системы Linux на виртуальной машине. Список поддерживаемых дистрибутивов Linux см. в разделе Linux в дистрибутивах Azure-Endorsed.
|
LinuxPatchAssessmentMode
|
Указывает режим оценки исправлений гостевой виртуальной машины для виртуальной машины IaaS.
Возможны следующие значения:
ImageDefault — вы управляете временем оценки исправлений на виртуальной машине.
AutomaticByPlatform — платформа запускает периодические оценки исправлений. Свойство provisionVMAgent должно иметь значение true.
|
LinuxPatchSettings
|
[Предварительная версия функции] Задает параметры, связанные с исправлением гостевой виртуальной машины в Linux.
|
LinuxVMGuestPatchAutomaticByPlatformRebootSetting
|
Задает параметр перезагрузки для всех операций установки исправлений AutomaticByPlatform.
|
LinuxVMGuestPatchAutomaticByPlatformSettings
|
Задает дополнительные параметры для режима исправления AutomaticByPlatform в гостевой системе исправлений виртуальной машины в Linux.
|
LinuxVMGuestPatchMode
|
Указывает режим установки исправлений гостевой виртуальной машины для виртуальной машины IaaS или виртуальных машин, связанных с масштабируемым набором виртуальных машин с параметром OrchestrationMode как гибкий.
Возможны следующие значения:
ImageDefault — используется конфигурация исправлений виртуальной машины по умолчанию.
AutomaticByPlatform — виртуальная машина будет автоматически обновлена платформой. Свойство provisionVMAgent должно иметь значение true.
|
MaintenanceOperationResultCodeTypes
|
Код результата последней операции обслуживания.
|
MaintenanceRedeployStatus
|
Состояние операции обслуживания на виртуальной машине.
|
ManagedDiskParameters
|
Параметры управляемого диска.
|
Mode
|
Указывает режим, в котором будет выполняться ProxyAgent, если эта функция включена. ProxyAgent начнет аудит или мониторинг, но не будет применять контроль доступа к запросам к конечным точкам размещения в режиме аудита, а в режиме принудительного применения он будет применять управление доступом. Значение по умолчанию — Режим принудительного применения.
|
NetworkApiVersion
|
указывает версию API Microsoft.Network, используемую при создании сетевых ресурсов в конфигурациях сетевого интерфейса.
|
NetworkInterfaceAuxiliaryMode
|
Указывает, включен ли вспомогательный режим для ресурса сетевого интерфейса.
|
NetworkInterfaceAuxiliarySku
|
Указывает, включен ли вспомогательный SKU для ресурса сетевого интерфейса.
|
NetworkInterfaceReference
|
Указывает список идентификаторов ресурсов для сетевых интерфейсов, связанных с виртуальной машиной.
|
NetworkProfile
|
Указывает сетевые интерфейсы виртуальной машины.
|
OperatingSystemTypes
|
Тип операционной системы.
|
OSDisk
|
Указывает сведения о диске операционной системы, используемом виртуальной машиной. Дополнительные сведения о дисках см. в статье Сведения о дисках и виртуальных жестких дисках для виртуальных машин Azure.
|
OSImageNotificationProfile
|
Указывает конфигурации, связанные с запланированным событием образа ОС.
|
OSProfile
|
Задает параметры операционной системы, используемые при создании виртуальной машины. Некоторые параметры нельзя изменить после подготовки виртуальной машины.
|
PassNames
|
Имя прохода. В настоящее время единственным допустимым значением является OobeSystem.
|
PatchOperationStatus
|
Общий успех или состояние сбоя операции. Он остается "InProgress" до завершения операции. В этот момент он будет ознавать "Unknown", "Failed", "Succeeded" или "CompletedWithWarnings".
|
PatchSettings
|
[Предварительная версия функции] Задает параметры, связанные с исправлением гостевой виртуальной машины в Windows.
|
Plan
|
Указывает сведения об образе Marketplace, используемом для создания виртуальной машины. Этот элемент используется только для образов Marketplace. Прежде чем использовать образ Marketplace из API, необходимо включить его для программного использования. В портал Azure найдите образ Marketplace, который вы хотите использовать, и нажмите кнопку Захотеть развернуть программным способом, Начало работы .>. Введите необходимые сведения и нажмите кнопку Сохранить.
|
ProtocolTypes
|
Указывает протокол прослушивателя WinRM. Возможные значения: http,https.
|
ProxyAgentSettings
|
Указывает параметры ProxyAgent при создании виртуальной машины. Минимальная версия API: 2024-03-01.
|
PublicIPAddressSku
|
Описывает номер SKU общедоступного IP-адреса. Его можно задать только с параметром OrchestrationMode как гибкий.
|
PublicIPAddressSkuName
|
Указание имени номера SKU общедоступного IP-адреса
|
PublicIPAddressSkuTier
|
Указание уровня SKU общедоступного IP-адреса
|
PublicIPAllocationMethod
|
Указание типа выделения общедоступных IP-адресов
|
ResourceIdentityType
|
Тип удостоверения, используемого для виртуальной машины. Тип SystemAssigned, UserAssigned включает как условно созданное удостоверение, так и набор удостоверений, назначенных пользователем. Тип None приведет к удалению всех удостоверений с виртуальной машины.
|
ScheduledEventsAdditionalPublishingTargets
|
Параметры конфигурации, используемые при публикации scheduledEventsAdditionalPublishingTargets.
|
ScheduledEventsPolicy
|
Указывает конфигурации, связанные с событиями повторного развертывания, перезагрузки и scheduledEventsAdditionalPublishingTargets Scheduled Event для виртуальной машины.
|
ScheduledEventsProfile
|
Указывает конфигурации, связанные с запланированными событиями.
|
securityEncryptionTypes
|
Указывает Тип шифрования управляемого диска. Для него задано значение DiskWithVMGuestState для шифрования управляемого диска вместе с BLOB-объектом VMGuestState, VMGuestStateOnly для шифрования только большого двоичного объекта VMGuestState и NonPersistedTPM для того, чтобы не сохранять состояние встроенного ПО в большом двоичном объекте VMGuestState.
Примечание: Его можно задать только для конфиденциальных виртуальных машин.
|
SecurityProfile
|
Задает параметры профиля, связанного с безопасностью, для виртуальной машины.
|
SecurityTypes
|
Указывает тип безопасности виртуальной машины. Чтобы включить UefiSettings, ему необходимо задать любое указанное значение. Поведение по умолчанию: UefiSettings не будет включено, если это свойство не задано.
|
SettingNames
|
Указывает имя параметра, к которому относится контент. Возможные значения: FirstLogonCommands и AutoLogon.
|
SshConfiguration
|
Указывает конфигурацию ключа SSH для операционной системы Linux.
|
SshPublicKey
|
Список открытых ключей SSH, используемых для проверки подлинности на виртуальных машинах под управлением Linux.
|
StatusLevelTypes
|
Код уровня.
|
StorageAccountTypes
|
Указывает тип учетной записи хранения для управляемого диска. ПРИМЕЧАНИЕ. UltraSSD_LRS можно использовать только с дисками данных, нельзя использовать с диском ОС.
|
StorageProfile
|
Указывает параметры хранилища дисков виртуальной машины.
|
SubResource
|
Относительный URL-адрес Key Vault, содержащего секрет.
|
TerminateNotificationProfile
|
Указывает конфигурации, связанные с запланированными событиями завершения.
|
UefiSettings
|
Указывает параметры безопасности, такие как безопасная загрузка и vTPM, используемые при создании виртуальной машины. Минимальная версия API: 2020-12-01.
|
UserAssignedIdentities
|
Список удостоверений пользователей, связанных с виртуальной машиной. Ссылки на ключи словаря удостоверений пользователей будут иметь идентификаторы ресурсов ARM в форме: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}".
|
UserInitiatedReboot
|
Параметры конфигурации, используемые при создании параметра запланированного события userInitiatedReboot.
|
UserInitiatedRedeploy
|
Параметры конфигурации, используемые при создании параметра запланированного события userInitiatedRedeploy.
|
VaultCertificate
|
Список ссылок на хранилища ключей в SourceVault, которые содержат сертификаты.
|
VaultSecretGroup
|
Указывает набор сертификатов, которые должны быть установлены на виртуальную машину. Чтобы установить сертификаты на виртуальной машине, рекомендуется использовать расширение виртуальной машины Azure Key Vault для Linux или расширение виртуальной машины Azure Key Vault для Windows.
|
VirtualHardDisk
|
Виртуальный жесткий диск.
|
VirtualMachine
|
Описывает виртуальную машину.
|
VirtualMachineAgentInstanceView
|
Агент виртуальной машины, работающий на виртуальной машине.
|
VirtualMachineEvictionPolicyTypes
|
Указывает политику вытеснения для точечных виртуальных машин Azure и точечных масштабируемых наборов Azure. Для точечных виртуальных машин Azure поддерживаются как "Отменить выделение", так и "Удалить", а минимальная версия API — 2019-03-01. Для точечных масштабируемых наборов Azure поддерживаются как Deallocate, так и Delete, а минимальная версия API — 2017-10-30-preview.
|
VirtualMachineExtension
|
Ресурсы дочернего расширения виртуальной машины.
|
VirtualMachineExtensionHandlerInstanceView
|
Представление экземпляра обработчика расширения виртуальной машины.
|
VirtualMachineExtensionInstanceView
|
Представление экземпляра расширения виртуальной машины.
|
VirtualMachineHealthStatus
|
Состояние работоспособности виртуальной машины.
|
VirtualMachineIdentity
|
Удостоверение виртуальной машины, если настроено.
|
VirtualMachineInstanceView
|
Представление экземпляра виртуальной машины.
|
VirtualMachineIpTag
|
Список тегов IP-адресов, связанных с общедоступным IP-адресом.
|
VirtualMachineNetworkInterfaceConfiguration
|
Задает конфигурации сети, которые будут использоваться для создания сетевых ресурсов виртуальной машины.
|
VirtualMachineNetworkInterfaceDnsSettingsConfiguration
|
Параметры DNS, применяемые к сетевым интерфейсам.
|
VirtualMachineNetworkInterfaceIPConfiguration
|
Задает IP-конфигурации сетевого интерфейса.
|
VirtualMachinePatchStatus
|
[Предварительная версия функции] Состояние операций исправления виртуальной машины.
|
VirtualMachinePriorityTypes
|
Указывает приоритет для виртуальной машины. Минимальная версия API: 2019-03-01
|
VirtualMachinePublicIPAddressConfiguration
|
PublicIPAddressConfiguration.
|
VirtualMachinePublicIPAddressDnsSettingsConfiguration
|
Параметры DNS, применяемые к общедоступным IP-адресам.
|
VirtualMachineSizeTypes
|
Задает размер виртуальной машины. Тип данных перечисления в настоящее время является устаревшим и будет удален до 23 декабря 2023 г. Рекомендуемый способ получить список доступных размеров — использовать следующие API: Перечисление всех доступных размеров виртуальных машин в группе доступности, Перечисление всех доступных размеров виртуальных машин в регионе, Перечисление всех доступных размеров виртуальных машин для изменения размера. Дополнительные сведения о размерах виртуальных машин см. в разделе Размеры виртуальных машин. Доступные размеры виртуальных машин зависят от региона и группы доступности.
|
VMDiskSecurityProfile
|
Указывает профиль безопасности для управляемого диска.
|
VMGalleryApplication
|
Указывает приложения коллекции, которые должны быть доступны для виртуальной машины или VMSS.
|
VMSizeProperties
|
Задает свойства для настройки размера виртуальной машины. Минимальная версия API: 2021-07-01. Эта функция по-прежнему находится в режиме предварительной версии и не поддерживается для VirtualMachineScaleSet. Для получения дополнительных сведений следуйте инструкциям в разделе Настройка виртуальной машины .
|
WindowsConfiguration
|
Указывает параметры операционной системы Windows на виртуальной машине.
|
WindowsPatchAssessmentMode
|
Указывает режим оценки исправлений гостевой виртуальной машины для виртуальной машины IaaS.
Возможны следующие значения:
ImageDefault — вы управляете временем оценки исправлений на виртуальной машине.
AutomaticByPlatform — платформа запускает периодические оценки исправлений. Свойство provisionVMAgent должно иметь значение true.
|
WindowsVMGuestPatchAutomaticByPlatformRebootSetting
|
Задает параметр перезагрузки для всех операций установки исправлений AutomaticByPlatform.
|
WindowsVMGuestPatchAutomaticByPlatformSettings
|
Задает дополнительные параметры для режима исправления AutomaticByPlatform в гостевой системе исправлений виртуальной машины в Windows.
|
WindowsVMGuestPatchMode
|
Указывает режим установки исправлений гостевой виртуальной машины для виртуальной машины IaaS или виртуальных машин, связанных с масштабируемым набором виртуальных машин с параметром OrchestrationMode как гибкий.
Возможны следующие значения:
Вручную . Вы управляете применением исправлений на виртуальной машине. Это можно сделать, применяя исправления вручную на виртуальной машине. В этом режиме автоматические обновления отключены; свойство WindowsConfiguration.enableAutomaticUpdates должно иметь значение false.
AutomaticByOS — виртуальная машина автоматически обновляется ОС. Свойство WindowsConfiguration.enableAutomaticUpdates должно иметь значение true.
AutomaticByPlatform — виртуальная машина автоматически обновляется платформой. Свойства provisionVMAgent и WindowsConfiguration.enableAutomaticUpdates должны иметь значение true.
|
WinRMConfiguration
|
Указывает прослушиватели удаленного управления Windows. Это включает удаленное взаимодействие с Windows PowerShell.
|
WinRMListener
|
Список прослушивателей удаленного управления Windows
|
AdditionalCapabilities
Указывает дополнительные возможности, включенные или отключенные на виртуальной машине.
Имя |
Тип |
Описание |
hibernationEnabled
|
boolean
|
Флаг, который включает или отключает возможность гибернации на виртуальной машине.
|
ultraSSDEnabled
|
boolean
|
Флаг, который включает или отключает возможность иметь один или несколько управляемых дисков данных с UltraSSD_LRS типом учетной записи хранения на виртуальной машине или VMSS. Управляемые диски с типом учетной записи хранения UltraSSD_LRS можно добавить в виртуальную машину или масштабируемый набор виртуальных машин, только если это свойство включено.
|
AdditionalUnattendContent
Задает дополнительные сведения в кодировке base-64 и в формате XML, которые могут включаться в файл Unattend.xml, используемый программой установки Windows.
Имя |
Тип |
Описание |
componentName
|
ComponentNames
|
Имя компонента. В настоящее время единственным допустимым значением является Microsoft-Windows-Shell-Setup.
|
content
|
string
|
Указывает содержимое в формате XML, добавляемое в файл unattend.xml для указанного пути и компонента. Размер XML должен быть меньше 4 КБ и должен содержать корневой элемент для вставляемого параметра или компонента.
|
passName
|
PassNames
|
Имя прохода. В настоящее время единственным допустимым значением является OobeSystem.
|
settingName
|
SettingNames
|
Указывает имя параметра, к которому относится контент. Возможные значения: FirstLogonCommands и AutoLogon.
|
ApiEntityReference
Идентификатор исходного ресурса. Это может быть snapshot или точка восстановления диска, из которой создается диск.
Имя |
Тип |
Описание |
id
|
string
|
Идентификатор ресурса ARM в виде /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/...
|
ApiError
Ошибка API.
Имя |
Тип |
Описание |
code
|
string
|
Код ошибки.
|
details
|
ApiErrorBase[]
|
Сведения об ошибке API
|
innererror
|
InnerError
|
Внутренняя ошибка API
|
message
|
string
|
Сообщение об ошибке.
|
target
|
string
|
Целевой объект конкретной ошибки.
|
ApiErrorBase
База ошибок API.
Имя |
Тип |
Описание |
code
|
string
|
Код ошибки.
|
message
|
string
|
Сообщение об ошибке.
|
target
|
string
|
Целевой объект конкретной ошибки.
|
ApplicationProfile
Указывает приложения коллекции, которые должны быть доступны для виртуальной машины или VMSS.
Имя |
Тип |
Описание |
galleryApplications
|
VMGalleryApplication[]
|
Указывает приложения коллекции, которые должны быть доступны для виртуальной машины или VMSS.
|
AvailablePatchSummary
Сводка доступных исправлений последней операции оценки для виртуальной машины.
Имя |
Тип |
Описание |
assessmentActivityId
|
string
|
Идентификатор действия операции, которая привела к этому результату. Он используется для сопоставления журналов CRP и расширений.
|
criticalAndSecurityPatchCount
|
integer
|
Количество критически важных исправлений или исправлений системы безопасности, которые были обнаружены как доступные и еще не установлены.
|
error
|
ApiError
|
Ошибки, возникшие во время выполнения операции. Массив сведений содержит их список.
|
lastModifiedTime
|
string
|
Метка времени в формате UTC при начале операции.
|
otherPatchCount
|
integer
|
Количество всех доступных исправлений, за исключением критически важных и безопасности.
|
rebootPending
|
boolean
|
Общее состояние перезагрузки виртуальной машины. Это значение будет true, если для частично установленных исправлений требуется перезагрузка для завершения установки, но перезагрузка еще не выполнена.
|
startTime
|
string
|
Метка времени в формате UTC при начале операции.
|
status
|
PatchOperationStatus
|
Общее состояние успешного или неудачного выполнения операции. Он остается "InProgress" до завершения операции. В этот момент он станет "Unknown", "Failed", "Succeeded" или "CompletedWithWarnings".
|
BillingProfile
Указывает сведения о выставлении счетов для точечных виртуальных машин Azure. Минимальная версия API: 2019-03-01.
Имя |
Тип |
Описание |
maxPrice
|
number
|
Указывает максимальную цену, которую вы готовы заплатить за точечные виртуальные машины Или VMSS Azure. Эта цена указана в долларах США.
Эта цена будет сравниваться с текущей ценой точечных ресурсов Azure для размера виртуальной машины. Кроме того, цены сравниваются во время создания или обновления точечных виртуальных машин Azure или VMSS, и операция будет успешной, только если максимальная цена превышает текущую цену Azure Spot.
Параметр maxPrice также будет использоваться для вытеснения точечных виртуальных машин Или VMSS Azure, если текущая цена точечных объектов Azure выходит за пределы maxPrice после создания виртуальной машины или VMSS.
Возможны следующие значения:
— любое десятичное значение больше нуля. Пример: 0,01538
-1 — указывает цену по умолчанию по запросу.
Вы можете задать для параметра maxPrice значение -1, чтобы указать, что точечные виртуальные машины Или VMSS Azure не должны быть вытеснено по соображениям цены. Кроме того, максимальная цена по умолчанию составляет -1, если она не предоставлена вами.
Минимальная версия API: 2019-03-01.
|
BootDiagnostics
Диагностика загрузки — это функция отладки, которая позволяет просматривать выходные данные консоли и снимок экрана для диагностики состояния виртуальной машины.
Примечание. Если указан параметр storageUri, убедитесь, что учетная запись хранения находится в том же регионе и подписке, что и виртуальная машина. Вы можете легко просмотреть выходные данные журнала консоли. Azure также позволяет просмотреть снимок экрана виртуальной машины из низкоуровневой оболочки.
Имя |
Тип |
Описание |
enabled
|
boolean
|
Указывает, должна ли на виртуальной машине быть включена загрузочная диагностика.
|
storageUri
|
string
|
URI учетной записи хранения, используемой для размещения выходных данных консоли и снимка экрана. Если параметр storageUri не указан при включении загрузочного диагностика, будет использоваться управляемое хранилище.
|
BootDiagnosticsInstanceView
Диагностика загрузки — это функция отладки, которая позволяет просматривать выходные данные консоли и снимок экрана для диагностики состояния виртуальной машины. Вы можете легко просмотреть выходные данные журнала консоли. Azure также позволяет просмотреть снимок экрана виртуальной машины из низкоуровневой оболочки.
Имя |
Тип |
Описание |
consoleScreenshotBlobUri
|
string
|
URI большого двоичного объекта консоли.
Примечание: Этот параметр не будет установлен, если загрузочный диагностика в настоящее время включен с управляемым хранилищем.
|
serialConsoleLogBlobUri
|
string
|
URI большого двоичного объекта последовательной консоли.
Примечание: Этот параметр не будет установлен, если загрузочный диагностика в настоящее время включен с управляемым хранилищем.
|
status
|
InstanceViewStatus
|
Загрузочный диагностика сведения о состоянии виртуальной машины.
Примечание: Он будет задан только в случае возникновения ошибок при включении диагностика загрузки.
|
CachingTypes
Указывает требования к кэшированию. Возможные значения: None,ReadOnly,ReadWrite. Поведение по умолчанию: Нет для хранилища уровня "Стандартный". ReadOnly для хранилища класса Premium.
Имя |
Тип |
Описание |
None
|
string
|
|
ReadOnly
|
string
|
|
ReadWrite
|
string
|
|
CapacityReservationProfile
Указывает сведения о резервировании емкости, используемом для выделения виртуальной машины. Минимальная версия API: 2021-04-01.
Имя |
Тип |
Описание |
capacityReservationGroup
|
SubResource
|
Указывает идентификатор ресурса группы резервирования емкости, который следует использовать для выделения экземпляров виртуальной машины или масштабируемого набора виртуальных машин при условии, что зарезервировано достаточно емкости. Дополнительные сведения см https://aka.ms/CapacityReservation . в статье.
|
CloudError
Ответ об ошибке от службы вычислений.
Имя |
Тип |
Описание |
error
|
ApiError
|
Ошибка API.
|
ComponentNames
Имя компонента. В настоящее время единственным допустимым значением является Microsoft-Windows-Shell-Setup.
Имя |
Тип |
Описание |
Microsoft-Windows-Shell-Setup
|
string
|
|
DataDisk
Задает параметры, используемые для добавления диска данных к виртуальной машине. Дополнительные сведения о дисках см. в статье Сведения о дисках и виртуальных жестких дисках для виртуальных машин Azure.
Имя |
Тип |
Описание |
caching
|
CachingTypes
|
Указывает требования к кэшированию. Возможные значения: None,ReadOnly,ReadWrite. Поведение по умолчанию: Нет для хранилища уровня "Стандартный". ReadOnly для хранилища класса Premium.
|
createOption
|
DiskCreateOptionTypes
|
Указывает способ создания диска виртуальной машины. Возможные значения: Присоединить. Это значение используется при использовании специализированного диска для создания виртуальной машины.
FromImage: Это значение используется при использовании образа для создания диска данных виртуальной машины. Если вы используете образ платформы, следует также использовать элемент imageReference, описанный выше. Если вы используете образ Marketplace, следует также использовать элемент plan, описанный выше.
Пустой: Это значение используется при создании пустого диска данных.
Копировать: Это значение используется для создания диска данных из snapshot или другого диска.
Восстановить: Это значение используется для создания диска данных из точки восстановления диска.
|
deleteOption
|
DiskDeleteOptionTypes
|
Указывает, следует ли удалять или отсоединять диск данных при удалении виртуальной машины. Возможные значения: Delete. Если используется это значение, диск данных удаляется при удалении виртуальной машины. Отсоединить. Если используется это значение, диск данных сохраняется после удаления виртуальной машины. Значение по умолчанию — Отсоединение.
|
detachOption
|
DiskDetachOptionTypes
|
Указывает поведение отсоединения, используемое при отключении диска или которое уже находится в процессе отсоединения от виртуальной машины. Поддерживаемые значения: ForceDetach. detachOption: ForceDetach применяется только для управляемых дисков данных. Если предыдущая попытка отсоединения диска данных не завершилась из-за непредвиденного сбоя виртуальной машины и диск по-прежнему не освобожден, используйте принудительное отсоединение в качестве крайнего средства, чтобы принудительно отсоединить диск от виртуальной машины. При использовании этого поведения отсоединения все операции записи могли не быть удалены.
Эта функция по-прежнему находится в режиме предварительной версии и не поддерживается для VirtualMachineScaleSet. Для принудительного отсоединения диска данных обновите toBeDetached до true вместе с параметром detachOption: ForceDetach.
|
diskIOPSReadWrite
|
integer
|
Указывает Read-Write операций ввода-вывода в секунду для управляемого диска при UltraSSD_LRS StorageAccountType. Возвращается только для дисков виртуальных машин VirtualMachine ScaleSet. Можно обновить только с помощью обновлений масштабируемого набора VirtualMachine.
|
diskMBpsReadWrite
|
integer
|
Указывает пропускную способность в МБ в секунду для управляемого диска при UltraSSD_LRS StorageAccountType. Возвращается только для дисков виртуальных машин VirtualMachine ScaleSet. Можно обновить только с помощью обновлений масштабируемого набора VirtualMachine.
|
diskSizeGB
|
integer
|
Указывает размер пустого диска данных в гигабайтах. Этот элемент можно использовать для перезаписи размера диска в образе виртуальной машины. Свойство "diskSizeGB" — это количество байтов x 1024^3 для диска и не может быть больше 1023.
|
image
|
VirtualHardDisk
|
Виртуальный жесткий диск исходного образа пользователя. Виртуальный жесткий диск будет скопирован перед подключением к виртуальной машине. Если указан параметр SourceImage, целевой виртуальный жесткий диск не должен существовать.
|
lun
|
integer
|
Указывает номер логической единицы диска данных. Это значение используется для идентификации дисков данных в виртуальной машине и поэтому должно быть уникальным для каждого диска данных, подключенного к виртуальной машине.
|
managedDisk
|
ManagedDiskParameters
|
Параметры управляемого диска.
|
name
|
string
|
имя диска.
|
sourceResource
|
ApiEntityReference
|
Идентификатор исходного ресурса. Это может быть snapshot или точка восстановления диска, из которой создается диск.
|
toBeDetached
|
boolean
|
Указывает, находится ли диск данных в процессе отсоединения от VirtualMachine/VirtualMachineScaleset.
|
vhd
|
VirtualHardDisk
|
Виртуальный жесткий диск.
|
writeAcceleratorEnabled
|
boolean
|
Указывает, следует ли включить или отключить writeAccelerator на диске.
|
DeleteOptions
Укажите, что происходит с сетевым интерфейсом при удалении виртуальной машины
Имя |
Тип |
Описание |
Delete
|
string
|
|
Detach
|
string
|
|
DiagnosticsProfile
Указывает состояние параметров диагностики загрузки. Минимальная версия API: 15.06.2015.
Имя |
Тип |
Описание |
bootDiagnostics
|
BootDiagnostics
|
Диагностика загрузки — это функция отладки, которая позволяет просматривать выходные данные консоли и снимок экрана для диагностики состояния виртуальной машины.
Примечание. Если указан параметр storageUri, убедитесь, что учетная запись хранения находится в том же регионе и подписке, что и виртуальная машина. Вы можете легко просмотреть выходные данные журнала консоли. Azure также позволяет просмотреть снимок экрана виртуальной машины из низкоуровневой оболочки.
|
DiffDiskOptions
Указывает временные параметры диска для диска операционной системы.
Имя |
Тип |
Описание |
Local
|
string
|
|
DiffDiskPlacement
Указывает временное размещение диска для диска операционной системы. Возможные значения: CacheDisk,ResourceDisk,NvmeDisk. Поведение по умолчанию: CacheDisk, если он настроен для размера виртуальной машины, в противном случае используется ResourceDisk или NvmeDisk. Сведения о том, проверка какие размеры виртуальных машин предоставляют диск кэша, см. в документации по размеру виртуальной машины Windows в https://docs.microsoft.com/azure/virtual-machines/windows/sizes и виртуальной машине Linux по адресуhttps://docs.microsoft.com/azure/virtual-machines/linux/sizes. Минимальная версия API для NvmeDisk: 2024-03-01.
Имя |
Тип |
Описание |
CacheDisk
|
string
|
|
NvmeDisk
|
string
|
|
ResourceDisk
|
string
|
|
DiffDiskSettings
Указывает временные параметры диска для диска операционной системы, используемого виртуальной машиной.
DiskControllerTypes
Указывает тип контроллера диска, настроенный для виртуальной машины.
Примечание: Для этого свойства будет задан тип дискового контроллера по умолчанию, если не указана виртуальная машина при условии, что для параметра hyperVGeneration задано значение V2, в зависимости от возможностей диска операционной системы и размера виртуальной машины из указанной минимальной версии API. Перед обновлением типа контроллера диска необходимо освободить виртуальную машину, если только размер виртуальной машины не обновляется в конфигурации виртуальной машины, которая неявно освобождает и перераспределяет виртуальную машину. Минимальная версия API: 2022-08-01.
Имя |
Тип |
Описание |
NVMe
|
string
|
|
SCSI
|
string
|
|
DiskCreateOptionTypes
Указывает способ создания диска виртуальной машины. Возможные значения: Присоединить. Это значение используется при использовании специализированного диска для создания виртуальной машины.
FromImage: Это значение используется при использовании образа для создания виртуальной машины. Если вы используете образ платформы, следует также использовать элемент imageReference, описанный выше. Если вы используете образ Marketplace, следует также использовать элемент плана, описанный выше.
Имя |
Тип |
Описание |
Attach
|
string
|
|
Copy
|
string
|
|
Empty
|
string
|
|
FromImage
|
string
|
|
Restore
|
string
|
|
DiskDeleteOptionTypes
Указывает, следует ли удалять или отсоединять диск ОС при удалении виртуальной машины. Возможные значения: Delete. Если это значение используется, диск ОС удаляется при удалении виртуальной машины. Отсоединить. Если используется это значение, диск ос сохраняется после удаления виртуальной машины. Значение по умолчанию — Отсоединение. Для эфемерного диска ОС по умолчанию устанавливается значение Delete. Пользователь не может изменить параметр удаления для временного диска ОС.
Имя |
Тип |
Описание |
Delete
|
string
|
|
Detach
|
string
|
|
DiskDetachOptionTypes
Указывает поведение отсоединения, используемое при отсоединение диска или уже находится в процессе отсоединения от виртуальной машины. Поддерживаемые значения: ForceDetach. detachOption: ForceDetach применяется только для управляемых дисков данных. Если предыдущая попытка отсоединения диска данных не завершилась из-за неожиданного сбоя виртуальной машины и диск по-прежнему не освобожден, используйте принудительное отсоединение в качестве крайнего средства, чтобы принудительно отсоединить диск от виртуальной машины. При использовании этого поведения отсоединения все операции записи не были удалены.
Эта функция по-прежнему находится в режиме предварительной версии и не поддерживается для VirtualMachineScaleSet. Для принудительного отсоединения обновления диска данных toBeDetached до true вместе с параметром detachOption: ForceDetach.
Имя |
Тип |
Описание |
ForceDetach
|
string
|
|
DiskEncryptionSetParameters
Указывает идентификатор ресурса набора шифрования управляемых пользователем дисков для управляемого диска.
Имя |
Тип |
Описание |
id
|
string
|
Идентификатор ресурса
|
DiskEncryptionSettings
Задает параметры шифрования для диска ОС. Минимальная версия API: 15.06.2015.
Имя |
Тип |
Описание |
diskEncryptionKey
|
KeyVaultSecretReference
|
Указывает расположение ключа шифрования диска, который является секретом Key Vault.
|
enabled
|
boolean
|
Указывает, следует ли включить шифрование дисков на виртуальной машине.
|
keyEncryptionKey
|
KeyVaultKeyReference
|
Указывает расположение ключа шифрования ключа в Key Vault.
|
DiskInstanceView
Сведения о диске виртуальной машины.
Имя |
Тип |
Описание |
encryptionSettings
|
DiskEncryptionSettings[]
|
Задает параметры шифрования для диска ОС.
Минимальная версия API: 2015-06-15
|
name
|
string
|
имя диска.
|
statuses
|
InstanceViewStatus[]
|
Сведения о состоянии ресурса.
|
DomainNameLabelScopeTypes
Метка доменного имени область ресурсов PublicIPAddress, которые будут созданы. Созданная метка имени — это объединение хэшированных меток доменного имени с политикой в соответствии с меткой доменного имени область и уникальным идентификатором сетевого профиля виртуальной машины.
Имя |
Тип |
Описание |
NoReuse
|
string
|
|
ResourceGroupReuse
|
string
|
|
SubscriptionReuse
|
string
|
|
TenantReuse
|
string
|
|
EncryptionIdentity
Указывает управляемое удостоверение, используемое ADE для получения маркера доступа для операций хранилища ключей.
Имя |
Тип |
Описание |
userAssignedIdentityResourceId
|
string
|
Указывает идентификатор ресурса ARM для одного из удостоверений пользователей, связанных с виртуальной машиной.
|
EventGridAndResourceGraph
Параметры конфигурации, используемые при создании параметра eventGridAndResourceGraph Scheduled Event.
Имя |
Тип |
Описание |
enable
|
boolean
|
Указывает, включены ли сетка событий и граф ресурсов для конфигураций, связанных с запланированными событиями.
|
ExtendedLocation
Расширенное расположение виртуальной машины.
Имя |
Тип |
Описание |
name
|
string
|
Имя расширенного расположения.
|
type
|
ExtendedLocationTypes
|
Тип расширенного расположения.
|
ExtendedLocationTypes
Тип расширенного расположения.
Имя |
Тип |
Описание |
EdgeZone
|
string
|
|
HardwareProfile
Указывает параметры оборудования виртуальной машины.
HyperVGenerationType
Указывает тип HyperVGeneration, связанный с ресурсом.
Имя |
Тип |
Описание |
V1
|
string
|
|
V2
|
string
|
|
ImageReference
Указывает сведения об используемом образе. Вы можете указать сведения об образах платформы, образах Marketplace или виртуальных машинах. Этот элемент является обязательным, если вы хотите использовать образ платформы, образ Marketplace или образ виртуальной машины, но не используется в других операциях создания.
Имя |
Тип |
Описание |
communityGalleryImageId
|
string
|
Указан уникальный идентификатор образа коллекции сообщества для развертывания виртуальной машины. Его можно получить из коллекции сообщества образ GET call.
|
exactVersion
|
string
|
Указывает в десятичных числах версию образа платформы или образа Marketplace, используемую для создания виртуальной машины. Это поле только для чтения отличается от "version" только в том случае, если значение, указанное в поле "версия", равно "latest".
|
id
|
string
|
Идентификатор ресурса
|
offer
|
string
|
Указывает предложение образа платформы или образа Marketplace, используемого для создания виртуальной машины.
|
publisher
|
string
|
Издатель образа.
|
sharedGalleryImageId
|
string
|
Указан уникальный идентификатор образа общей коллекции для развертывания виртуальной машины. Его можно получить из вызова GET образа общей коллекции.
|
sku
|
string
|
Номер SKU образа.
|
version
|
string
|
Указывает версию образа платформы или образа Marketplace, используемого для создания виртуальной машины. Допустимые форматы: Major.Minor.Build или latest. Основной, Дополнительный и Сборка являются десятичными числами. Укажите "latest", чтобы использовать последнюю версию образа, доступную во время развертывания. Даже если вы используете последнюю версию, образ виртуальной машины не будет автоматически обновляться после развертывания, даже если станет доступна новая версия. Не используйте поле "версия" для развертывания образа коллекции. Образ коллекции всегда должен использовать поле id для развертывания, чтобы использовать "последнюю" версию образа коллекции, просто задайте "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/gallerys/{galleryName}/images/{imageName}" в поле id без ввода версии.
|
InnerError
Сведения о внутренней ошибке.
Имя |
Тип |
Описание |
errordetail
|
string
|
Внутреннее сообщение об ошибке или дамп исключений.
|
exceptiontype
|
string
|
Тип исключения.
|
InstanceViewStatus
Состояние представления экземпляра.
Имя |
Тип |
Описание |
code
|
string
|
Код состояния.
|
displayStatus
|
string
|
Короткая локализуемая метка состояния.
|
level
|
StatusLevelTypes
|
Код уровня.
|
message
|
string
|
Подробное сообщение о состоянии, в том числе для оповещений и сообщений об ошибках.
|
time
|
string
|
Время состояния.
|
IPVersions
Доступно с Api-Version 2019-07-01, он указывает, является ли конкретная ip-конфигурация IPv4 или IPv6. Значение по умолчанию принимается как IPv4. Возможные значения: IPv4 и IPv6.
Имя |
Тип |
Описание |
IPv4
|
string
|
|
IPv6
|
string
|
|
KeyVaultKeyReference
Указывает расположение ключа шифрования ключа в Key Vault.
Имя |
Тип |
Описание |
keyUrl
|
string
|
URL-адрес, ссылающийся на ключ шифрования ключа в Key Vault.
|
sourceVault
|
SubResource
|
Относительный URL-адрес Key Vault, содержащий ключ.
|
KeyVaultSecretReference
Расширения защищают параметры, передаваемые по ссылке и используемые из хранилища ключей.
Имя |
Тип |
Описание |
secretUrl
|
string
|
URL-адрес, ссылающийся на секрет в Key Vault.
|
sourceVault
|
SubResource
|
Относительный URL-адрес Key Vault, содержащий секрет.
|
LastPatchInstallationSummary
Сводка по последней операции установки виртуальной машины.
Имя |
Тип |
Описание |
error
|
ApiError
|
Ошибки, возникшие во время выполнения операции. Массив сведений содержит их список.
|
excludedPatchCount
|
integer
|
Количество всех доступных исправлений, но явно исключенных указанным клиентом списком исключений.
|
failedPatchCount
|
integer
|
Количество исправлений, которые не удалось установить.
|
installationActivityId
|
string
|
Идентификатор действия операции, которая привела к этому результату. Он используется для сопоставления журналов CRP и расширений.
|
installedPatchCount
|
integer
|
Число успешно установленных исправлений.
|
lastModifiedTime
|
string
|
Метка времени в формате UTC при начале операции.
|
maintenanceWindowExceeded
|
boolean
|
Описывает, истекло ли время операции до завершения всех предполагаемых действий.
|
notSelectedPatchCount
|
integer
|
Количество всех доступных исправлений, но не будет установлено, так как они не соответствуют записи в списке классификации или включения.
|
pendingPatchCount
|
integer
|
Количество всех доступных исправлений, которые должны быть установлены в течение операции установки исправлений.
|
startTime
|
string
|
Метка времени в формате UTC при начале операции.
|
status
|
PatchOperationStatus
|
Общее состояние успешного или неудачного выполнения операции. Он остается "InProgress" до завершения операции. В этот момент он станет "Unknown", "Failed", "Succeeded" или "CompletedWithWarnings".
|
LinuxConfiguration
Задает параметры операционной системы Linux на виртуальной машине. Список поддерживаемых дистрибутивов Linux см. в разделе Linux в дистрибутивах Azure-Endorsed.
Имя |
Тип |
Описание |
disablePasswordAuthentication
|
boolean
|
Указывает, следует ли отключить проверку подлинности паролем.
|
enableVMAgentPlatformUpdates
|
boolean
|
Указывает, включена ли Обновления платформы VMAgent для виртуальной машины Linux. Значение по умолчанию — false.
|
patchSettings
|
LinuxPatchSettings
|
[Предварительная версия функции] Задает параметры, связанные с установкой исправлений гостевой виртуальной машины в Linux.
|
provisionVMAgent
|
boolean
|
Указывает, должен ли агент виртуальной машины быть подготовлен на виртуальной машине. Если это свойство не указано в тексте запроса, по умолчанию ему присваивается значение true. Это гарантирует, что агент виртуальной машины будет установлен на виртуальной машине, чтобы расширения можно было добавить в виртуальную машину позже.
|
ssh
|
SshConfiguration
|
Указывает конфигурацию ключа SSH для операционной системы Linux.
|
LinuxPatchAssessmentMode
Указывает режим оценки исправлений гостевой виртуальной машины для виртуальной машины IaaS.
Возможны следующие значения:
ImageDefault — вы управляете временем оценки исправлений на виртуальной машине.
AutomaticByPlatform — платформа запускает периодические оценки исправлений. Свойство provisionVMAgent должно иметь значение true.
Имя |
Тип |
Описание |
AutomaticByPlatform
|
string
|
|
ImageDefault
|
string
|
|
LinuxPatchSettings
[Предварительная версия функции] Задает параметры, связанные с исправлением гостевой виртуальной машины в Linux.
Имя |
Тип |
Описание |
assessmentMode
|
LinuxPatchAssessmentMode
|
Указывает режим оценки исправлений гостевой виртуальной машины для виртуальной машины IaaS.
Возможны следующие значения:
ImageDefault — вы управляете временем оценки исправлений на виртуальной машине.
AutomaticByPlatform — платформа запускает периодические оценки исправлений. Свойство provisionVMAgent должно иметь значение true.
|
automaticByPlatformSettings
|
LinuxVMGuestPatchAutomaticByPlatformSettings
|
Задает дополнительные параметры для режима исправления AutomaticByPlatform в гостевой системе исправлений виртуальной машины в Linux.
|
patchMode
|
LinuxVMGuestPatchMode
|
Указывает режим установки исправлений гостевой виртуальной машины для виртуальной машины IaaS или виртуальных машин, связанных с масштабируемым набором виртуальных машин с параметром OrchestrationMode как гибкий.
Возможны следующие значения:
ImageDefault — используется конфигурация исправлений виртуальной машины по умолчанию.
AutomaticByPlatform — виртуальная машина будет автоматически обновлена платформой. Свойство provisionVMAgent должно иметь значение true.
|
Задает параметр перезагрузки для всех операций установки исправлений AutomaticByPlatform.
Имя |
Тип |
Описание |
Always
|
string
|
|
IfRequired
|
string
|
|
Never
|
string
|
|
Unknown
|
string
|
|
Задает дополнительные параметры для режима исправления AutomaticByPlatform в гостевой системе исправлений виртуальной машины в Linux.
Имя |
Тип |
Описание |
bypassPlatformSafetyChecksOnUserSchedule
|
boolean
|
Позволяет клиенту планировать установку исправлений без случайных обновлений
|
rebootSetting
|
LinuxVMGuestPatchAutomaticByPlatformRebootSetting
|
Задает параметр перезагрузки для всех операций установки исправлений AutomaticByPlatform.
|
LinuxVMGuestPatchMode
Указывает режим установки исправлений гостевой виртуальной машины для виртуальной машины IaaS или виртуальных машин, связанных с масштабируемым набором виртуальных машин с параметром OrchestrationMode как гибкий.
Возможны следующие значения:
ImageDefault — используется конфигурация исправлений виртуальной машины по умолчанию.
AutomaticByPlatform — виртуальная машина будет автоматически обновлена платформой. Свойство provisionVMAgent должно иметь значение true.
Имя |
Тип |
Описание |
AutomaticByPlatform
|
string
|
|
ImageDefault
|
string
|
|
MaintenanceOperationResultCodeTypes
Код результата последней операции обслуживания.
Имя |
Тип |
Описание |
MaintenanceAborted
|
string
|
|
MaintenanceCompleted
|
string
|
|
None
|
string
|
|
RetryLater
|
string
|
|
MaintenanceRedeployStatus
Состояние операции обслуживания на виртуальной машине.
Имя |
Тип |
Описание |
isCustomerInitiatedMaintenanceAllowed
|
boolean
|
Значение true, если клиенту разрешено выполнять обслуживание.
|
lastOperationMessage
|
string
|
Сообщение, возвращенное для последней операции обслуживания.
|
lastOperationResultCode
|
MaintenanceOperationResultCodeTypes
|
Код результата последней операции обслуживания.
|
maintenanceWindowEndTime
|
string
|
Время окончания периода обслуживания.
|
maintenanceWindowStartTime
|
string
|
Время начала периода обслуживания.
|
preMaintenanceWindowEndTime
|
string
|
Время окончания периода предварительного обслуживания.
|
preMaintenanceWindowStartTime
|
string
|
Время начала периода предварительного обслуживания.
|
ManagedDiskParameters
Параметры управляемого диска.
Имя |
Тип |
Описание |
diskEncryptionSet
|
DiskEncryptionSetParameters
|
Указывает идентификатор ресурса набора шифрования управляемых пользователем дисков для управляемого диска.
|
id
|
string
|
Идентификатор ресурса
|
securityProfile
|
VMDiskSecurityProfile
|
Указывает профиль безопасности для управляемого диска.
|
storageAccountType
|
StorageAccountTypes
|
Указывает тип учетной записи хранения для управляемого диска. ПРИМЕЧАНИЕ. UltraSSD_LRS можно использовать только с дисками данных, нельзя использовать с диском ОС.
|
Mode
Указывает режим, в котором будет выполняться ProxyAgent, если эта функция включена. ProxyAgent начнет аудит или мониторинг, но не будет применять контроль доступа к запросам к конечным точкам размещения в режиме аудита, а в режиме принудительного применения он будет применять управление доступом. Значение по умолчанию — Режим принудительного применения.
Имя |
Тип |
Описание |
Audit
|
string
|
|
Enforce
|
string
|
|
NetworkApiVersion
указывает версию API Microsoft.Network, используемую при создании сетевых ресурсов в конфигурациях сетевого интерфейса.
Имя |
Тип |
Описание |
2020-11-01
|
string
|
|
NetworkInterfaceAuxiliaryMode
Указывает, включен ли вспомогательный режим для ресурса сетевого интерфейса.
Имя |
Тип |
Описание |
AcceleratedConnections
|
string
|
|
Floating
|
string
|
|
None
|
string
|
|
NetworkInterfaceAuxiliarySku
Указывает, включен ли вспомогательный SKU для ресурса сетевого интерфейса.
Имя |
Тип |
Описание |
A1
|
string
|
|
A2
|
string
|
|
A4
|
string
|
|
A8
|
string
|
|
None
|
string
|
|
NetworkInterfaceReference
Указывает список идентификаторов ресурсов для сетевых интерфейсов, связанных с виртуальной машиной.
Имя |
Тип |
Описание |
id
|
string
|
Идентификатор ресурса
|
properties.deleteOption
|
DeleteOptions
|
Укажите, что происходит с сетевым интерфейсом при удалении виртуальной машины
|
properties.primary
|
boolean
|
Указывает основной сетевой интерфейс, если виртуальная машина имеет более 1 сетевого интерфейса.
|
NetworkProfile
Указывает сетевые интерфейсы виртуальной машины.
Имя |
Тип |
Описание |
networkApiVersion
|
NetworkApiVersion
|
указывает версию API Microsoft.Network, используемую при создании сетевых ресурсов в конфигурациях сетевого интерфейса.
|
networkInterfaceConfigurations
|
VirtualMachineNetworkInterfaceConfiguration[]
|
Задает конфигурации сети, которые будут использоваться для создания сетевых ресурсов виртуальной машины.
|
networkInterfaces
|
NetworkInterfaceReference[]
|
Указывает список идентификаторов ресурсов для сетевых интерфейсов, связанных с виртуальной машиной.
|
OperatingSystemTypes
Тип операционной системы.
Имя |
Тип |
Описание |
Linux
|
string
|
|
Windows
|
string
|
|
OSDisk
Указывает сведения о диске операционной системы, используемом виртуальной машиной. Дополнительные сведения о дисках см. в статье Сведения о дисках и виртуальных жестких дисках для виртуальных машин Azure.
Имя |
Тип |
Описание |
caching
|
CachingTypes
|
Указывает требования к кэшированию. Возможные значения: None,ReadOnly,ReadWrite. Поведение по умолчанию: Нет для хранилища уровня "Стандартный". ReadOnly для хранилища класса Premium.
|
createOption
|
DiskCreateOptionTypes
|
Указывает способ создания диска виртуальной машины. Возможные значения: Присоединить. Это значение используется при использовании специализированного диска для создания виртуальной машины.
FromImage: Это значение используется при использовании образа для создания виртуальной машины. Если вы используете образ платформы, следует также использовать элемент imageReference, описанный выше. Если вы используете образ Marketplace, следует также использовать элемент plan, описанный выше.
|
deleteOption
|
DiskDeleteOptionTypes
|
Указывает, следует ли удалять или отсоединять диск ОС при удалении виртуальной машины. Возможные значения: Delete. Если используется это значение, диск ОС удаляется при удалении виртуальной машины. Отсоединить. Если используется это значение, диск ос сохраняется после удаления виртуальной машины. Значение по умолчанию — Отсоединение. Для временного диска ОС значение по умолчанию — Delete. Пользователь не может изменить параметр удаления для временного диска ОС.
|
diffDiskSettings
|
DiffDiskSettings
|
Задает временные параметры диска для диска операционной системы, используемого виртуальной машиной.
|
diskSizeGB
|
integer
|
Указывает размер пустого диска данных в гигабайтах. Этот элемент можно использовать для перезаписи размера диска в образе виртуальной машины. Свойство "diskSizeGB" — это количество байтов x 1024^3 для диска и не может быть больше 1023.
|
encryptionSettings
|
DiskEncryptionSettings
|
Задает параметры шифрования для диска ОС. Минимальная версия API: 15.06.2015.
|
image
|
VirtualHardDisk
|
Виртуальный жесткий диск исходного образа пользователя. Виртуальный жесткий диск будет скопирован перед подключением к виртуальной машине. Если указан параметр SourceImage, целевой виртуальный жесткий диск не должен существовать.
|
managedDisk
|
ManagedDiskParameters
|
Параметры управляемого диска.
|
name
|
string
|
имя диска.
|
osType
|
OperatingSystemTypes
|
Это свойство позволяет указать тип операционной системы, которая включена в диск при создании виртуальной машины из пользовательского образа или специализированного виртуального жесткого диска. Возможные значения: Windows,Linux.
|
vhd
|
VirtualHardDisk
|
Виртуальный жесткий диск.
|
writeAcceleratorEnabled
|
boolean
|
Указывает, следует ли включить или отключить writeAccelerator на диске.
|
OSImageNotificationProfile
Указывает конфигурации, связанные с запланированным событием образа ОС.
Имя |
Тип |
Описание |
enable
|
boolean
|
Указывает, включено или отключено событие Запланированное изображение ОС.
|
notBeforeTimeout
|
string
|
Период времени, в течение времени, когда виртуальная машина будет переосмыслена или обновлена ос, необходимо будет утвердить запланированное событие образа ОС, прежде чем событие будет автоматически утверждено (истекло время ожидания). Конфигурация указывается в формате ISO 8601, а значение должно быть 15 минут (PT15M)
|
OSProfile
Задает параметры операционной системы, используемые при создании виртуальной машины. Некоторые параметры нельзя изменить после подготовки виртуальной машины.
Имя |
Тип |
Описание |
adminPassword
|
string
|
Указывает пароль учетной записи администратора.
Минимальная длина (Windows): 8 символов
Минимальная длина (Linux): 6 символов
Максимальная длина (Windows): 123 символа
Максимальная длина (Linux): 72 символа
Требования к сложности: 3 из 4 условий, приведенных ниже, должны быть выполнены Содержит более низкие символы Содержит верхние символы Имеет цифру Имеет специальный символ (соответствие регулярного выражения [\W_])
Запрещенные значения: "abc@123", "P@$$w 0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", "Password22", "iloveyou!"
Сведения о сбросе пароля см. в статье Как сбросить пароль для входа в службу удаленного рабочего стола на виртуальной машине Windows.
Сведения о сбросе пароля привилегированного пользователя см. в статье Управление пользователями, SSH и проверка или восстановление дисков на виртуальных машинах Linux в Azure с помощью расширения VMAccess.
|
adminUsername
|
string
|
Указывает имя учетной записи администратора.
Это свойство невозможно обновить после создания виртуальной машины.
Ограничение только для Windows: Не может заканчиваться на "."
Запрещенные значения: "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".
Минимальная длина (Linux): 1 символ
Максимальная длина (Linux): 64 символа
Максимальная длина (Windows): 20 символов.
|
allowExtensionOperations
|
boolean
|
Указывает, следует ли разрешать операции расширения на виртуальной машине. Для этого параметра может быть задано значение False, только если на виртуальной машине нет расширений.
|
computerName
|
string
|
Указывает имя ОС узла виртуальной машины. Это имя невозможно обновить после создания виртуальной машины.
Максимальная длина (Windows): 15 символов.
Максимальная длина (Linux): 64 символа. Соглашения об именовании и ограничения см. в руководстве по реализации служб инфраструктуры Azure.
|
customData
|
string
|
Указывает строку пользовательских данных в кодировке base-64. Строка в кодировке base-64 кодируется в двоичный массив, который сохраняется в виде файла на виртуальной машине. Максимальная длина двоичного массива — 65 535 байт. Примечание. Не передайте секреты или пароли в свойстве customData. Это свойство невозможно обновить после создания виртуальной машины. Свойство customData передается виртуальной машине для сохранения в виде файла. Дополнительные сведения см. в статье Пользовательские данные на виртуальных машинах Azure. Сведения об использовании cloud-init для виртуальной машины Linux см. в статье Использование cloud-init для настройки виртуальной машины Linux во время создания.
|
linuxConfiguration
|
LinuxConfiguration
|
Задает параметры операционной системы Linux на виртуальной машине. Список поддерживаемых дистрибутивов Linux см. в разделе Linux в дистрибутивах Azure-Endorsed.
|
requireGuestProvisionSignal
|
boolean
|
Необязательное свойство, для которого должно быть задано значение True или опущено.
|
secrets
|
VaultSecretGroup[]
|
Указывает набор сертификатов, которые должны быть установлены на виртуальную машину. Чтобы установить сертификаты на виртуальной машине, рекомендуется использовать расширение виртуальной машины Azure Key Vault для Linux или расширение виртуальной машины Azure Key Vault для Windows.
|
windowsConfiguration
|
WindowsConfiguration
|
Указывает параметры операционной системы Windows на виртуальной машине.
|
PassNames
Имя прохода. В настоящее время единственным допустимым значением является OobeSystem.
Имя |
Тип |
Описание |
OobeSystem
|
string
|
|
PatchOperationStatus
Общий успех или состояние сбоя операции. Он остается "InProgress" до завершения операции. В этот момент он будет ознавать "Unknown", "Failed", "Succeeded" или "CompletedWithWarnings".
Имя |
Тип |
Описание |
CompletedWithWarnings
|
string
|
|
Failed
|
string
|
|
InProgress
|
string
|
|
Succeeded
|
string
|
|
Unknown
|
string
|
|
PatchSettings
[Предварительная версия функции] Задает параметры, связанные с исправлением гостевой виртуальной машины в Windows.
Имя |
Тип |
Описание |
assessmentMode
|
WindowsPatchAssessmentMode
|
Указывает режим оценки исправлений гостевой виртуальной машины для виртуальной машины IaaS.
Возможны следующие значения:
ImageDefault — вы управляете временем оценки исправлений на виртуальной машине.
AutomaticByPlatform — платформа запускает периодические оценки исправлений. Свойство provisionVMAgent должно иметь значение true.
|
automaticByPlatformSettings
|
WindowsVMGuestPatchAutomaticByPlatformSettings
|
Задает дополнительные параметры для режима исправления AutomaticByPlatform в гостевой системе исправлений виртуальной машины в Windows.
|
enableHotpatching
|
boolean
|
Позволяет клиентам исправлять свои виртуальные машины Azure без перезагрузки. Для enableHotpatching параметру provisionVMAgent необходимо задать значение true, а для patchMode — значение AutomaticByPlatform.
|
patchMode
|
WindowsVMGuestPatchMode
|
Указывает режим установки исправлений гостевой виртуальной машины для виртуальной машины IaaS или виртуальных машин, связанных с масштабируемым набором виртуальных машин с параметром OrchestrationMode как гибкий.
Возможны следующие значения:
Вручную . Вы управляете применением исправлений на виртуальной машине. Это можно сделать, применяя исправления вручную на виртуальной машине. В этом режиме автоматические обновления отключены; свойство WindowsConfiguration.enableAutomaticUpdates должно иметь значение false.
AutomaticByOS — виртуальная машина автоматически обновляется ОС. Свойство WindowsConfiguration.enableAutomaticUpdates должно иметь значение true.
AutomaticByPlatform — виртуальная машина автоматически обновляется платформой. Свойства provisionVMAgent и WindowsConfiguration.enableAutomaticUpdates должны иметь значение true.
|
Plan
Указывает сведения об образе Marketplace, используемом для создания виртуальной машины. Этот элемент используется только для образов Marketplace. Прежде чем использовать образ Marketplace из API, необходимо включить его для программного использования. В портал Azure найдите образ Marketplace, который вы хотите использовать, и нажмите кнопку Захотеть развернуть программным способом, Начало работы .>. Введите необходимые сведения и нажмите кнопку Сохранить.
Имя |
Тип |
Описание |
name
|
string
|
Идентификатор плана.
|
product
|
string
|
Указывает продукт изображения из Marketplace. Это то же значение, что и Предложение в элементе imageReference.
|
promotionCode
|
string
|
Промокод.
|
publisher
|
string
|
Идентификатор издателя.
|
ProtocolTypes
Указывает протокол прослушивателя WinRM. Возможные значения: http,https.
Имя |
Тип |
Описание |
Http
|
string
|
|
Https
|
string
|
|
ProxyAgentSettings
Указывает параметры ProxyAgent при создании виртуальной машины. Минимальная версия API: 2024-03-01.
Имя |
Тип |
Описание |
enabled
|
boolean
|
Указывает, следует ли включить функцию ProxyAgent на виртуальной машине или в масштабируемом наборе виртуальных машин.
|
keyIncarnationId
|
integer
|
Увеличение значения этого свойства позволяет пользователю сбросить ключ, используемый для защиты канала связи между гостевым и узлом.
|
mode
|
Mode
|
Указывает режим, в котором будет выполняться ProxyAgent, если эта функция включена. ProxyAgent начнет выполнять аудит или мониторинг, но не будет применять управление доступом к запросам к конечным точкам размещения в режиме аудита, а в режиме принудительного применения он будет применять управление доступом. Значение по умолчанию — Принудительный режим.
|
PublicIPAddressSku
Описывает номер SKU общедоступного IP-адреса. Его можно задать только с параметром OrchestrationMode как гибкий.
PublicIPAddressSkuName
Указание имени номера SKU общедоступного IP-адреса
Имя |
Тип |
Описание |
Basic
|
string
|
|
Standard
|
string
|
|
PublicIPAddressSkuTier
Указание уровня SKU общедоступного IP-адреса
Имя |
Тип |
Описание |
Global
|
string
|
|
Regional
|
string
|
|
PublicIPAllocationMethod
Указание типа выделения общедоступных IP-адресов
Имя |
Тип |
Описание |
Dynamic
|
string
|
|
Static
|
string
|
|
ResourceIdentityType
Тип удостоверения, используемого для виртуальной машины. Тип SystemAssigned, UserAssigned включает как условно созданное удостоверение, так и набор удостоверений, назначенных пользователем. Тип None приведет к удалению всех удостоверений с виртуальной машины.
Имя |
Тип |
Описание |
None
|
string
|
|
SystemAssigned
|
string
|
|
SystemAssigned, UserAssigned
|
string
|
|
UserAssigned
|
string
|
|
ScheduledEventsAdditionalPublishingTargets
Параметры конфигурации, используемые при публикации scheduledEventsAdditionalPublishingTargets.
Имя |
Тип |
Описание |
eventGridAndResourceGraph
|
EventGridAndResourceGraph
|
Параметры конфигурации, используемые при создании параметра eventGridAndResourceGraph Scheduled Event.
|
ScheduledEventsPolicy
Указывает конфигурации, связанные с событиями повторного развертывания, перезагрузки и scheduledEventsAdditionalPublishingTargets Scheduled Event для виртуальной машины.
Имя |
Тип |
Описание |
scheduledEventsAdditionalPublishingTargets
|
ScheduledEventsAdditionalPublishingTargets
|
Параметры конфигурации, используемые при публикации scheduledEventsAdditionalPublishingTargets.
|
userInitiatedReboot
|
UserInitiatedReboot
|
Параметры конфигурации, используемые при создании параметра запланированного события userInitiatedReboot.
|
userInitiatedRedeploy
|
UserInitiatedRedeploy
|
Параметры конфигурации, используемые при создании параметра запланированного события userInitiatedRedeploy.
|
ScheduledEventsProfile
Указывает конфигурации, связанные с запланированными событиями.
Имя |
Тип |
Описание |
osImageNotificationProfile
|
OSImageNotificationProfile
|
Указывает конфигурации, связанные с запланированным событием образа ОС.
|
terminateNotificationProfile
|
TerminateNotificationProfile
|
Указывает конфигурации, связанные с запланированным событием terminate.
|
securityEncryptionTypes
Указывает Тип шифрования управляемого диска. Для него задано значение DiskWithVMGuestState для шифрования управляемого диска вместе с BLOB-объектом VMGuestState, VMGuestStateOnly для шифрования только большого двоичного объекта VMGuestState и NonPersistedTPM для того, чтобы не сохранять состояние встроенного ПО в большом двоичном объекте VMGuestState.
Примечание: Его можно задать только для конфиденциальных виртуальных машин.
Имя |
Тип |
Описание |
DiskWithVMGuestState
|
string
|
|
NonPersistedTPM
|
string
|
|
VMGuestStateOnly
|
string
|
|
SecurityProfile
Задает параметры профиля, связанного с безопасностью, для виртуальной машины.
Имя |
Тип |
Описание |
encryptionAtHost
|
boolean
|
Это свойство может использоваться пользователем в запросе для включения или отключения шифрования узла для виртуальной машины или масштабируемого набора виртуальных машин. Это позволит включить шифрование для всех дисков, включая ресурс или временный диск на самом узле. Поведение по умолчанию: Шифрование на узле будет отключено, если это свойство не имеет значение true для ресурса.
|
encryptionIdentity
|
EncryptionIdentity
|
Указывает управляемое удостоверение, используемое ADE для получения маркера доступа для операций хранилища ключей.
|
proxyAgentSettings
|
ProxyAgentSettings
|
Указывает параметры ProxyAgent при создании виртуальной машины. Минимальная версия API: 2024-03-01.
|
securityType
|
SecurityTypes
|
Указывает тип безопасности виртуальной машины. Чтобы включить UefiSettings, ему необходимо задать любое указанное значение. Поведение по умолчанию: UefiSettings не будет включено, если это свойство не задано.
|
uefiSettings
|
UefiSettings
|
Указывает параметры безопасности, такие как безопасная загрузка и vTPM, используемые при создании виртуальной машины. Минимальная версия API: 2020-12-01.
|
SecurityTypes
Указывает тип безопасности виртуальной машины. Чтобы включить UefiSettings, ему необходимо задать любое указанное значение. Поведение по умолчанию: UefiSettings не будет включено, если это свойство не задано.
Имя |
Тип |
Описание |
ConfidentialVM
|
string
|
|
TrustedLaunch
|
string
|
|
SettingNames
Указывает имя параметра, к которому относится контент. Возможные значения: FirstLogonCommands и AutoLogon.
Имя |
Тип |
Описание |
AutoLogon
|
string
|
|
FirstLogonCommands
|
string
|
|
SshConfiguration
Указывает конфигурацию ключа SSH для операционной системы Linux.
Имя |
Тип |
Описание |
publicKeys
|
SshPublicKey[]
|
Список открытых ключей SSH, используемых для проверки подлинности на виртуальных машинах под управлением Linux.
|
SshPublicKey
Список открытых ключей SSH, используемых для проверки подлинности на виртуальных машинах под управлением Linux.
Имя |
Тип |
Описание |
keyData
|
string
|
Сертификат открытого ключа SSH, используемый для проверки подлинности на виртуальной машине через SSH. Ключ должен быть не менее 2048 бит и иметь формат ssh-rsa. Сведения о создании ключей SSH см. в статье [Создание ключей SSH в Linux и Mac для виртуальных машин Linux в Azure]https://docs.microsoft.com/azure/virtual-machines/linux/create-ssh-keys-detailed).
|
path
|
string
|
Указывает полный путь на созданной виртуальной машине, где хранится открытый ключ SSH. Если файл уже существует, указанный ключ добавляется к файлу. Пример: /home/user/.ssh/authorized_keys
|
StatusLevelTypes
Код уровня.
Имя |
Тип |
Описание |
Error
|
string
|
|
Info
|
string
|
|
Warning
|
string
|
|
StorageAccountTypes
Указывает тип учетной записи хранения для управляемого диска. ПРИМЕЧАНИЕ. UltraSSD_LRS можно использовать только с дисками данных, нельзя использовать с диском ОС.
Имя |
Тип |
Описание |
PremiumV2_LRS
|
string
|
|
Premium_LRS
|
string
|
|
Premium_ZRS
|
string
|
|
StandardSSD_LRS
|
string
|
|
StandardSSD_ZRS
|
string
|
|
Standard_LRS
|
string
|
|
UltraSSD_LRS
|
string
|
|
StorageProfile
Указывает параметры хранилища дисков виртуальной машины.
Имя |
Тип |
Описание |
dataDisks
|
DataDisk[]
|
Задает параметры, используемые для добавления диска данных к виртуальной машине. Дополнительные сведения о дисках см. в статье Сведения о дисках и виртуальных жестких дисках для виртуальных машин Azure.
|
diskControllerType
|
DiskControllerTypes
|
Указывает тип контроллера диска, настроенный для виртуальной машины.
Примечание: Для этого свойства будет задан тип дискового контроллера по умолчанию, если не указана виртуальная машина при условии, что для параметра hyperVGeneration задано значение V2, в зависимости от возможностей диска операционной системы и размера виртуальной машины из указанной минимальной версии API. Перед обновлением типа контроллера диска необходимо освободить виртуальную машину, если только размер виртуальной машины не обновляется в конфигурации виртуальной машины, которая неявно освобождает и перераспределяет виртуальную машину. Минимальная версия API: 2022-08-01.
|
imageReference
|
ImageReference
|
Указывает сведения об используемом образе. Вы можете указать сведения об образах платформы, образах Marketplace или виртуальных машинах. Этот элемент является обязательным, если вы хотите использовать образ платформы, образ Marketplace или образ виртуальной машины, но не используется в других операциях создания.
|
osDisk
|
OSDisk
|
Указывает сведения о диске операционной системы, используемом виртуальной машиной. Дополнительные сведения о дисках см. в статье Сведения о дисках и виртуальных жестких дисках для виртуальных машин Azure.
|
SubResource
Относительный URL-адрес Key Vault, содержащего секрет.
Имя |
Тип |
Описание |
id
|
string
|
Идентификатор ресурса
|
TerminateNotificationProfile
Указывает конфигурации, связанные с запланированными событиями завершения.
Имя |
Тип |
Описание |
enable
|
boolean
|
Указывает, включено или отключено событие Terminate Scheduled.
|
notBeforeTimeout
|
string
|
Настраиваемая продолжительность удаления виртуальной машины может потенциально утвердить запланированное событие завершения до автоматического утверждения события (истекло время ожидания). Конфигурация должна быть указана в формате ISO 8601, значение по умолчанию — 5 минут (PT5M).
|
UefiSettings
Указывает параметры безопасности, такие как безопасная загрузка и vTPM, используемые при создании виртуальной машины. Минимальная версия API: 2020-12-01.
Имя |
Тип |
Описание |
secureBootEnabled
|
boolean
|
Указывает, должна ли быть включена безопасная загрузка на виртуальной машине. Минимальная версия API: 2020-12-01.
|
vTpmEnabled
|
boolean
|
Указывает, следует ли включить vTPM на виртуальной машине. Минимальная версия API: 2020-12-01.
|
UserAssignedIdentities
Список удостоверений пользователей, связанных с виртуальной машиной. Ссылки на ключи словаря удостоверений пользователей будут иметь идентификаторы ресурсов ARM в форме: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}".
UserInitiatedReboot
Параметры конфигурации, используемые при создании параметра запланированного события userInitiatedReboot.
Имя |
Тип |
Описание |
automaticallyApprove
|
boolean
|
Указывает конфигурации, связанные с запланированными событиями перезагрузки.
|
UserInitiatedRedeploy
Параметры конфигурации, используемые при создании параметра запланированного события userInitiatedRedeploy.
Имя |
Тип |
Описание |
automaticallyApprove
|
boolean
|
Указывает конфигурации, связанные с запланированными событиями повторного развертывания.
|
VaultCertificate
Список ссылок на хранилища ключей в SourceVault, которые содержат сертификаты.
Имя |
Тип |
Описание |
certificateStore
|
string
|
Для виртуальных машин Windows указывает хранилище сертификатов на виртуальной машине, в которое необходимо добавить сертификат. Указанное хранилище сертификатов неявно находится в учетной записи LocalMachine. Для виртуальных машин Linux файл сертификата помещается в каталог /var/lib/waagent с именем <UppercaseThumbprint.crt> для файла сертификата X509 и <UppercaseThumbprint.prv> для закрытого ключа. Оба этих файла имеют формат PEM.
|
certificateUrl
|
string
|
Это URL-адрес сертификата, переданного в Key Vault в виде секрета. Сведения о добавлении секрета в Key Vault см. в статье Добавление ключа или секрета в хранилище ключей. В этом случае сертификат должен иметь кодировку Base64 следующего объекта JSON, кодированного в UTF-8:
{ "data":"", "dataType":"pfx", "password":"" } Чтобы установить сертификаты на виртуальной машине, рекомендуется использовать расширение виртуальной машины Azure Key Vault для Linux или расширение виртуальной машины Azure Key Vault для Windows.
|
VaultSecretGroup
Указывает набор сертификатов, которые должны быть установлены на виртуальную машину. Чтобы установить сертификаты на виртуальной машине, рекомендуется использовать расширение виртуальной машины Azure Key Vault для Linux или расширение виртуальной машины Azure Key Vault для Windows.
Имя |
Тип |
Описание |
sourceVault
|
SubResource
|
Относительный URL-адрес Key Vault, содержащий все сертификаты в VaultCertificates.
|
vaultCertificates
|
VaultCertificate[]
|
Список ссылок на хранилище ключей в SourceVault, которые содержат сертификаты.
|
VirtualHardDisk
Виртуальный жесткий диск.
Имя |
Тип |
Описание |
uri
|
string
|
Указывает универсальный код ресурса (URI) виртуального жесткого диска.
|
VirtualMachine
Описывает виртуальную машину.
Имя |
Тип |
Описание |
etag
|
string
|
Etag — это свойство, возвращаемое при создании, обновлении или получении ответа виртуальной машины, чтобы клиент смог указать его в заголовке для обеспечения оптимистичных обновлений.
|
extendedLocation
|
ExtendedLocation
|
Расширенное расположение виртуальной машины.
|
id
|
string
|
Идентификатор ресурса
|
identity
|
VirtualMachineIdentity
|
Удостоверение виртуальной машины, если настроено.
|
location
|
string
|
Расположение ресурса
|
managedBy
|
string
|
ManagedBy имеет значение Virtual Machine Scale Set (VMSS) flex ARM resourceID, если виртуальная машина является частью VMSS. Это свойство используется платформой для оптимизации удаления внутренней группы ресурсов.
|
name
|
string
|
Имя ресурса
|
plan
|
Plan
|
Указывает сведения об образе Marketplace, используемом для создания виртуальной машины. Этот элемент используется только для образов Marketplace. Прежде чем использовать образ Marketplace из API, необходимо включить его для программного использования. В портал Azure найдите образ Marketplace, который вы хотите использовать, и нажмите кнопку Захотеть развернуть программным способом, Начало работы .>. Введите необходимые сведения и нажмите кнопку Сохранить.
|
properties.additionalCapabilities
|
AdditionalCapabilities
|
Указывает дополнительные возможности, включенные или отключенные на виртуальной машине.
|
properties.applicationProfile
|
ApplicationProfile
|
Указывает приложения коллекции, которые должны быть доступны виртуальной машине или VMSS.
|
properties.availabilitySet
|
SubResource
|
Указывает сведения о группе доступности, в которую должна быть назначена виртуальная машина. Виртуальные машины, заданные в одной группе доступности, выделяются в различных узлах для достижения максимальной доступности. Дополнительные сведения о группах доступности см. в статье Общие сведения о группах доступности. Дополнительные сведения о плановом обслуживании Azure см. в статье Обслуживание и обновления для Виртуальные машины в Azure. В настоящее время виртуальную машину можно добавить в группу доступности только во время создания. Группа доступности, в которую добавляется виртуальная машина, должна находиться в той же группе ресурсов, что и ресурс группы доступности. Существующую виртуальную машину нельзя добавить в группу доступности. Это свойство не может существовать вместе со ссылкой properties.virtualMachineScaleSet, отличной от null.
|
properties.billingProfile
|
BillingProfile
|
Указывает сведения о точечных виртуальных машинах Azure, связанных с выставлением счетов. Минимальная версия API: 2019-03-01.
|
properties.capacityReservation
|
CapacityReservationProfile
|
Указывает сведения о резервировании емкости, используемой для выделения виртуальной машины. Минимальная версия API: 2021-04-01.
|
properties.diagnosticsProfile
|
DiagnosticsProfile
|
Указывает состояние параметров диагностики загрузки. Минимальная версия API: 15.06.2015.
|
properties.evictionPolicy
|
VirtualMachineEvictionPolicyTypes
|
Указывает политику вытеснения для точечных виртуальных машин Azure и точечных масштабируемых наборов Azure. Для точечных виртуальных машин Azure поддерживаются как "Отменить выделение", так и "Удалить", а минимальная версия API — 2019-03-01. Для точечных масштабируемых наборов Azure поддерживаются как Deallocate, так и Delete, а минимальная версия API — 2017-10-30-preview.
|
properties.extensionsTimeBudget
|
string
|
Указывает время, отведенное для запуска всех расширений. Длительность должна быть от 15 до 120 минут (включительно) и должна быть указана в формате ISO 8601. Значение по умолчанию — 90 минут (PT1H30M). Минимальная версия API: 2020-06-01.
|
properties.hardwareProfile
|
HardwareProfile
|
Указывает параметры оборудования виртуальной машины.
|
properties.host
|
SubResource
|
Указывает сведения о выделенном узле, на котором находится виртуальная машина. Минимальная версия API: 2018-10-01.
|
properties.hostGroup
|
SubResource
|
Указывает сведения о выделенной группе узлов, в которой находится виртуальная машина.
Примечание: Пользователь не может указать свойства host и hostGroup. Минимальная версия API: 2020-06-01.
|
properties.instanceView
|
VirtualMachineInstanceView
|
Представление экземпляра виртуальной машины.
|
properties.licenseType
|
string
|
Указывает, что используемый образ или диск были лицензированы локально.
Возможные значения операционной системы Windows Server:
Windows_Client
Windows_Server
Возможные значения для операционной системы Linux Server:
RHEL_BYOS (для RHEL)
SLES_BYOS (для SUSE)
Дополнительные сведения см. в статье Преимущество гибридного использования Azure для Windows Server.
Преимущество гибридного использования Azure для сервера Linux
Минимальная версия API: 15.06.2015
|
properties.networkProfile
|
NetworkProfile
|
Указывает сетевые интерфейсы виртуальной машины.
|
properties.osProfile
|
OSProfile
|
Указывает параметры операционной системы, используемые при создании виртуальной машины. Некоторые параметры нельзя изменить после подготовки виртуальной машины.
|
properties.platformFaultDomain
|
integer
|
Указывает домен логического сбоя масштабируемого набора, в котором будет создана виртуальная машина. По умолчанию виртуальная машина будет автоматически назначена домену сбоя, который лучше всего поддерживает баланс между доступными доменами сбоя. Это применимо, только если задано свойство "virtualMachineScaleSet" этой виртуальной машины. Масштабируемый набор виртуальных машин, на который ссылается, должен иметь параметр platformFaultDomainCount больше 1. Это свойство нельзя обновить после создания виртуальной машины. Назначение домена сбоя можно просмотреть в представлении экземпляра виртуальной машины. Минимальная версия api:2020,12,01.
|
properties.priority
|
VirtualMachinePriorityTypes
|
Указывает приоритет для виртуальной машины. Минимальная версия API: 2019-03-01
|
properties.provisioningState
|
string
|
Состояние подготовки, которое отображается только в ответе.
|
properties.proximityPlacementGroup
|
SubResource
|
Указывает сведения о группе размещения близкого взаимодействия, в которую должна быть назначена виртуальная машина. Минимальная версия API: 2018-04-01.
|
properties.scheduledEventsPolicy
|
ScheduledEventsPolicy
|
Указывает конфигурации, связанные с событиями повторного развертывания, перезагрузки и scheduledEventsAdditionalPublishingTargets Для виртуальной машины.
|
properties.scheduledEventsProfile
|
ScheduledEventsProfile
|
Указывает конфигурации, связанные с запланированными событиями.
|
properties.securityProfile
|
SecurityProfile
|
Задает параметры профиля, связанного с безопасностью, для виртуальной машины.
|
properties.storageProfile
|
StorageProfile
|
Указывает параметры хранилища дисков виртуальной машины.
|
properties.timeCreated
|
string
|
Указывает время создания ресурса виртуальной машины. Минимальная версия API: 2021-11-01.
|
properties.userData
|
string
|
UserData для виртуальной машины, которая должна быть закодирована в кодировке Base-64. Клиент не должен передавать здесь какие-либо секреты. Минимальная версия API: 2021-03-01.
|
properties.virtualMachineScaleSet
|
SubResource
|
Указывает сведения о масштабируемом наборе виртуальных машин, которому должна быть назначена виртуальная машина. Виртуальные машины, указанные в одном масштабируемом наборе виртуальных машин, выделяются для разных узлов, чтобы обеспечить максимальную доступность. В настоящее время виртуальную машину можно добавить в масштабируемый набор виртуальных машин только во время создания. Существующую виртуальную машину нельзя добавить в масштабируемый набор виртуальных машин. Это свойство не может существовать вместе со ссылкой properties.availabilitySet, отличной от NULL. Минимальная версия api:2019,03,01.
|
properties.vmId
|
string
|
Указывает уникальный идентификатор виртуальной машины, который является 128-разрядным идентификатором, который кодируется и хранится во всех виртуальных машинах Azure IaaS SMBIOS и может быть считан с помощью команд BIOS платформы.
|
resources
|
VirtualMachineExtension[]
|
Ресурсы дочернего расширения виртуальной машины.
|
tags
|
object
|
Теги ресурсов
|
type
|
string
|
Тип ресурса
|
zones
|
string[]
|
Зоны виртуальных машин.
|
VirtualMachineAgentInstanceView
Агент виртуальной машины, работающий на виртуальной машине.
VirtualMachineEvictionPolicyTypes
Указывает политику вытеснения для точечных виртуальных машин Azure и точечных масштабируемых наборов Azure. Для точечных виртуальных машин Azure поддерживаются как "Отменить выделение", так и "Удалить", а минимальная версия API — 2019-03-01. Для точечных масштабируемых наборов Azure поддерживаются как Deallocate, так и Delete, а минимальная версия API — 2017-10-30-preview.
Имя |
Тип |
Описание |
Deallocate
|
string
|
|
Delete
|
string
|
|
VirtualMachineExtension
Ресурсы дочернего расширения виртуальной машины.
Имя |
Тип |
Описание |
id
|
string
|
Идентификатор ресурса
|
location
|
string
|
Расположение ресурса
|
name
|
string
|
Имя ресурса
|
properties.autoUpgradeMinorVersion
|
boolean
|
Указывает, должно ли расширение использовать более новую дополнительную версию, если она доступна во время развертывания. Однако после развертывания расширение не будет обновляться до дополнительных версий, кроме случаев повторного развертывания, даже если это свойство имеет значение true.
|
properties.enableAutomaticUpgrade
|
boolean
|
Указывает, должно ли расширение автоматически обновляться платформой, если доступна более новая версия расширения.
|
properties.forceUpdateTag
|
string
|
Способ принудительного обновления обработчика расширений, даже если конфигурация расширения не изменилась.
|
properties.instanceView
|
VirtualMachineExtensionInstanceView
|
Представление экземпляра расширения виртуальной машины.
|
properties.protectedSettings
|
object
|
Расширение может содержать protectedSettings или protectedSettingsFromKeyVault или вообще не иметь защищенных параметров.
|
properties.protectedSettingsFromKeyVault
|
KeyVaultSecretReference
|
Расширения защищают параметры, которые передаются по ссылке и используются из хранилища ключей.
|
properties.provisionAfterExtensions
|
string[]
|
Коллекция имен расширений, после которых необходимо подготовить это расширение.
|
properties.provisioningState
|
string
|
Состояние подготовки, которое отображается только в ответе.
|
properties.publisher
|
string
|
Имя издателя обработчика расширений.
|
properties.settings
|
object
|
Общедоступные параметры расширения в формате JSON.
|
properties.suppressFailures
|
boolean
|
Указывает, будут ли сбои, вытекающие из расширения, подавляться (операционные сбои, такие как отсутствие подключения к виртуальной машине, не будут подавляться независимо от этого значения). Значение по умолчанию — false.
|
properties.type
|
string
|
Указывает тип расширения; пример : CustomScriptExtension.
|
properties.typeHandlerVersion
|
string
|
Указывает версию обработчика скрипта.
|
tags
|
object
|
Теги ресурсов
|
type
|
string
|
Тип ресурса
|
VirtualMachineExtensionHandlerInstanceView
Представление экземпляра обработчика расширения виртуальной машины.
Имя |
Тип |
Описание |
status
|
InstanceViewStatus
|
Состояние обработчика расширения.
|
type
|
string
|
Указывает тип расширения; пример : CustomScriptExtension.
|
typeHandlerVersion
|
string
|
Указывает версию обработчика скрипта.
|
VirtualMachineExtensionInstanceView
Представление экземпляра расширения виртуальной машины.
Имя |
Тип |
Описание |
name
|
string
|
Имя расширения виртуальной машины.
|
statuses
|
InstanceViewStatus[]
|
Сведения о состоянии ресурса.
|
substatuses
|
InstanceViewStatus[]
|
Сведения о состоянии ресурса.
|
type
|
string
|
Указывает тип расширения; пример : CustomScriptExtension.
|
typeHandlerVersion
|
string
|
Указывает версию обработчика скрипта.
|
VirtualMachineHealthStatus
Состояние работоспособности виртуальной машины.
Имя |
Тип |
Описание |
status
|
InstanceViewStatus
|
Сведения о состоянии работоспособности виртуальной машины.
|
VirtualMachineIdentity
Удостоверение виртуальной машины, если настроено.
Имя |
Тип |
Описание |
principalId
|
string
|
Идентификатор субъекта удостоверения виртуальной машины. Это свойство будет предоставлено только для удостоверения, назначаемого системой.
|
tenantId
|
string
|
Идентификатор клиента, связанный с виртуальной машиной. Это свойство будет предоставлено только для удостоверения, назначаемого системой.
|
type
|
ResourceIdentityType
|
Тип удостоверения, используемого для виртуальной машины. Тип SystemAssigned, UserAssigned включает как условно созданное удостоверение, так и набор удостоверений, назначенных пользователем. Тип None приведет к удалению всех удостоверений из виртуальной машины.
|
userAssignedIdentities
|
UserAssignedIdentities
|
Список удостоверений пользователей, связанных с виртуальной машиной. Ссылки на ключ словаря удостоверений пользователей будут иметь идентификаторы ресурсов ARM в формате "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}".
|
VirtualMachineInstanceView
Представление экземпляра виртуальной машины.
Имя |
Тип |
Описание |
assignedHost
|
string
|
Идентификатор ресурса выделенного узла, на котором выделена виртуальная машина путем автоматического размещения, если виртуальная машина связана с выделенной группой узлов с включенным автоматическим размещением. Минимальная версия API: 2020-06-01.
|
bootDiagnostics
|
BootDiagnosticsInstanceView
|
Диагностика загрузки — это функция отладки, которая позволяет просматривать выходные данные консоли и снимок экрана для диагностики состояния виртуальной машины. Вы можете легко просмотреть выходные данные журнала консоли. Azure также позволяет просмотреть снимок экрана виртуальной машины из низкоуровневой оболочки.
|
computerName
|
string
|
Имя компьютера, назначенное виртуальной машине.
|
disks
|
DiskInstanceView[]
|
Сведения о диске виртуальной машины.
|
extensions
|
VirtualMachineExtensionInstanceView[]
|
Сведения о расширениях.
|
hyperVGeneration
|
HyperVGenerationType
|
Указывает тип HyperVGeneration, связанный с ресурсом.
|
isVMInStandbyPool
|
boolean
|
[Предварительная версия функции] Указывает, находится ли виртуальная машина в резервном пуле или из него.
|
maintenanceRedeployStatus
|
MaintenanceRedeployStatus
|
Состояние операции обслуживания на виртуальной машине.
|
osName
|
string
|
Операционная система, запущенная на виртуальной машине.
|
osVersion
|
string
|
Версия операционной системы, работающей на виртуальной машине.
|
patchStatus
|
VirtualMachinePatchStatus
|
[Предварительная версия функции] Состояние операций исправления виртуальной машины.
|
platformFaultDomain
|
integer
|
Задает домен сбоя виртуальной машины.
|
platformUpdateDomain
|
integer
|
Задает домен обновления виртуальной машины.
|
rdpThumbPrint
|
string
|
Отпечаток сертификата удаленного рабочего стола.
|
statuses
|
InstanceViewStatus[]
|
Сведения о состоянии ресурса.
|
vmAgent
|
VirtualMachineAgentInstanceView
|
Агент виртуальной машины, работающий на виртуальной машине.
|
vmHealth
|
VirtualMachineHealthStatus
|
Состояние работоспособности виртуальной машины.
|
VirtualMachineIpTag
Список тегов IP-адресов, связанных с общедоступным IP-адресом.
Имя |
Тип |
Описание |
ipTagType
|
string
|
Тип тега IP. Пример: FirstPartyUsage.
|
tag
|
string
|
Тег IP, связанный с общедоступным IP-адресом. Пример: SQL, Хранилище и т. д.
|
VirtualMachineNetworkInterfaceConfiguration
Задает конфигурации сети, которые будут использоваться для создания сетевых ресурсов виртуальной машины.
Имя |
Тип |
Описание |
name
|
string
|
Имя конфигурации сетевого интерфейса.
|
properties.auxiliaryMode
|
NetworkInterfaceAuxiliaryMode
|
Указывает, включен ли вспомогательный режим для ресурса сетевого интерфейса.
|
properties.auxiliarySku
|
NetworkInterfaceAuxiliarySku
|
Указывает, включен ли вспомогательный SKU для ресурса сетевого интерфейса.
|
properties.deleteOption
|
DeleteOptions
|
Укажите, что происходит с сетевым интерфейсом при удалении виртуальной машины
|
properties.disableTcpStateTracking
|
boolean
|
Указывает, отключен ли сетевой интерфейс для отслеживания состояния TCP.
|
properties.dnsSettings
|
VirtualMachineNetworkInterfaceDnsSettingsConfiguration
|
Параметры DNS, применяемые к сетевым интерфейсам.
|
properties.dscpConfiguration
|
SubResource
|
|
properties.enableAcceleratedNetworking
|
boolean
|
Указывает, включена ли в сетевом интерфейсе функция ускорения сети.
|
properties.enableFpga
|
boolean
|
Указывает, включен ли сетевой интерфейс ППВМ с поддержкой сети.
|
properties.enableIPForwarding
|
boolean
|
Включена ли IP-пересылка на этом сетевом адаптере.
|
properties.ipConfigurations
|
VirtualMachineNetworkInterfaceIPConfiguration[]
|
Задает IP-конфигурации сетевого интерфейса.
|
properties.networkSecurityGroup
|
SubResource
|
Группа безопасности сети.
|
properties.primary
|
boolean
|
Указывает основной сетевой интерфейс, если виртуальная машина имеет более 1 сетевого интерфейса.
|
VirtualMachineNetworkInterfaceDnsSettingsConfiguration
Параметры DNS, применяемые к сетевым интерфейсам.
Имя |
Тип |
Описание |
dnsServers
|
string[]
|
Список IP-адресов DNS-серверов
|
VirtualMachineNetworkInterfaceIPConfiguration
Задает IP-конфигурации сетевого интерфейса.
Имя |
Тип |
Описание |
name
|
string
|
Имя IP-конфигурации.
|
properties.applicationGatewayBackendAddressPools
|
SubResource[]
|
Задает массив ссылок на серверные пулы адресов шлюзов приложений. Виртуальная машина может ссылаться на серверные пулы адресов нескольких шлюзов приложений. Несколько виртуальных машин не могут использовать один и тот же шлюз приложений.
|
properties.applicationSecurityGroups
|
SubResource[]
|
Задает массив ссылок на группу безопасности приложений.
|
properties.loadBalancerBackendAddressPools
|
SubResource[]
|
Задает массив ссылок на серверные пулы адресов подсистем балансировки нагрузки. Виртуальная машина может ссылаться на серверные пулы адресов одного общедоступного и одного внутреннего балансировщика нагрузки. [Несколько виртуальных машин не могут использовать одну и ту же подсистему балансировки нагрузки ценовой категории "Базовый"].
|
properties.primary
|
boolean
|
Указывает основной сетевой интерфейс, если виртуальная машина имеет более 1 сетевого интерфейса.
|
properties.privateIPAddressVersion
|
IPVersions
|
Доступно с Api-Version 2017-03-30 и более поздних, он указывает, является ли конкретная ipconfiguration IPv4 или IPv6. Значение по умолчанию принимается как IPv4. Возможные значения: IPv4 и IPv6.
|
properties.publicIPAddressConfiguration
|
VirtualMachinePublicIPAddressConfiguration
|
PublicIPAddressConfiguration.
|
properties.subnet
|
SubResource
|
Указывает идентификатор подсети.
|
VirtualMachinePatchStatus
[Предварительная версия функции] Состояние операций исправления виртуальной машины.
Имя |
Тип |
Описание |
availablePatchSummary
|
AvailablePatchSummary
|
Сводка доступных исправлений последней операции оценки для виртуальной машины.
|
configurationStatuses
|
InstanceViewStatus[]
|
Состояние включения указанного patchMode
|
lastPatchInstallationSummary
|
LastPatchInstallationSummary
|
Сводка по последней операции установки виртуальной машины.
|
VirtualMachinePriorityTypes
Указывает приоритет для виртуальной машины. Минимальная версия API: 2019-03-01
Имя |
Тип |
Описание |
Low
|
string
|
|
Regular
|
string
|
|
Spot
|
string
|
|
VirtualMachinePublicIPAddressConfiguration
PublicIPAddressConfiguration.
Имя |
Тип |
Описание |
name
|
string
|
Имя конфигурации адреса publicIP.
|
properties.deleteOption
|
DeleteOptions
|
Укажите, что происходит с общедоступным IP-адресом при удалении виртуальной машины
|
properties.dnsSettings
|
VirtualMachinePublicIPAddressDnsSettingsConfiguration
|
Параметры DNS, применяемые к общедоступным IP-адресам.
|
properties.idleTimeoutInMinutes
|
integer
|
Время ожидания простоя общедоступного IP-адреса.
|
properties.ipTags
|
VirtualMachineIpTag[]
|
Список тегов IP-адресов, связанных с общедоступным IP-адресом.
|
properties.publicIPAddressVersion
|
IPVersions
|
Доступно с Api-Version 2019-07-01, он указывает, является ли конкретная ip-конфигурация IPv4 или IPv6. Значение по умолчанию принимается как IPv4. Возможные значения: IPv4 и IPv6.
|
properties.publicIPAllocationMethod
|
PublicIPAllocationMethod
|
Указание типа выделения общедоступного IP-адреса
|
properties.publicIPPrefix
|
SubResource
|
PublicIPPrefix, из которого следует выделить общедоступные IP-адреса.
|
sku
|
PublicIPAddressSku
|
Описывает номер SKU общедоступного IP-адреса. Его можно задать только с параметром OrchestrationMode как Гибкий.
|
VirtualMachinePublicIPAddressDnsSettingsConfiguration
Параметры DNS, применяемые к общедоступным IP-адресам.
Имя |
Тип |
Описание |
domainNameLabel
|
string
|
Префикс метки доменного имени для ресурсов PublicIPAddress, которые будут созданы. Созданная метка имени — это объединение метки доменного имени и уникального идентификатора сетевого профиля виртуальной машины.
|
domainNameLabelScope
|
DomainNameLabelScopeTypes
|
Метка доменного имени область ресурсов PublicIPAddress, которые будут созданы. Созданная метка имени — это объединение хэшированных меток доменного имени с политикой в соответствии с меткой доменного имени область и уникальным идентификатором сетевого профиля виртуальной машины.
|
VirtualMachineSizeTypes
Задает размер виртуальной машины. Тип данных перечисления в настоящее время является устаревшим и будет удален до 23 декабря 2023 г. Рекомендуемый способ получить список доступных размеров — использовать следующие API: Перечисление всех доступных размеров виртуальных машин в группе доступности, Перечисление всех доступных размеров виртуальных машин в регионе, Перечисление всех доступных размеров виртуальных машин для изменения размера. Дополнительные сведения о размерах виртуальных машин см. в разделе Размеры виртуальных машин. Доступные размеры виртуальных машин зависят от региона и группы доступности.
Имя |
Тип |
Описание |
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
Указывает профиль безопасности для управляемого диска.
Имя |
Тип |
Описание |
diskEncryptionSet
|
DiskEncryptionSetParameters
|
Указывает идентификатор ресурса набора шифрования управляемых пользователем дисков для управляемого диска, который используется для зашифрованного ключа конфиденциальной виртуальной машины и большого двоичного объекта VMGuest.
|
securityEncryptionType
|
securityEncryptionTypes
|
Указывает Тип шифрования управляемого диска. Для него задано значение DiskWithVMGuestState для шифрования управляемого диска вместе с BLOB-объектом VMGuestState, VMGuestStateOnly для шифрования только большого двоичного объекта VMGuestState и NonPersistedTPM для того, чтобы не сохранять состояние встроенного ПО в BLOB-объекте VMGuestState.
Примечание: Его можно задать только для конфиденциальных виртуальных машин.
|
VMGalleryApplication
Указывает приложения коллекции, которые должны быть доступны для виртуальной машины или VMSS.
Имя |
Тип |
Описание |
configurationReference
|
string
|
Необязательно. Указывает универсальный код ресурса (URI) большого двоичного объекта Azure, который заменит конфигурацию по умолчанию для пакета, если он указан.
|
enableAutomaticUpgrade
|
boolean
|
Если задано значение true, при наличии новой версии приложения коллекции в PIR/SIG она будет автоматически обновлена для виртуальной машины или VMSS.
|
order
|
integer
|
Необязательный параметр. Указывает порядок установки пакетов.
|
packageReferenceId
|
string
|
Указывает идентификатор ресурса GalleryApplicationVersion в форме /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.Compute/gallerys/{galleryName}/applications/{application}/versions/{versions/{version}
|
tags
|
string
|
Необязательно. Задает значение сквозной передачи для более универсального контекста.
|
treatFailureAsDeploymentFailure
|
boolean
|
Необязательно. Если значение равно true, любой сбой для любой операции в VmApplication приведет к сбою развертывания.
|
VMSizeProperties
Задает свойства для настройки размера виртуальной машины. Минимальная версия API: 2021-07-01. Эта функция по-прежнему находится в режиме предварительной версии и не поддерживается для VirtualMachineScaleSet. Для получения дополнительных сведений следуйте инструкциям в разделе Настройка виртуальной машины .
Имя |
Тип |
Описание |
vCPUsAvailable
|
integer
|
Указывает количество виртуальных ЦП, доступных для виртуальной машины. Если это свойство не указано в тексте запроса, по умолчанию ему присваивается значение виртуальных ЦП, доступных для этого размера виртуальной машины, которое отображается в ответе API списка всех доступных размеров виртуальных машин в регионе.
|
vCPUsPerCore
|
integer
|
Указывает соотношение виртуальных ЦП и физических ядер. Если это свойство не указано в тексте запроса, по умолчанию устанавливается значение vCPUsPerCore для размера виртуальной машины, предоставляемого в ответе API в разделе Список всех доступных размеров виртуальных машин в регионе.
Установка для этого свойства значения 1 также означает, что гиперпотония отключена.
|
WindowsConfiguration
Указывает параметры операционной системы Windows на виртуальной машине.
Имя |
Тип |
Описание |
additionalUnattendContent
|
AdditionalUnattendContent[]
|
Задает дополнительные сведения в кодировке base-64 и в формате XML, которые могут включаться в файл Unattend.xml, используемый программой установки Windows.
|
enableAutomaticUpdates
|
boolean
|
Указывает, включена ли автоматическая Обновления для виртуальной машины Windows. Значение по умолчанию — true. Для масштабируемых наборов виртуальных машин это свойство можно обновить, и обновления вступают в силу при повторной подготовке ОС.
|
enableVMAgentPlatformUpdates
|
boolean
|
Указывает, включена ли для виртуальной машины Windows Обновления платформы VMAgent. Значение по умолчанию — false.
|
patchSettings
|
PatchSettings
|
[Предварительная версия функции] Задает параметры, связанные с установкой исправлений гостевой виртуальной машины в Windows.
|
provisionVMAgent
|
boolean
|
Указывает, должен ли агент виртуальной машины быть подготовлен на виртуальной машине. Если это свойство не указано в тексте запроса, по умолчанию ему присваивается значение true. Это гарантирует, что агент виртуальной машины будет установлен на виртуальной машине, чтобы расширения можно было добавить в виртуальную машину позже.
|
timeZone
|
string
|
Указывает часовой пояс виртуальной машины. Например, "Тихоокеанское стандартное время". Возможные значения могут быть TimeZoneInfo.Id значения из часовых поясов, возвращаемых TimeZoneInfo.GetSystemTimeZones.
|
winRM
|
WinRMConfiguration
|
Задает прослушиватели удаленного управления Windows. Это включает удаленное взаимодействие с Windows PowerShell.
|
WindowsPatchAssessmentMode
Указывает режим оценки исправлений гостевой виртуальной машины для виртуальной машины IaaS.
Возможны следующие значения:
ImageDefault — вы управляете временем оценки исправлений на виртуальной машине.
AutomaticByPlatform — платформа запускает периодические оценки исправлений. Свойство provisionVMAgent должно иметь значение true.
Имя |
Тип |
Описание |
AutomaticByPlatform
|
string
|
|
ImageDefault
|
string
|
|
Задает параметр перезагрузки для всех операций установки исправлений AutomaticByPlatform.
Имя |
Тип |
Описание |
Always
|
string
|
|
IfRequired
|
string
|
|
Never
|
string
|
|
Unknown
|
string
|
|
Задает дополнительные параметры для режима исправления AutomaticByPlatform в гостевой системе исправлений виртуальной машины в Windows.
Имя |
Тип |
Описание |
bypassPlatformSafetyChecksOnUserSchedule
|
boolean
|
Позволяет клиенту планировать установку исправлений без случайных обновлений
|
rebootSetting
|
WindowsVMGuestPatchAutomaticByPlatformRebootSetting
|
Задает параметр перезагрузки для всех операций установки исправлений AutomaticByPlatform.
|
WindowsVMGuestPatchMode
Указывает режим установки исправлений гостевой виртуальной машины для виртуальной машины IaaS или виртуальных машин, связанных с масштабируемым набором виртуальных машин с параметром OrchestrationMode как гибкий.
Возможны следующие значения:
Вручную . Вы управляете применением исправлений на виртуальной машине. Это можно сделать, применяя исправления вручную на виртуальной машине. В этом режиме автоматические обновления отключены; свойство WindowsConfiguration.enableAutomaticUpdates должно иметь значение false.
AutomaticByOS — виртуальная машина автоматически обновляется ОС. Свойство WindowsConfiguration.enableAutomaticUpdates должно иметь значение true.
AutomaticByPlatform — виртуальная машина автоматически обновляется платформой. Свойства provisionVMAgent и WindowsConfiguration.enableAutomaticUpdates должны иметь значение true.
Имя |
Тип |
Описание |
AutomaticByOS
|
string
|
|
AutomaticByPlatform
|
string
|
|
Manual
|
string
|
|
WinRMConfiguration
Указывает прослушиватели удаленного управления Windows. Это включает удаленное взаимодействие с Windows PowerShell.
Имя |
Тип |
Описание |
listeners
|
WinRMListener[]
|
Список прослушивателей удаленного управления Windows
|
WinRMListener
Список прослушивателей удаленного управления Windows