Создайте или обновите группы контейнеров с указанными конфигурациями.
PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}?api-version=2023-05-01
Параметры URI
Имя |
В |
Обязательно |
Тип |
Описание |
containerGroupName
|
path |
True
|
string
|
Имя группы контейнеров.
|
resourceGroupName
|
path |
True
|
string
|
Имя группы ресурсов.
|
subscriptionId
|
path |
True
|
string
|
Учетные данные подписки, которые однозначно определяют подписку Microsoft Azure. Идентификатор подписки входит в состав URI для каждого вызова службы.
|
api-version
|
query |
True
|
string
|
Версия API клиента
|
Текст запроса
Имя |
Обязательно |
Тип |
Описание |
properties.containers
|
True
|
Container[]
|
Контейнеры в группе контейнеров.
|
properties.osType
|
True
|
OperatingSystemTypes
|
Тип операционной системы, необходимый контейнерам в группе контейнеров.
|
identity
|
|
ContainerGroupIdentity
|
Удостоверение группы контейнеров, если настроено.
|
location
|
|
string
|
Расположение ресурса.
|
properties.confidentialComputeProperties
|
|
ConfidentialComputeProperties
|
Свойства для конфиденциальной группы контейнеров
|
properties.diagnostics
|
|
ContainerGroupDiagnostics
|
Диагностические сведения для группы контейнеров.
|
properties.dnsConfig
|
|
DnsConfiguration
|
Сведения о конфигурации DNS для группы контейнеров.
|
properties.encryptionProperties
|
|
EncryptionProperties
|
Свойства шифрования для группы контейнеров.
|
properties.extensions
|
|
DeploymentExtensionSpec[]
|
расширения, используемые виртуальным kubelet
|
properties.imageRegistryCredentials
|
|
ImageRegistryCredential[]
|
Учетные данные реестра образов, из которых создается группа контейнеров.
|
properties.initContainers
|
|
InitContainerDefinition[]
|
Контейнеры инициализации для группы контейнеров.
|
properties.ipAddress
|
|
IpAddress
|
Тип IP-адреса группы контейнеров.
|
properties.priority
|
|
ContainerGroupPriority
|
Приоритет группы контейнеров.
|
properties.restartPolicy
|
|
ContainerGroupRestartPolicy
|
Перезапустите политику для всех контейнеров в группе контейнеров.
-
Always Всегда перезапуск
-
OnFailure перезапуск при сбое
-
Never никогда не перезапускать
|
properties.sku
|
|
ContainerGroupSku
|
Номер SKU для группы контейнеров.
|
properties.subnetIds
|
|
ContainerGroupSubnetId[]
|
Идентификаторы ресурсов подсети для группы контейнеров.
|
properties.volumes
|
|
Volume[]
|
Список томов, которые могут быть подключены контейнерами в этой группе контейнеров.
|
tags
|
|
object
|
Теги ресурсов.
|
zones
|
|
string[]
|
Зоны для группы контейнеров.
|
Ответы
Имя |
Тип |
Описание |
200 OK
|
ContainerGroup
|
ХОРОШО
|
201 Created
|
ContainerGroup
|
Создано — создается группа контейнеров.
|
Other Status Codes
|
CloudError
|
Ответ на ошибку, описывающий причину сбоя операции.
|
Безопасность
azure_auth
Поток OAuth2 Azure Active Directory
Тип:
oauth2
Flow:
implicit
URL-адрес авторизации:
https://login.microsoftonline.com/common/oauth2/authorize
Области
Имя |
Описание |
user_impersonation
|
Олицетворения учетной записи пользователя
|
Примеры
ConfidentialContainerGroup
Образец запроса
PUT https://management.azure.com/subscriptions/subid/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/demo1?api-version=2023-05-01
{
"location": "westeurope",
"properties": {
"containers": [
{
"name": "accdemo",
"properties": {
"command": [],
"environmentVariables": [],
"image": "confiimage",
"ports": [
{
"port": 8000
}
],
"resources": {
"requests": {
"cpu": 1,
"memoryInGB": 1.5
}
},
"securityContext": {
"privileged": false,
"capabilities": {
"add": [
"CAP_NET_ADMIN"
]
}
}
}
}
],
"imageRegistryCredentials": [],
"ipAddress": {
"ports": [
{
"protocol": "TCP",
"port": 8000
}
],
"type": "Public"
},
"osType": "Linux",
"sku": "Confidential",
"confidentialComputeProperties": {
"ccePolicy": "eyJhbGxvd19hbGwiOiB0cnVlLCAiY29udGFpbmVycyI6IHsibGVuZ3RoIjogMCwgImVsZW1lbnRzIjogbnVsbH19"
}
}
}
import com.azure.resourcemanager.containerinstance.fluent.models.ContainerGroupInner;
import com.azure.resourcemanager.containerinstance.models.ConfidentialComputeProperties;
import com.azure.resourcemanager.containerinstance.models.Container;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupIpAddressType;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupNetworkProtocol;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupSku;
import com.azure.resourcemanager.containerinstance.models.ContainerPort;
import com.azure.resourcemanager.containerinstance.models.IpAddress;
import com.azure.resourcemanager.containerinstance.models.OperatingSystemTypes;
import com.azure.resourcemanager.containerinstance.models.Port;
import com.azure.resourcemanager.containerinstance.models.ResourceRequests;
import com.azure.resourcemanager.containerinstance.models.ResourceRequirements;
import com.azure.resourcemanager.containerinstance.models.SecurityContextCapabilitiesDefinition;
import com.azure.resourcemanager.containerinstance.models.SecurityContextDefinition;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for ContainerGroups CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/
* ContainerGroupCreateConfidential.json
*/
/**
* Sample code: ConfidentialContainerGroup.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void confidentialContainerGroup(com.azure.resourcemanager.AzureResourceManager azure) {
azure.containerGroups().manager().serviceClient().getContainerGroups().createOrUpdate("demo", "demo1",
new ContainerGroupInner().withLocation("westeurope")
.withContainers(Arrays.asList(new Container().withName("accdemo").withImage("confiimage")
.withCommand(Arrays.asList()).withPorts(Arrays.asList(new ContainerPort().withPort(8000)))
.withEnvironmentVariables(Arrays.asList())
.withResources(new ResourceRequirements()
.withRequests(new ResourceRequests().withMemoryInGB(1.5).withCpu(1.0)))
.withSecurityContext(new SecurityContextDefinition().withPrivileged(false).withCapabilities(
new SecurityContextCapabilitiesDefinition().withAdd(Arrays.asList("CAP_NET_ADMIN"))))))
.withImageRegistryCredentials(Arrays.asList())
.withIpAddress(new IpAddress()
.withPorts(Arrays.asList(new Port().withProtocol(ContainerGroupNetworkProtocol.TCP).withPort(8000)))
.withType(ContainerGroupIpAddressType.PUBLIC))
.withOsType(OperatingSystemTypes.LINUX).withSku(ContainerGroupSku.CONFIDENTIAL)
.withConfidentialComputeProperties(new ConfidentialComputeProperties().withCcePolicy(
"eyJhbGxvd19hbGwiOiB0cnVlLCAiY29udGFpbmVycyI6IHsibGVuZ3RoIjogMCwgImVsZW1lbnRzIjogbnVsbH19")),
com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from azure.identity import DefaultAzureCredential
from azure.mgmt.containerinstance import ContainerInstanceManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-containerinstance
# USAGE
python container_group_create_confidential.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 = ContainerInstanceManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.container_groups.begin_create_or_update(
resource_group_name="demo",
container_group_name="demo1",
container_group={
"location": "westeurope",
"properties": {
"confidentialComputeProperties": {
"ccePolicy": "eyJhbGxvd19hbGwiOiB0cnVlLCAiY29udGFpbmVycyI6IHsibGVuZ3RoIjogMCwgImVsZW1lbnRzIjogbnVsbH19"
},
"containers": [
{
"name": "accdemo",
"properties": {
"command": [],
"environmentVariables": [],
"image": "confiimage",
"ports": [{"port": 8000}],
"resources": {"requests": {"cpu": 1, "memoryInGB": 1.5}},
"securityContext": {"capabilities": {"add": ["CAP_NET_ADMIN"]}, "privileged": False},
},
}
],
"imageRegistryCredentials": [],
"ipAddress": {"ports": [{"port": 8000, "protocol": "TCP"}], "type": "Public"},
"osType": "Linux",
"sku": "Confidential",
},
},
).result()
print(response)
# x-ms-original-file: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupCreateConfidential.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 armcontainerinstance_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/containerinstance/armcontainerinstance/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e60df62e9e0d88462e6abba81a76d94eab000f0d/specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupCreateConfidential.json
func ExampleContainerGroupsClient_BeginCreateOrUpdate_confidentialContainerGroup() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcontainerinstance.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewContainerGroupsClient().BeginCreateOrUpdate(ctx, "demo", "demo1", armcontainerinstance.ContainerGroup{
Properties: &armcontainerinstance.ContainerGroupPropertiesProperties{
ConfidentialComputeProperties: &armcontainerinstance.ConfidentialComputeProperties{
CcePolicy: to.Ptr("eyJhbGxvd19hbGwiOiB0cnVlLCAiY29udGFpbmVycyI6IHsibGVuZ3RoIjogMCwgImVsZW1lbnRzIjogbnVsbH19"),
},
Containers: []*armcontainerinstance.Container{
{
Name: to.Ptr("accdemo"),
Properties: &armcontainerinstance.ContainerProperties{
Command: []*string{},
EnvironmentVariables: []*armcontainerinstance.EnvironmentVariable{},
Image: to.Ptr("confiimage"),
Ports: []*armcontainerinstance.ContainerPort{
{
Port: to.Ptr[int32](8000),
}},
Resources: &armcontainerinstance.ResourceRequirements{
Requests: &armcontainerinstance.ResourceRequests{
CPU: to.Ptr[float64](1),
MemoryInGB: to.Ptr[float64](1.5),
},
},
SecurityContext: &armcontainerinstance.SecurityContextDefinition{
Capabilities: &armcontainerinstance.SecurityContextCapabilitiesDefinition{
Add: []*string{
to.Ptr("CAP_NET_ADMIN")},
},
Privileged: to.Ptr(false),
},
},
}},
ImageRegistryCredentials: []*armcontainerinstance.ImageRegistryCredential{},
IPAddress: &armcontainerinstance.IPAddress{
Type: to.Ptr(armcontainerinstance.ContainerGroupIPAddressTypePublic),
Ports: []*armcontainerinstance.Port{
{
Port: to.Ptr[int32](8000),
Protocol: to.Ptr(armcontainerinstance.ContainerGroupNetworkProtocolTCP),
}},
},
OSType: to.Ptr(armcontainerinstance.OperatingSystemTypesLinux),
SKU: to.Ptr(armcontainerinstance.ContainerGroupSKUConfidential),
},
Location: to.Ptr("westeurope"),
}, 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.ContainerGroup = armcontainerinstance.ContainerGroup{
// Properties: &armcontainerinstance.ContainerGroupPropertiesProperties{
// ConfidentialComputeProperties: &armcontainerinstance.ConfidentialComputeProperties{
// CcePolicy: to.Ptr("eyJhbGxvd19hbGwiOiB0cnVlLCAiY29udGFpbmVycyI6IHsibGVuZ3RoIjogMCwgImVsZW1lbnRzIjogbnVsbH19"),
// },
// Containers: []*armcontainerinstance.Container{
// {
// Name: to.Ptr("accdemo"),
// Properties: &armcontainerinstance.ContainerProperties{
// Command: []*string{
// },
// EnvironmentVariables: []*armcontainerinstance.EnvironmentVariable{
// },
// Image: to.Ptr("confiimage"),
// Ports: []*armcontainerinstance.ContainerPort{
// {
// Port: to.Ptr[int32](8000),
// }},
// Resources: &armcontainerinstance.ResourceRequirements{
// Requests: &armcontainerinstance.ResourceRequests{
// CPU: to.Ptr[float64](1),
// MemoryInGB: to.Ptr[float64](1.5),
// },
// },
// SecurityContext: &armcontainerinstance.SecurityContextDefinition{
// Capabilities: &armcontainerinstance.SecurityContextCapabilitiesDefinition{
// Add: []*string{
// to.Ptr("CAP_NET_ADMIN")},
// },
// Privileged: to.Ptr(false),
// },
// },
// }},
// ImageRegistryCredentials: []*armcontainerinstance.ImageRegistryCredential{
// },
// InitContainers: []*armcontainerinstance.InitContainerDefinition{
// },
// InstanceView: &armcontainerinstance.ContainerGroupPropertiesInstanceView{
// Events: []*armcontainerinstance.Event{
// },
// State: to.Ptr("Running"),
// },
// IPAddress: &armcontainerinstance.IPAddress{
// Type: to.Ptr(armcontainerinstance.ContainerGroupIPAddressTypePublic),
// Ports: []*armcontainerinstance.Port{
// {
// Port: to.Ptr[int32](8000),
// Protocol: to.Ptr(armcontainerinstance.ContainerGroupNetworkProtocolTCP),
// }},
// },
// OSType: to.Ptr(armcontainerinstance.OperatingSystemTypesLinux),
// ProvisioningState: to.Ptr("Succeeded"),
// SKU: to.Ptr(armcontainerinstance.ContainerGroupSKUConfidential),
// },
// Name: to.Ptr("demo1"),
// Type: to.Ptr("Microsoft.ContainerInstance/containerGroups"),
// ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.ContainerInstance/containerGroups/demo1"),
// Location: to.Ptr("westeurope"),
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ContainerInstanceManagementClient } = require("@azure/arm-containerinstance");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Create or update container groups with specified configurations.
*
* @summary Create or update container groups with specified configurations.
* x-ms-original-file: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupCreateConfidential.json
*/
async function confidentialContainerGroup() {
const subscriptionId = process.env["CONTAINERINSTANCE_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["CONTAINERINSTANCE_RESOURCE_GROUP"] || "demo";
const containerGroupName = "demo1";
const containerGroup = {
confidentialComputeProperties: {
ccePolicy:
"eyJhbGxvd19hbGwiOiB0cnVlLCAiY29udGFpbmVycyI6IHsibGVuZ3RoIjogMCwgImVsZW1lbnRzIjogbnVsbH19",
},
containers: [
{
name: "accdemo",
command: [],
environmentVariables: [],
image: "confiimage",
ports: [{ port: 8000 }],
resources: { requests: { cpu: 1, memoryInGB: 1.5 } },
securityContext: {
capabilities: { add: ["CAP_NET_ADMIN"] },
privileged: false,
},
},
],
imageRegistryCredentials: [],
ipAddress: { type: "Public", ports: [{ port: 8000, protocol: "TCP" }] },
location: "westeurope",
osType: "Linux",
sku: "Confidential",
};
const credential = new DefaultAzureCredential();
const client = new ContainerInstanceManagementClient(credential, subscriptionId);
const result = await client.containerGroups.beginCreateOrUpdateAndWait(
resourceGroupName,
containerGroupName,
containerGroup
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.ContainerInstance.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.ContainerInstance;
// Generated from example definition: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupCreateConfidential.json
// this example is just showing the usage of "ContainerGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "subid";
string resourceGroupName = "demo";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this ContainerGroupResource
ContainerGroupCollection collection = resourceGroupResource.GetContainerGroups();
// invoke the operation
string containerGroupName = "demo1";
ContainerGroupData data = new ContainerGroupData(new AzureLocation("westeurope"), new ContainerInstanceContainer[]
{
new ContainerInstanceContainer("accdemo","confiimage",new ContainerResourceRequirements(new ContainerResourceRequestsContent(1.5,1)))
{
Command =
{
},
Ports =
{
new ContainerPort(8000)
},
EnvironmentVariables =
{
},
SecurityContext = new ContainerSecurityContextDefinition()
{
IsPrivileged = false,
Capabilities = new ContainerSecurityContextCapabilitiesDefinition()
{
Add =
{
"CAP_NET_ADMIN"
},
},
},
}
}, ContainerInstanceOperatingSystemType.Linux)
{
ImageRegistryCredentials =
{
},
IPAddress = new ContainerGroupIPAddress(new ContainerGroupPort[]
{
new ContainerGroupPort(8000)
{
Protocol = ContainerGroupNetworkProtocol.Tcp,
}
}, ContainerGroupIPAddressType.Public),
Sku = ContainerGroupSku.Confidential,
ConfidentialComputeCcePolicy = "eyJhbGxvd19hbGwiOiB0cnVlLCAiY29udGFpbmVycyI6IHsibGVuZ3RoIjogMCwgImVsZW1lbnRzIjogbnVsbH19",
};
ArmOperation<ContainerGroupResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, containerGroupName, data);
ContainerGroupResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
ContainerGroupData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Пример ответа
{
"properties": {
"sku": "Confidential",
"provisioningState": "Succeeded",
"containers": [
{
"name": "accdemo",
"properties": {
"image": "confiimage",
"command": [],
"ports": [
{
"port": 8000
}
],
"environmentVariables": [],
"resources": {
"requests": {
"memoryInGB": 1.5,
"cpu": 1
}
},
"securityContext": {
"privileged": false,
"capabilities": {
"add": [
"CAP_NET_ADMIN"
]
}
}
}
}
],
"ipAddress": {
"ports": [
{
"protocol": "TCP",
"port": 8000
}
],
"type": "Public"
},
"initContainers": [],
"imageRegistryCredentials": [],
"osType": "Linux",
"instanceView": {
"events": [],
"state": "Running"
},
"confidentialComputeProperties": {
"ccePolicy": "eyJhbGxvd19hbGwiOiB0cnVlLCAiY29udGFpbmVycyI6IHsibGVuZ3RoIjogMCwgImVsZW1lbnRzIjogbnVsbH19"
}
},
"id": "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.ContainerInstance/containerGroups/demo1",
"name": "demo1",
"type": "Microsoft.ContainerInstance/containerGroups",
"location": "westeurope"
}
{
"properties": {
"sku": "Confidential",
"provisioningState": "Succeeded",
"containers": [
{
"name": "accdemo",
"properties": {
"image": "confiimage",
"command": [],
"ports": [
{
"port": 8000
}
],
"environmentVariables": [],
"resources": {
"requests": {
"memoryInGB": 1.5,
"cpu": 1
}
},
"securityContext": {
"privileged": false,
"capabilities": {
"add": [
"CAP_NET_ADMIN"
]
}
}
}
}
],
"ipAddress": {
"ports": [
{
"protocol": "TCP",
"port": 8000
}
],
"type": "Public"
},
"initContainers": [],
"imageRegistryCredentials": [],
"osType": "Linux",
"instanceView": {
"events": [],
"state": "Running"
},
"confidentialComputeProperties": {
"ccePolicy": "eyJhbGxvd19hbGwiOiB0cnVlLCAiY29udGFpbmVycyI6IHsibGVuZ3RoIjogMCwgImVsZW1lbnRzIjogbnVsbH19"
}
},
"id": "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.ContainerInstance/containerGroups/demo1",
"name": "demo1",
"type": "Microsoft.ContainerInstance/containerGroups",
"location": "westeurope"
}
ContainerGroupCreateWithExtensions
Образец запроса
PUT https://management.azure.com/subscriptions/subid/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/demo1?api-version=2023-05-01
{
"location": "eastus2",
"properties": {
"containers": [
{
"name": "demo1",
"properties": {
"command": [],
"environmentVariables": [],
"image": "nginx",
"ports": [
{
"port": 80
}
],
"resources": {
"requests": {
"cpu": 1,
"memoryInGB": 1.5
}
}
}
}
],
"imageRegistryCredentials": [],
"ipAddress": {
"ports": [
{
"protocol": "TCP",
"port": 80
}
],
"type": "Private"
},
"osType": "Linux",
"subnetIds": [
{
"id": "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.Network/virtualNetworks/test-rg-vnet/subnets/test-subnet"
}
],
"extensions": [
{
"name": "kube-proxy",
"properties": {
"extensionType": "kube-proxy",
"version": "1.0",
"settings": {
"clusterCidr": "10.240.0.0/16",
"kubeVersion": "v1.9.10"
},
"protectedSettings": {
"kubeConfig": "<kubeconfig encoded string>"
}
}
},
{
"name": "vk-realtime-metrics",
"properties": {
"extensionType": "realtime-metrics",
"version": "1.0"
}
}
]
}
}
import com.azure.core.management.serializer.SerializerFactory;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.resourcemanager.containerinstance.fluent.models.ContainerGroupInner;
import com.azure.resourcemanager.containerinstance.models.Container;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupIpAddressType;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupNetworkProtocol;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupSubnetId;
import com.azure.resourcemanager.containerinstance.models.ContainerPort;
import com.azure.resourcemanager.containerinstance.models.DeploymentExtensionSpec;
import com.azure.resourcemanager.containerinstance.models.IpAddress;
import com.azure.resourcemanager.containerinstance.models.OperatingSystemTypes;
import com.azure.resourcemanager.containerinstance.models.Port;
import com.azure.resourcemanager.containerinstance.models.ResourceRequests;
import com.azure.resourcemanager.containerinstance.models.ResourceRequirements;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for ContainerGroups CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/
* ContainerGroupExtensions.json
*/
/**
* Sample code: ContainerGroupCreateWithExtensions.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void containerGroupCreateWithExtensions(com.azure.resourcemanager.AzureResourceManager azure)
throws IOException {
azure.containerGroups().manager().serviceClient().getContainerGroups().createOrUpdate("demo", "demo1",
new ContainerGroupInner().withLocation("eastus2")
.withContainers(Arrays.asList(new Container().withName("demo1").withImage("nginx")
.withCommand(Arrays.asList()).withPorts(Arrays.asList(new ContainerPort().withPort(80)))
.withEnvironmentVariables(Arrays.asList())
.withResources(new ResourceRequirements()
.withRequests(new ResourceRequests().withMemoryInGB(1.5).withCpu(1.0)))))
.withImageRegistryCredentials(Arrays.asList())
.withIpAddress(new IpAddress()
.withPorts(Arrays.asList(new Port().withProtocol(ContainerGroupNetworkProtocol.TCP).withPort(80)))
.withType(ContainerGroupIpAddressType.PRIVATE))
.withOsType(OperatingSystemTypes.LINUX)
.withSubnetIds(Arrays.asList(new ContainerGroupSubnetId().withId(
"/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.Network/virtualNetworks/test-rg-vnet/subnets/test-subnet")))
.withExtensions(Arrays.asList(
new DeploymentExtensionSpec().withName("kube-proxy").withExtensionType("kube-proxy")
.withVersion("1.0")
.withSettings(SerializerFactory.createDefaultManagementSerializerAdapter().deserialize(
"{\"clusterCidr\":\"10.240.0.0/16\",\"kubeVersion\":\"v1.9.10\"}", Object.class,
SerializerEncoding.JSON))
.withProtectedSettings(SerializerFactory.createDefaultManagementSerializerAdapter().deserialize(
"{\"kubeConfig\":\"<kubeconfig encoded string>\"}", Object.class, SerializerEncoding.JSON)),
new DeploymentExtensionSpec().withName("vk-realtime-metrics").withExtensionType("realtime-metrics")
.withVersion("1.0"))),
com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from azure.identity import DefaultAzureCredential
from azure.mgmt.containerinstance import ContainerInstanceManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-containerinstance
# USAGE
python container_group_extensions.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 = ContainerInstanceManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.container_groups.begin_create_or_update(
resource_group_name="demo",
container_group_name="demo1",
container_group={
"location": "eastus2",
"properties": {
"containers": [
{
"name": "demo1",
"properties": {
"command": [],
"environmentVariables": [],
"image": "nginx",
"ports": [{"port": 80}],
"resources": {"requests": {"cpu": 1, "memoryInGB": 1.5}},
},
}
],
"extensions": [
{
"name": "kube-proxy",
"properties": {
"extensionType": "kube-proxy",
"protectedSettings": {"kubeConfig": "<kubeconfig encoded string>"},
"settings": {"clusterCidr": "10.240.0.0/16", "kubeVersion": "v1.9.10"},
"version": "1.0",
},
},
{
"name": "vk-realtime-metrics",
"properties": {"extensionType": "realtime-metrics", "version": "1.0"},
},
],
"imageRegistryCredentials": [],
"ipAddress": {"ports": [{"port": 80, "protocol": "TCP"}], "type": "Private"},
"osType": "Linux",
"subnetIds": [
{
"id": "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.Network/virtualNetworks/test-rg-vnet/subnets/test-subnet"
}
],
},
},
).result()
print(response)
# x-ms-original-file: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupExtensions.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 armcontainerinstance_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/containerinstance/armcontainerinstance/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e60df62e9e0d88462e6abba81a76d94eab000f0d/specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupExtensions.json
func ExampleContainerGroupsClient_BeginCreateOrUpdate_containerGroupCreateWithExtensions() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcontainerinstance.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewContainerGroupsClient().BeginCreateOrUpdate(ctx, "demo", "demo1", armcontainerinstance.ContainerGroup{
Properties: &armcontainerinstance.ContainerGroupPropertiesProperties{
Containers: []*armcontainerinstance.Container{
{
Name: to.Ptr("demo1"),
Properties: &armcontainerinstance.ContainerProperties{
Command: []*string{},
EnvironmentVariables: []*armcontainerinstance.EnvironmentVariable{},
Image: to.Ptr("nginx"),
Ports: []*armcontainerinstance.ContainerPort{
{
Port: to.Ptr[int32](80),
}},
Resources: &armcontainerinstance.ResourceRequirements{
Requests: &armcontainerinstance.ResourceRequests{
CPU: to.Ptr[float64](1),
MemoryInGB: to.Ptr[float64](1.5),
},
},
},
}},
ImageRegistryCredentials: []*armcontainerinstance.ImageRegistryCredential{},
IPAddress: &armcontainerinstance.IPAddress{
Type: to.Ptr(armcontainerinstance.ContainerGroupIPAddressTypePrivate),
Ports: []*armcontainerinstance.Port{
{
Port: to.Ptr[int32](80),
Protocol: to.Ptr(armcontainerinstance.ContainerGroupNetworkProtocolTCP),
}},
},
OSType: to.Ptr(armcontainerinstance.OperatingSystemTypesLinux),
SubnetIDs: []*armcontainerinstance.ContainerGroupSubnetID{
{
ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.Network/virtualNetworks/test-rg-vnet/subnets/test-subnet"),
}},
Extensions: []*armcontainerinstance.DeploymentExtensionSpec{
{
Name: to.Ptr("kube-proxy"),
Properties: &armcontainerinstance.DeploymentExtensionSpecProperties{
ExtensionType: to.Ptr("kube-proxy"),
ProtectedSettings: map[string]any{
"kubeConfig": "<kubeconfig encoded string>",
},
Settings: map[string]any{
"clusterCidr": "10.240.0.0/16",
"kubeVersion": "v1.9.10",
},
Version: to.Ptr("1.0"),
},
},
{
Name: to.Ptr("vk-realtime-metrics"),
Properties: &armcontainerinstance.DeploymentExtensionSpecProperties{
ExtensionType: to.Ptr("realtime-metrics"),
Version: to.Ptr("1.0"),
},
}},
},
Location: to.Ptr("eastus2"),
}, 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.ContainerGroup = armcontainerinstance.ContainerGroup{
// Properties: &armcontainerinstance.ContainerGroupPropertiesProperties{
// Containers: []*armcontainerinstance.Container{
// {
// Name: to.Ptr("demo1"),
// Properties: &armcontainerinstance.ContainerProperties{
// Command: []*string{
// },
// EnvironmentVariables: []*armcontainerinstance.EnvironmentVariable{
// },
// Image: to.Ptr("nginx"),
// Ports: []*armcontainerinstance.ContainerPort{
// {
// Port: to.Ptr[int32](80),
// }},
// Resources: &armcontainerinstance.ResourceRequirements{
// Requests: &armcontainerinstance.ResourceRequests{
// CPU: to.Ptr[float64](1),
// MemoryInGB: to.Ptr[float64](1.5),
// },
// },
// },
// }},
// ImageRegistryCredentials: []*armcontainerinstance.ImageRegistryCredential{
// },
// InitContainers: []*armcontainerinstance.InitContainerDefinition{
// },
// InstanceView: &armcontainerinstance.ContainerGroupPropertiesInstanceView{
// Events: []*armcontainerinstance.Event{
// },
// State: to.Ptr("Pending"),
// },
// OSType: to.Ptr(armcontainerinstance.OperatingSystemTypesLinux),
// ProvisioningState: to.Ptr("Succeeded"),
// SKU: to.Ptr(armcontainerinstance.ContainerGroupSKUStandard),
// SubnetIDs: []*armcontainerinstance.ContainerGroupSubnetID{
// {
// ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.Network/virtualNetworks/test-rg-vnet/subnets/test-subnet"),
// }},
// Extensions: []*armcontainerinstance.DeploymentExtensionSpec{
// {
// Name: to.Ptr("kube-proxy"),
// Properties: &armcontainerinstance.DeploymentExtensionSpecProperties{
// ExtensionType: to.Ptr("kube-proxy"),
// Settings: map[string]any{
// "clusterCidr": "10.240.0.0/16",
// "kubeVersion": "v1.9.10",
// },
// Version: to.Ptr("1.0"),
// },
// },
// {
// Name: to.Ptr("vk-realtime-metrics"),
// Properties: &armcontainerinstance.DeploymentExtensionSpecProperties{
// ExtensionType: to.Ptr("realtime-metrics"),
// Version: to.Ptr("1.0"),
// },
// }},
// },
// Name: to.Ptr("demo1"),
// Type: to.Ptr("Microsoft.ContainerInstance/containerGroups"),
// ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.ContainerInstance/containerGroups/demo1"),
// Location: to.Ptr("eastus2"),
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ContainerInstanceManagementClient } = require("@azure/arm-containerinstance");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Create or update container groups with specified configurations.
*
* @summary Create or update container groups with specified configurations.
* x-ms-original-file: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupExtensions.json
*/
async function containerGroupCreateWithExtensions() {
const subscriptionId = process.env["CONTAINERINSTANCE_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["CONTAINERINSTANCE_RESOURCE_GROUP"] || "demo";
const containerGroupName = "demo1";
const containerGroup = {
containers: [
{
name: "demo1",
command: [],
environmentVariables: [],
image: "nginx",
ports: [{ port: 80 }],
resources: { requests: { cpu: 1, memoryInGB: 1.5 } },
},
],
imageRegistryCredentials: [],
ipAddress: { type: "Private", ports: [{ port: 80, protocol: "TCP" }] },
location: "eastus2",
osType: "Linux",
subnetIds: [
{
id: "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.Network/virtualNetworks/test-rg-vnet/subnets/test-subnet",
},
],
extensions: [
{
name: "kube-proxy",
extensionType: "kube-proxy",
protectedSettings: { kubeConfig: "<kubeconfig encoded string>" },
settings: { clusterCidr: "10.240.0.0/16", kubeVersion: "v1.9.10" },
version: "1.0",
},
{
name: "vk-realtime-metrics",
extensionType: "realtime-metrics",
version: "1.0",
},
],
};
const credential = new DefaultAzureCredential();
const client = new ContainerInstanceManagementClient(credential, subscriptionId);
const result = await client.containerGroups.beginCreateOrUpdateAndWait(
resourceGroupName,
containerGroupName,
containerGroup
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.ContainerInstance.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.ContainerInstance;
// Generated from example definition: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupExtensions.json
// this example is just showing the usage of "ContainerGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "subid";
string resourceGroupName = "demo";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this ContainerGroupResource
ContainerGroupCollection collection = resourceGroupResource.GetContainerGroups();
// invoke the operation
string containerGroupName = "demo1";
ContainerGroupData data = new ContainerGroupData(new AzureLocation("eastus2"), new ContainerInstanceContainer[]
{
new ContainerInstanceContainer("demo1","nginx",new ContainerResourceRequirements(new ContainerResourceRequestsContent(1.5,1)))
{
Command =
{
},
Ports =
{
new ContainerPort(80)
},
EnvironmentVariables =
{
},
}
}, ContainerInstanceOperatingSystemType.Linux)
{
ImageRegistryCredentials =
{
},
IPAddress = new ContainerGroupIPAddress(new ContainerGroupPort[]
{
new ContainerGroupPort(80)
{
Protocol = ContainerGroupNetworkProtocol.Tcp,
}
}, ContainerGroupIPAddressType.Private),
SubnetIds =
{
new ContainerGroupSubnetId(new ResourceIdentifier("/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.Network/virtualNetworks/test-rg-vnet/subnets/test-subnet"))
},
Extensions =
{
new DeploymentExtensionSpec("kube-proxy")
{
ExtensionType = "kube-proxy",
Version = "1.0",
Settings = BinaryData.FromObjectAsJson(new Dictionary<string, object>()
{
["clusterCidr"] = "10.240.0.0/16",
["kubeVersion"] = "v1.9.10"}),
ProtectedSettings = BinaryData.FromObjectAsJson(new Dictionary<string, object>()
{
["kubeConfig"] = "<kubeconfig encoded string>"}),
},new DeploymentExtensionSpec("vk-realtime-metrics")
{
ExtensionType = "realtime-metrics",
Version = "1.0",
}
},
};
ArmOperation<ContainerGroupResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, containerGroupName, data);
ContainerGroupResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
ContainerGroupData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Пример ответа
{
"properties": {
"sku": "Standard",
"provisioningState": "Pending",
"containers": [
{
"name": "demo1",
"properties": {
"image": "nginx",
"command": [],
"ports": [
{
"port": 80
}
],
"environmentVariables": [],
"resources": {
"requests": {
"memoryInGB": 1.5,
"cpu": 1
}
}
}
}
],
"initContainers": [],
"extensions": [
{
"name": "kube-proxy",
"properties": {
"extensionType": "kube-proxy",
"version": "1.0",
"settings": {
"clusterCidr": "10.240.0.0/16",
"kubeVersion": "v1.9.10"
}
}
},
{
"name": "vk-realtime-metrics",
"properties": {
"extensionType": "realtime-metrics",
"version": "1.0"
}
}
],
"imageRegistryCredentials": [],
"osType": "Linux",
"instanceView": {
"events": [],
"state": "Pending"
},
"subnetIds": [
{
"id": "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.Network/virtualNetworks/test-rg-vnet/subnets/test-subnet"
}
]
},
"id": "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.ContainerInstance/containerGroups/demo1",
"name": "demo1",
"type": "Microsoft.ContainerInstance/containerGroups",
"location": "eastus2"
}
{
"properties": {
"sku": "Standard",
"provisioningState": "Pending",
"containers": [
{
"name": "demo1",
"properties": {
"image": "nginx",
"command": [],
"ports": [
{
"port": 80
}
],
"environmentVariables": [],
"resources": {
"requests": {
"memoryInGB": 1.5,
"cpu": 1
}
}
}
}
],
"initContainers": [],
"extensions": [
{
"name": "kube-proxy",
"properties": {
"extensionType": "kube-proxy",
"version": "1.0",
"settings": {
"clusterCidr": "10.240.0.0/16",
"kubeVersion": "v1.9.10"
}
}
},
{
"name": "vk-realtime-metrics",
"properties": {
"extensionType": "realtime-metrics",
"version": "1.0"
}
}
],
"imageRegistryCredentials": [],
"osType": "Linux",
"instanceView": {
"events": [],
"state": "Running"
},
"subnetIds": [
{
"id": "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.Network/virtualNetworks/test-rg-vnet/subnets/test-subnet"
}
]
},
"id": "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/test-rg/providers/Microsoft.ContainerInstance/containerGroups/demo1",
"name": "demo1",
"type": "Microsoft.ContainerInstance/containerGroups",
"location": "eastus2"
}
ContainerGroupsCreateOrUpdate
Образец запроса
PUT https://management.azure.com/subscriptions/subid/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/demo1?api-version=2023-05-01
{
"location": "west us",
"identity": {
"type": "SystemAssigned, UserAssigned",
"userAssignedIdentities": {
"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity-name": {}
}
},
"properties": {
"containers": [
{
"name": "demo1",
"properties": {
"command": [],
"environmentVariables": [],
"image": "nginx",
"ports": [
{
"port": 80
}
],
"resources": {
"requests": {
"cpu": 1,
"memoryInGB": 1.5,
"gpu": {
"count": 1,
"sku": "K80"
}
}
},
"volumeMounts": [
{
"name": "volume1",
"mountPath": "/mnt/volume1",
"readOnly": false
},
{
"name": "volume2",
"mountPath": "/mnt/volume2",
"readOnly": false
},
{
"name": "volume3",
"mountPath": "/mnt/volume3",
"readOnly": true
}
]
}
}
],
"diagnostics": {
"logAnalytics": {
"workspaceId": "workspaceid",
"workspaceKey": "workspaceKey",
"logType": "ContainerInsights",
"metadata": {
"test-key": "test-metadata-value"
},
"workspaceResourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rg/providers/microsoft.operationalinsights/workspaces/workspace"
}
},
"subnetIds": [
{
"id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', parameters('vnetName'), parameters('subnetName'))]"
}
],
"dnsConfig": {
"nameServers": [
"1.1.1.1"
],
"searchDomains": "cluster.local svc.cluster.local",
"options": "ndots:2"
},
"imageRegistryCredentials": [],
"ipAddress": {
"ports": [
{
"protocol": "TCP",
"port": 80
}
],
"type": "Public",
"dnsNameLabel": "dnsnamelabel1",
"autoGeneratedDomainNameLabelScope": "Unsecure"
},
"osType": "Linux",
"volumes": [
{
"name": "volume1",
"azureFile": {
"shareName": "shareName",
"storageAccountName": "accountName",
"storageAccountKey": "accountKey"
}
},
{
"name": "volume2",
"emptyDir": {}
},
{
"name": "volume3",
"secret": {
"secretKey1": "SecretValue1InBase64",
"secretKey2": "SecretValue2InBase64"
}
}
]
}
}
import com.azure.core.management.serializer.SerializerFactory;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.resourcemanager.containerinstance.fluent.models.ContainerGroupInner;
import com.azure.resourcemanager.containerinstance.models.AzureFileVolume;
import com.azure.resourcemanager.containerinstance.models.Container;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupDiagnostics;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupIdentity;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupIdentityUserAssignedIdentities;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupIpAddressType;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupNetworkProtocol;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupSubnetId;
import com.azure.resourcemanager.containerinstance.models.ContainerPort;
import com.azure.resourcemanager.containerinstance.models.DnsConfiguration;
import com.azure.resourcemanager.containerinstance.models.DnsNameLabelReusePolicy;
import com.azure.resourcemanager.containerinstance.models.GpuResource;
import com.azure.resourcemanager.containerinstance.models.GpuSku;
import com.azure.resourcemanager.containerinstance.models.IpAddress;
import com.azure.resourcemanager.containerinstance.models.LogAnalytics;
import com.azure.resourcemanager.containerinstance.models.LogAnalyticsLogType;
import com.azure.resourcemanager.containerinstance.models.OperatingSystemTypes;
import com.azure.resourcemanager.containerinstance.models.Port;
import com.azure.resourcemanager.containerinstance.models.ResourceIdentityType;
import com.azure.resourcemanager.containerinstance.models.ResourceRequests;
import com.azure.resourcemanager.containerinstance.models.ResourceRequirements;
import com.azure.resourcemanager.containerinstance.models.Volume;
import com.azure.resourcemanager.containerinstance.models.VolumeMount;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for ContainerGroups CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/
* ContainerGroupsCreateOrUpdate.json
*/
/**
* Sample code: ContainerGroupsCreateOrUpdate.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void containerGroupsCreateOrUpdate(com.azure.resourcemanager.AzureResourceManager azure)
throws IOException {
azure.containerGroups().manager().serviceClient().getContainerGroups().createOrUpdate("demo", "demo1",
new ContainerGroupInner().withLocation("west us").withIdentity(new ContainerGroupIdentity()
.withType(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)
.withUserAssignedIdentities(mapOf(
"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity-name",
new ContainerGroupIdentityUserAssignedIdentities())))
.withContainers(Arrays.asList(new Container().withName("demo1").withImage("nginx")
.withCommand(Arrays.asList()).withPorts(Arrays.asList(new ContainerPort().withPort(80)))
.withEnvironmentVariables(Arrays.asList())
.withResources(new ResourceRequirements().withRequests(new ResourceRequests().withMemoryInGB(1.5)
.withCpu(1.0).withGpu(new GpuResource().withCount(1).withSku(GpuSku.K80))))
.withVolumeMounts(Arrays.asList(
new VolumeMount().withName("volume1").withMountPath("/mnt/volume1").withReadOnly(false),
new VolumeMount().withName("volume2").withMountPath("/mnt/volume2").withReadOnly(false),
new VolumeMount().withName("volume3").withMountPath("/mnt/volume3").withReadOnly(true)))))
.withImageRegistryCredentials(Arrays.asList())
.withIpAddress(new IpAddress()
.withPorts(Arrays.asList(new Port().withProtocol(ContainerGroupNetworkProtocol.TCP).withPort(80)))
.withType(ContainerGroupIpAddressType.PUBLIC).withDnsNameLabel("dnsnamelabel1")
.withAutoGeneratedDomainNameLabelScope(DnsNameLabelReusePolicy.UNSECURE))
.withOsType(OperatingSystemTypes.LINUX)
.withVolumes(Arrays.asList(
new Volume().withName("volume1")
.withAzureFile(new AzureFileVolume().withShareName("shareName")
.withStorageAccountName("accountName").withStorageAccountKey("fakeTokenPlaceholder")),
new Volume().withName("volume2")
.withEmptyDir(SerializerFactory.createDefaultManagementSerializerAdapter().deserialize("{}",
Object.class, SerializerEncoding.JSON)),
new Volume().withName("volume3")
.withSecret(mapOf("secretKey1", "fakeTokenPlaceholder", "secretKey2", "fakeTokenPlaceholder"))))
.withDiagnostics(new ContainerGroupDiagnostics().withLogAnalytics(new LogAnalytics()
.withWorkspaceId("workspaceid").withWorkspaceKey("fakeTokenPlaceholder")
.withLogType(LogAnalyticsLogType.CONTAINER_INSIGHTS)
.withMetadata(mapOf("test-key", "fakeTokenPlaceholder")).withWorkspaceResourceId(
"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rg/providers/microsoft.operationalinsights/workspaces/workspace")))
.withSubnetIds(Arrays.asList(new ContainerGroupSubnetId().withId(
"[resourceId('Microsoft.Network/virtualNetworks/subnets', parameters('vnetName'), parameters('subnetName'))]")))
.withDnsConfig(new DnsConfiguration().withNameServers(Arrays.asList("1.1.1.1"))
.withSearchDomains("cluster.local svc.cluster.local").withOptions("ndots:2")),
com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from azure.identity import DefaultAzureCredential
from azure.mgmt.containerinstance import ContainerInstanceManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-containerinstance
# USAGE
python container_groups_create_or_update.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 = ContainerInstanceManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.container_groups.begin_create_or_update(
resource_group_name="demo",
container_group_name="demo1",
container_group={
"identity": {
"type": "SystemAssigned, UserAssigned",
"userAssignedIdentities": {
"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity-name": {}
},
},
"location": "west us",
"properties": {
"containers": [
{
"name": "demo1",
"properties": {
"command": [],
"environmentVariables": [],
"image": "nginx",
"ports": [{"port": 80}],
"resources": {"requests": {"cpu": 1, "gpu": {"count": 1, "sku": "K80"}, "memoryInGB": 1.5}},
"volumeMounts": [
{"mountPath": "/mnt/volume1", "name": "volume1", "readOnly": False},
{"mountPath": "/mnt/volume2", "name": "volume2", "readOnly": False},
{"mountPath": "/mnt/volume3", "name": "volume3", "readOnly": True},
],
},
}
],
"diagnostics": {
"logAnalytics": {
"logType": "ContainerInsights",
"metadata": {"test-key": "test-metadata-value"},
"workspaceId": "workspaceid",
"workspaceKey": "workspaceKey",
"workspaceResourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rg/providers/microsoft.operationalinsights/workspaces/workspace",
}
},
"dnsConfig": {
"nameServers": ["1.1.1.1"],
"options": "ndots:2",
"searchDomains": "cluster.local svc.cluster.local",
},
"imageRegistryCredentials": [],
"ipAddress": {
"autoGeneratedDomainNameLabelScope": "Unsecure",
"dnsNameLabel": "dnsnamelabel1",
"ports": [{"port": 80, "protocol": "TCP"}],
"type": "Public",
},
"osType": "Linux",
"subnetIds": [
{
"id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', parameters('vnetName'), parameters('subnetName'))]"
}
],
"volumes": [
{
"azureFile": {
"shareName": "shareName",
"storageAccountKey": "accountKey",
"storageAccountName": "accountName",
},
"name": "volume1",
},
{"emptyDir": {}, "name": "volume2"},
{
"name": "volume3",
"secret": {"secretKey1": "SecretValue1InBase64", "secretKey2": "SecretValue2InBase64"},
},
],
},
},
).result()
print(response)
# x-ms-original-file: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupsCreateOrUpdate.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 armcontainerinstance_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/containerinstance/armcontainerinstance/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e60df62e9e0d88462e6abba81a76d94eab000f0d/specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupsCreateOrUpdate.json
func ExampleContainerGroupsClient_BeginCreateOrUpdate_containerGroupsCreateOrUpdate() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcontainerinstance.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewContainerGroupsClient().BeginCreateOrUpdate(ctx, "demo", "demo1", armcontainerinstance.ContainerGroup{
Identity: &armcontainerinstance.ContainerGroupIdentity{
Type: to.Ptr(armcontainerinstance.ResourceIdentityTypeSystemAssignedUserAssigned),
UserAssignedIdentities: map[string]*armcontainerinstance.UserAssignedIdentities{
"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity-name": {},
},
},
Properties: &armcontainerinstance.ContainerGroupPropertiesProperties{
Containers: []*armcontainerinstance.Container{
{
Name: to.Ptr("demo1"),
Properties: &armcontainerinstance.ContainerProperties{
Command: []*string{},
EnvironmentVariables: []*armcontainerinstance.EnvironmentVariable{},
Image: to.Ptr("nginx"),
Ports: []*armcontainerinstance.ContainerPort{
{
Port: to.Ptr[int32](80),
}},
Resources: &armcontainerinstance.ResourceRequirements{
Requests: &armcontainerinstance.ResourceRequests{
CPU: to.Ptr[float64](1),
Gpu: &armcontainerinstance.GpuResource{
Count: to.Ptr[int32](1),
SKU: to.Ptr(armcontainerinstance.GpuSKUK80),
},
MemoryInGB: to.Ptr[float64](1.5),
},
},
VolumeMounts: []*armcontainerinstance.VolumeMount{
{
Name: to.Ptr("volume1"),
MountPath: to.Ptr("/mnt/volume1"),
ReadOnly: to.Ptr(false),
},
{
Name: to.Ptr("volume2"),
MountPath: to.Ptr("/mnt/volume2"),
ReadOnly: to.Ptr(false),
},
{
Name: to.Ptr("volume3"),
MountPath: to.Ptr("/mnt/volume3"),
ReadOnly: to.Ptr(true),
}},
},
}},
Diagnostics: &armcontainerinstance.ContainerGroupDiagnostics{
LogAnalytics: &armcontainerinstance.LogAnalytics{
LogType: to.Ptr(armcontainerinstance.LogAnalyticsLogTypeContainerInsights),
Metadata: map[string]*string{
"test-key": to.Ptr("test-metadata-value"),
},
WorkspaceID: to.Ptr("workspaceid"),
WorkspaceKey: to.Ptr("workspaceKey"),
WorkspaceResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rg/providers/microsoft.operationalinsights/workspaces/workspace"),
},
},
DNSConfig: &armcontainerinstance.DNSConfiguration{
NameServers: []*string{
to.Ptr("1.1.1.1")},
Options: to.Ptr("ndots:2"),
SearchDomains: to.Ptr("cluster.local svc.cluster.local"),
},
ImageRegistryCredentials: []*armcontainerinstance.ImageRegistryCredential{},
IPAddress: &armcontainerinstance.IPAddress{
Type: to.Ptr(armcontainerinstance.ContainerGroupIPAddressTypePublic),
AutoGeneratedDomainNameLabelScope: to.Ptr(armcontainerinstance.DNSNameLabelReusePolicyUnsecure),
DNSNameLabel: to.Ptr("dnsnamelabel1"),
Ports: []*armcontainerinstance.Port{
{
Port: to.Ptr[int32](80),
Protocol: to.Ptr(armcontainerinstance.ContainerGroupNetworkProtocolTCP),
}},
},
OSType: to.Ptr(armcontainerinstance.OperatingSystemTypesLinux),
SubnetIDs: []*armcontainerinstance.ContainerGroupSubnetID{
{
ID: to.Ptr("[resourceId('Microsoft.Network/virtualNetworks/subnets', parameters('vnetName'), parameters('subnetName'))]"),
}},
Volumes: []*armcontainerinstance.Volume{
{
Name: to.Ptr("volume1"),
AzureFile: &armcontainerinstance.AzureFileVolume{
ShareName: to.Ptr("shareName"),
StorageAccountKey: to.Ptr("accountKey"),
StorageAccountName: to.Ptr("accountName"),
},
},
{
Name: to.Ptr("volume2"),
EmptyDir: map[string]any{},
},
{
Name: to.Ptr("volume3"),
Secret: map[string]*string{
"secretKey1": to.Ptr("SecretValue1InBase64"),
"secretKey2": to.Ptr("SecretValue2InBase64"),
},
}},
},
Location: to.Ptr("west us"),
}, 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.ContainerGroup = armcontainerinstance.ContainerGroup{
// Properties: &armcontainerinstance.ContainerGroupPropertiesProperties{
// Containers: []*armcontainerinstance.Container{
// {
// Name: to.Ptr("demo1"),
// Properties: &armcontainerinstance.ContainerProperties{
// Command: []*string{
// },
// EnvironmentVariables: []*armcontainerinstance.EnvironmentVariable{
// },
// Image: to.Ptr("nginx"),
// Ports: []*armcontainerinstance.ContainerPort{
// {
// Port: to.Ptr[int32](80),
// }},
// Resources: &armcontainerinstance.ResourceRequirements{
// Requests: &armcontainerinstance.ResourceRequests{
// CPU: to.Ptr[float64](1),
// Gpu: &armcontainerinstance.GpuResource{
// Count: to.Ptr[int32](1),
// SKU: to.Ptr(armcontainerinstance.GpuSKUK80),
// },
// MemoryInGB: to.Ptr[float64](1.5),
// },
// },
// VolumeMounts: []*armcontainerinstance.VolumeMount{
// {
// Name: to.Ptr("volume1"),
// MountPath: to.Ptr("/mnt/volume1"),
// ReadOnly: to.Ptr(false),
// },
// {
// Name: to.Ptr("volume2"),
// MountPath: to.Ptr("/mnt/volume2"),
// ReadOnly: to.Ptr(false),
// },
// {
// Name: to.Ptr("volume3"),
// MountPath: to.Ptr("/mnt/volume3"),
// ReadOnly: to.Ptr(true),
// }},
// },
// }},
// Diagnostics: &armcontainerinstance.ContainerGroupDiagnostics{
// LogAnalytics: &armcontainerinstance.LogAnalytics{
// WorkspaceID: to.Ptr("workspaceid"),
// },
// },
// DNSConfig: &armcontainerinstance.DNSConfiguration{
// NameServers: []*string{
// to.Ptr("1.1.1.1")},
// Options: to.Ptr("ndots:2"),
// SearchDomains: to.Ptr("cluster.local svc.cluster.local"),
// },
// ImageRegistryCredentials: []*armcontainerinstance.ImageRegistryCredential{
// },
// IPAddress: &armcontainerinstance.IPAddress{
// Type: to.Ptr(armcontainerinstance.ContainerGroupIPAddressTypePublic),
// AutoGeneratedDomainNameLabelScope: to.Ptr(armcontainerinstance.DNSNameLabelReusePolicyUnsecure),
// DNSNameLabel: to.Ptr("dnsnamelabel1"),
// Fqdn: to.Ptr("dnsnamelabel1.azure-container.io"),
// IP: to.Ptr("10.0.0.1"),
// Ports: []*armcontainerinstance.Port{
// {
// Port: to.Ptr[int32](80),
// Protocol: to.Ptr(armcontainerinstance.ContainerGroupNetworkProtocolTCP),
// }},
// },
// OSType: to.Ptr(armcontainerinstance.OperatingSystemTypesLinux),
// ProvisioningState: to.Ptr("Succeeded"),
// Volumes: []*armcontainerinstance.Volume{
// {
// Name: to.Ptr("volume1"),
// AzureFile: &armcontainerinstance.AzureFileVolume{
// ShareName: to.Ptr("shareName"),
// StorageAccountName: to.Ptr("accountName"),
// },
// },
// {
// Name: to.Ptr("volume2"),
// EmptyDir: map[string]any{
// },
// },
// {
// Name: to.Ptr("volume3"),
// Secret: map[string]*string{
// },
// }},
// },
// Name: to.Ptr("demo1"),
// Type: to.Ptr("Microsoft.ContainerInstance/containerGroups"),
// ID: to.Ptr("/subscriptions/subid/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/demo1"),
// Location: to.Ptr("WestUs"),
// Zones: []*string{
// to.Ptr("1")},
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ContainerInstanceManagementClient } = require("@azure/arm-containerinstance");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Create or update container groups with specified configurations.
*
* @summary Create or update container groups with specified configurations.
* x-ms-original-file: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupsCreateOrUpdate.json
*/
async function containerGroupsCreateOrUpdate() {
const subscriptionId = process.env["CONTAINERINSTANCE_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["CONTAINERINSTANCE_RESOURCE_GROUP"] || "demo";
const containerGroupName = "demo1";
const containerGroup = {
containers: [
{
name: "demo1",
command: [],
environmentVariables: [],
image: "nginx",
ports: [{ port: 80 }],
resources: {
requests: { cpu: 1, gpu: { count: 1, sku: "K80" }, memoryInGB: 1.5 },
},
volumeMounts: [
{ name: "volume1", mountPath: "/mnt/volume1", readOnly: false },
{ name: "volume2", mountPath: "/mnt/volume2", readOnly: false },
{ name: "volume3", mountPath: "/mnt/volume3", readOnly: true },
],
},
],
diagnostics: {
logAnalytics: {
logType: "ContainerInsights",
metadata: { testKey: "test-metadata-value" },
workspaceId: "workspaceid",
workspaceKey: "workspaceKey",
workspaceResourceId:
"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rg/providers/microsoft.operationalinsights/workspaces/workspace",
},
},
dnsConfig: {
nameServers: ["1.1.1.1"],
options: "ndots:2",
searchDomains: "cluster.local svc.cluster.local",
},
identity: {
type: "SystemAssigned, UserAssigned",
userAssignedIdentities: {
"/subscriptions/00000000000000000000000000000000/resourceGroups/myResourceGroup/providers/MicrosoftManagedIdentity/userAssignedIdentities/identityName":
{},
},
},
imageRegistryCredentials: [],
ipAddress: {
type: "Public",
autoGeneratedDomainNameLabelScope: "Unsecure",
dnsNameLabel: "dnsnamelabel1",
ports: [{ port: 80, protocol: "TCP" }],
},
location: "west us",
osType: "Linux",
subnetIds: [
{
id: "[resourceId('Microsoft.Network/virtualNetworks/subnets', parameters('vnetName'), parameters('subnetName'))]",
},
],
volumes: [
{
name: "volume1",
azureFile: {
shareName: "shareName",
storageAccountKey: "accountKey",
storageAccountName: "accountName",
},
},
{ name: "volume2", emptyDir: {} },
{
name: "volume3",
secret: {
secretKey1: "SecretValue1InBase64",
secretKey2: "SecretValue2InBase64",
},
},
],
};
const credential = new DefaultAzureCredential();
const client = new ContainerInstanceManagementClient(credential, subscriptionId);
const result = await client.containerGroups.beginCreateOrUpdateAndWait(
resourceGroupName,
containerGroupName,
containerGroup
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.ContainerInstance.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.ContainerInstance;
// Generated from example definition: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupsCreateOrUpdate.json
// this example is just showing the usage of "ContainerGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "subid";
string resourceGroupName = "demo";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this ContainerGroupResource
ContainerGroupCollection collection = resourceGroupResource.GetContainerGroups();
// invoke the operation
string containerGroupName = "demo1";
ContainerGroupData data = new ContainerGroupData(new AzureLocation("west us"), new ContainerInstanceContainer[]
{
new ContainerInstanceContainer("demo1","nginx",new ContainerResourceRequirements(new ContainerResourceRequestsContent(1.5,1)
{
Gpu = new ContainerGpuResourceInfo(1,ContainerGpuSku.K80),
}))
{
Command =
{
},
Ports =
{
new ContainerPort(80)
},
EnvironmentVariables =
{
},
VolumeMounts =
{
new ContainerVolumeMount("volume1","/mnt/volume1")
{
IsReadOnly = false,
},new ContainerVolumeMount("volume2","/mnt/volume2")
{
IsReadOnly = false,
},new ContainerVolumeMount("volume3","/mnt/volume3")
{
IsReadOnly = true,
}
},
}
}, ContainerInstanceOperatingSystemType.Linux)
{
Identity = new ManagedServiceIdentity("SystemAssigned, UserAssigned")
{
UserAssignedIdentities =
{
[new ResourceIdentifier("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity-name")] = new UserAssignedIdentity(),
},
},
ImageRegistryCredentials =
{
},
IPAddress = new ContainerGroupIPAddress(new ContainerGroupPort[]
{
new ContainerGroupPort(80)
{
Protocol = ContainerGroupNetworkProtocol.Tcp,
}
}, ContainerGroupIPAddressType.Public)
{
DnsNameLabel = "dnsnamelabel1",
AutoGeneratedDomainNameLabelScope = DnsNameLabelReusePolicy.Unsecure,
},
Volumes =
{
new ContainerVolume("volume1")
{
AzureFile = new ContainerInstanceAzureFileVolume("shareName","accountName")
{
StorageAccountKey = "accountKey",
},
},new ContainerVolume("volume2")
{
EmptyDir = BinaryData.FromObjectAsJson(new Dictionary<string, object>()
{
}),
},new ContainerVolume("volume3")
{
Secret =
{
["secretKey1"] = "SecretValue1InBase64",
["secretKey2"] = "SecretValue2InBase64",
},
}
},
DiagnosticsLogAnalytics = new ContainerGroupLogAnalytics("workspaceid", "workspaceKey")
{
LogType = ContainerGroupLogAnalyticsLogType.ContainerInsights,
Metadata =
{
["test-key"] = "test-metadata-value",
},
WorkspaceResourceId = new ResourceIdentifier("/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rg/providers/microsoft.operationalinsights/workspaces/workspace"),
},
SubnetIds =
{
new ContainerGroupSubnetId(new ResourceIdentifier("[resourceId('Microsoft.Network/virtualNetworks/subnets', parameters('vnetName'), parameters('subnetName'))]"))
},
DnsConfig = new ContainerGroupDnsConfiguration(new string[]
{
"1.1.1.1"
})
{
SearchDomains = "cluster.local svc.cluster.local",
Options = "ndots:2",
},
};
ArmOperation<ContainerGroupResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, containerGroupName, data);
ContainerGroupResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
ContainerGroupData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Пример ответа
{
"id": "/subscriptions/subid/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/demo1",
"location": "WestUs",
"zones": [
"1"
],
"name": "demo1",
"properties": {
"containers": [
{
"name": "demo1",
"properties": {
"command": [],
"environmentVariables": [],
"image": "nginx",
"ports": [
{
"port": 80
}
],
"resources": {
"requests": {
"cpu": 1,
"memoryInGB": 1.5,
"gpu": {
"count": 1,
"sku": "K80"
}
}
},
"volumeMounts": [
{
"name": "volume1",
"mountPath": "/mnt/volume1",
"readOnly": false
},
{
"name": "volume2",
"mountPath": "/mnt/volume2",
"readOnly": false
},
{
"name": "volume3",
"mountPath": "/mnt/volume3",
"readOnly": true
}
]
}
}
],
"diagnostics": {
"logAnalytics": {
"workspaceId": "workspaceid"
}
},
"dnsConfig": {
"nameServers": [
"1.1.1.1"
],
"searchDomains": "cluster.local svc.cluster.local",
"options": "ndots:2"
},
"imageRegistryCredentials": [],
"ipAddress": {
"ip": "10.0.0.1",
"ports": [
{
"port": 80,
"protocol": "TCP"
}
],
"type": "Public",
"dnsNameLabel": "dnsnamelabel1",
"autoGeneratedDomainNameLabelScope": "Unsecure",
"fqdn": "dnsnamelabel1.azure-container.io"
},
"osType": "Linux",
"provisioningState": "Succeeded",
"volumes": [
{
"name": "volume1",
"azureFile": {
"shareName": "shareName",
"storageAccountName": "accountName"
}
},
{
"name": "volume2",
"emptyDir": {}
},
{
"name": "volume3",
"secret": {}
}
]
},
"type": "Microsoft.ContainerInstance/containerGroups"
}
{
"id": "/subscriptions/subid/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/demo1",
"location": "WestUs",
"zones": [
"1"
],
"name": "demo1",
"properties": {
"containers": [
{
"name": "demo1",
"properties": {
"command": [],
"environmentVariables": [],
"image": "nginx",
"ports": [
{
"port": 80
}
],
"resources": {
"requests": {
"cpu": 1,
"memoryInGB": 1.5,
"gpu": {
"count": 1,
"sku": "K80"
}
}
},
"volumeMounts": [
{
"name": "volume1",
"mountPath": "/mnt/volume1",
"readOnly": false
},
{
"name": "volume2",
"mountPath": "/mnt/volume2",
"readOnly": false
},
{
"name": "volume3",
"mountPath": "/mnt/volume3",
"readOnly": true
}
]
}
}
],
"dnsConfig": {
"nameServers": [
"1.1.1.1"
]
},
"imageRegistryCredentials": [],
"ipAddress": {
"ip": "10.0.0.1",
"ports": [
{
"port": 80,
"protocol": "TCP"
}
],
"type": "Public",
"dnsNameLabel": "dnsnamelabel1",
"autoGeneratedDomainNameLabelScope": "Unsecure",
"fqdn": "dnsnamelabel1.azure-container.io"
},
"osType": "Linux",
"provisioningState": "Succeeded",
"volumes": [
{
"name": "volume1",
"azureFile": {
"shareName": "shareName",
"storageAccountName": "accountName"
}
},
{
"name": "volume2",
"emptyDir": {}
},
{
"name": "volume3",
"secret": {}
}
]
},
"type": "Microsoft.ContainerInstance/containerGroups"
}
ContainerGroupsCreateWithPriority
Образец запроса
PUT https://management.azure.com/subscriptions/subid/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/demo1?api-version=2023-05-01
{
"properties": {
"sku": "Standard",
"containers": [
{
"name": "test-container-001",
"properties": {
"image": "alpine:latest",
"command": [
"/bin/sh",
"-c",
"sleep 10"
],
"resources": {
"requests": {
"memoryInGB": 1,
"cpu": 1
}
}
}
}
],
"restartPolicy": "Never",
"osType": "Linux",
"priority": "Spot"
},
"location": "eastus"
}
import com.azure.resourcemanager.containerinstance.fluent.models.ContainerGroupInner;
import com.azure.resourcemanager.containerinstance.models.Container;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupPriority;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupRestartPolicy;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupSku;
import com.azure.resourcemanager.containerinstance.models.OperatingSystemTypes;
import com.azure.resourcemanager.containerinstance.models.ResourceRequests;
import com.azure.resourcemanager.containerinstance.models.ResourceRequirements;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for ContainerGroups CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/
* ContainerGroupsCreatePriority.json
*/
/**
* Sample code: ContainerGroupsCreateWithPriority.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void containerGroupsCreateWithPriority(com.azure.resourcemanager.AzureResourceManager azure) {
azure.containerGroups().manager().serviceClient().getContainerGroups().createOrUpdate("demo", "demo1",
new ContainerGroupInner().withLocation("eastus")
.withContainers(Arrays.asList(new Container().withName("test-container-001").withImage("alpine:latest")
.withCommand(Arrays.asList("/bin/sh", "-c", "sleep 10"))
.withResources(new ResourceRequirements()
.withRequests(new ResourceRequests().withMemoryInGB(1.0).withCpu(1.0)))))
.withRestartPolicy(ContainerGroupRestartPolicy.NEVER).withOsType(OperatingSystemTypes.LINUX)
.withSku(ContainerGroupSku.STANDARD).withPriority(ContainerGroupPriority.SPOT),
com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from azure.identity import DefaultAzureCredential
from azure.mgmt.containerinstance import ContainerInstanceManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-containerinstance
# USAGE
python container_groups_create_priority.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 = ContainerInstanceManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.container_groups.begin_create_or_update(
resource_group_name="demo",
container_group_name="demo1",
container_group={
"location": "eastus",
"properties": {
"containers": [
{
"name": "test-container-001",
"properties": {
"command": ["/bin/sh", "-c", "sleep 10"],
"image": "alpine:latest",
"resources": {"requests": {"cpu": 1, "memoryInGB": 1}},
},
}
],
"osType": "Linux",
"priority": "Spot",
"restartPolicy": "Never",
"sku": "Standard",
},
},
).result()
print(response)
# x-ms-original-file: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupsCreatePriority.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 armcontainerinstance_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/containerinstance/armcontainerinstance/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e60df62e9e0d88462e6abba81a76d94eab000f0d/specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupsCreatePriority.json
func ExampleContainerGroupsClient_BeginCreateOrUpdate_containerGroupsCreateWithPriority() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcontainerinstance.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewContainerGroupsClient().BeginCreateOrUpdate(ctx, "demo", "demo1", armcontainerinstance.ContainerGroup{
Properties: &armcontainerinstance.ContainerGroupPropertiesProperties{
Containers: []*armcontainerinstance.Container{
{
Name: to.Ptr("test-container-001"),
Properties: &armcontainerinstance.ContainerProperties{
Command: []*string{
to.Ptr("/bin/sh"),
to.Ptr("-c"),
to.Ptr("sleep 10")},
Image: to.Ptr("alpine:latest"),
Resources: &armcontainerinstance.ResourceRequirements{
Requests: &armcontainerinstance.ResourceRequests{
CPU: to.Ptr[float64](1),
MemoryInGB: to.Ptr[float64](1),
},
},
},
}},
OSType: to.Ptr(armcontainerinstance.OperatingSystemTypesLinux),
Priority: to.Ptr(armcontainerinstance.ContainerGroupPrioritySpot),
RestartPolicy: to.Ptr(armcontainerinstance.ContainerGroupRestartPolicyNever),
SKU: to.Ptr(armcontainerinstance.ContainerGroupSKUStandard),
},
Location: to.Ptr("eastus"),
}, 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.ContainerGroup = armcontainerinstance.ContainerGroup{
// Properties: &armcontainerinstance.ContainerGroupPropertiesProperties{
// Containers: []*armcontainerinstance.Container{
// {
// Name: to.Ptr("test-container-001"),
// Properties: &armcontainerinstance.ContainerProperties{
// Command: []*string{
// to.Ptr("/bin/sh"),
// to.Ptr("-c"),
// to.Ptr("sleep 10")},
// EnvironmentVariables: []*armcontainerinstance.EnvironmentVariable{
// },
// Image: to.Ptr("alpine:latest"),
// Ports: []*armcontainerinstance.ContainerPort{
// },
// Resources: &armcontainerinstance.ResourceRequirements{
// Requests: &armcontainerinstance.ResourceRequests{
// CPU: to.Ptr[float64](1),
// MemoryInGB: to.Ptr[float64](1),
// },
// },
// },
// }},
// InitContainers: []*armcontainerinstance.InitContainerDefinition{
// },
// InstanceView: &armcontainerinstance.ContainerGroupPropertiesInstanceView{
// Events: []*armcontainerinstance.Event{
// },
// State: to.Ptr("Succeeded"),
// },
// OSType: to.Ptr(armcontainerinstance.OperatingSystemTypesLinux),
// Priority: to.Ptr(armcontainerinstance.ContainerGroupPrioritySpot),
// ProvisioningState: to.Ptr("Succeeded"),
// RestartPolicy: to.Ptr(armcontainerinstance.ContainerGroupRestartPolicyNever),
// SKU: to.Ptr(armcontainerinstance.ContainerGroupSKUStandard),
// },
// Name: to.Ptr("demo1"),
// Type: to.Ptr("Microsoft.ContainerInstance/containerGroups"),
// ID: to.Ptr("/subscriptions/subId/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/demo1"),
// Location: to.Ptr("eastus"),
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ContainerInstanceManagementClient } = require("@azure/arm-containerinstance");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Create or update container groups with specified configurations.
*
* @summary Create or update container groups with specified configurations.
* x-ms-original-file: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupsCreatePriority.json
*/
async function containerGroupsCreateWithPriority() {
const subscriptionId = process.env["CONTAINERINSTANCE_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["CONTAINERINSTANCE_RESOURCE_GROUP"] || "demo";
const containerGroupName = "demo1";
const containerGroup = {
containers: [
{
name: "test-container-001",
command: ["/bin/sh", "-c", "sleep 10"],
image: "alpine:latest",
resources: { requests: { cpu: 1, memoryInGB: 1 } },
},
],
location: "eastus",
osType: "Linux",
priority: "Spot",
restartPolicy: "Never",
sku: "Standard",
};
const credential = new DefaultAzureCredential();
const client = new ContainerInstanceManagementClient(credential, subscriptionId);
const result = await client.containerGroups.beginCreateOrUpdateAndWait(
resourceGroupName,
containerGroupName,
containerGroup
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.ContainerInstance.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.ContainerInstance;
// Generated from example definition: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupsCreatePriority.json
// this example is just showing the usage of "ContainerGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "subid";
string resourceGroupName = "demo";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this ContainerGroupResource
ContainerGroupCollection collection = resourceGroupResource.GetContainerGroups();
// invoke the operation
string containerGroupName = "demo1";
ContainerGroupData data = new ContainerGroupData(new AzureLocation("eastus"), new ContainerInstanceContainer[]
{
new ContainerInstanceContainer("test-container-001","alpine:latest",new ContainerResourceRequirements(new ContainerResourceRequestsContent(1,1)))
{
Command =
{
"/bin/sh","-c","sleep 10"
},
}
}, ContainerInstanceOperatingSystemType.Linux)
{
RestartPolicy = ContainerGroupRestartPolicy.Never,
Sku = ContainerGroupSku.Standard,
Priority = ContainerGroupPriority.Spot,
};
ArmOperation<ContainerGroupResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, containerGroupName, data);
ContainerGroupResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
ContainerGroupData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Пример ответа
{
"properties": {
"sku": "Standard",
"provisioningState": "Succeeded",
"containers": [
{
"name": "test-container-001",
"properties": {
"image": "alpine:latest",
"command": [
"/bin/sh",
"-c",
"sleep 10"
],
"ports": [],
"environmentVariables": [],
"resources": {
"requests": {
"memoryInGB": 1,
"cpu": 1
}
}
}
}
],
"initContainers": [],
"restartPolicy": "Never",
"osType": "Linux",
"instanceView": {
"events": [],
"state": "Succeeded"
},
"priority": "Spot"
},
"id": "/subscriptions/subId/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/demo1",
"name": "demo1",
"type": "Microsoft.ContainerInstance/containerGroups",
"location": "eastus"
}
{
"properties": {
"sku": "Standard",
"provisioningState": "Created",
"containers": [
{
"name": "test-container-001",
"properties": {
"image": "alpine:latest",
"command": [
"/bin/sh",
"-c",
"sleep 10"
],
"ports": [],
"environmentVariables": [],
"resources": {
"requests": {
"memoryInGB": 1,
"cpu": 1
}
}
}
}
],
"initContainers": [],
"restartPolicy": "Never",
"osType": "Linux",
"instanceView": {
"events": [],
"state": "Created"
},
"priority": "Spot"
},
"id": "/subscriptions/subId/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/demo1",
"name": "demo1",
"type": "Microsoft.ContainerInstance/containerGroups",
"location": "eastus"
}
ContainerGroupWithEncryptionProperties
Образец запроса
PUT https://management.azure.com/subscriptions/subid/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/demo1?api-version=2023-05-01
{
"location": "eastus2",
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity": {}
}
},
"properties": {
"containers": [
{
"name": "demo1",
"properties": {
"command": [],
"environmentVariables": [],
"image": "nginx",
"ports": [
{
"port": 80
}
],
"resources": {
"requests": {
"cpu": 1,
"memoryInGB": 1.5
}
}
}
}
],
"imageRegistryCredentials": [],
"ipAddress": {
"ports": [
{
"protocol": "TCP",
"port": 80
}
],
"type": "Public"
},
"osType": "Linux",
"encryptionProperties": {
"vaultBaseUrl": "https://testkeyvault.vault.azure.net",
"keyName": "test-key",
"keyVersion": "<key version>",
"identity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity"
}
}
}
import com.azure.resourcemanager.containerinstance.fluent.models.ContainerGroupInner;
import com.azure.resourcemanager.containerinstance.models.Container;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupIdentity;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupIdentityUserAssignedIdentities;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupIpAddressType;
import com.azure.resourcemanager.containerinstance.models.ContainerGroupNetworkProtocol;
import com.azure.resourcemanager.containerinstance.models.ContainerPort;
import com.azure.resourcemanager.containerinstance.models.EncryptionProperties;
import com.azure.resourcemanager.containerinstance.models.IpAddress;
import com.azure.resourcemanager.containerinstance.models.OperatingSystemTypes;
import com.azure.resourcemanager.containerinstance.models.Port;
import com.azure.resourcemanager.containerinstance.models.ResourceIdentityType;
import com.azure.resourcemanager.containerinstance.models.ResourceRequests;
import com.azure.resourcemanager.containerinstance.models.ResourceRequirements;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for ContainerGroups CreateOrUpdate.
*/
public final class Main {
/*
* x-ms-original-file:
* specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/
* ContainerGroupEncryptionProperties.json
*/
/**
* Sample code: ContainerGroupWithEncryptionProperties.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void containerGroupWithEncryptionProperties(com.azure.resourcemanager.AzureResourceManager azure) {
azure.containerGroups().manager().serviceClient().getContainerGroups().createOrUpdate("demo", "demo1",
new ContainerGroupInner().withLocation("eastus2").withIdentity(new ContainerGroupIdentity()
.withType(ResourceIdentityType.USER_ASSIGNED)
.withUserAssignedIdentities(mapOf(
"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity",
new ContainerGroupIdentityUserAssignedIdentities())))
.withContainers(Arrays.asList(new Container().withName("demo1").withImage("nginx")
.withCommand(Arrays.asList()).withPorts(Arrays.asList(new ContainerPort().withPort(80)))
.withEnvironmentVariables(Arrays.asList())
.withResources(new ResourceRequirements()
.withRequests(new ResourceRequests().withMemoryInGB(1.5).withCpu(1.0)))))
.withImageRegistryCredentials(Arrays.asList())
.withIpAddress(new IpAddress()
.withPorts(Arrays.asList(new Port().withProtocol(ContainerGroupNetworkProtocol.TCP).withPort(80)))
.withType(ContainerGroupIpAddressType.PUBLIC))
.withOsType(OperatingSystemTypes.LINUX)
.withEncryptionProperties(new EncryptionProperties()
.withVaultBaseUrl("https://testkeyvault.vault.azure.net").withKeyName("fakeTokenPlaceholder")
.withKeyVersion("fakeTokenPlaceholder").withIdentity(
"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity")),
com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
from azure.identity import DefaultAzureCredential
from azure.mgmt.containerinstance import ContainerInstanceManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-containerinstance
# USAGE
python container_group_encryption_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 = ContainerInstanceManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.container_groups.begin_create_or_update(
resource_group_name="demo",
container_group_name="demo1",
container_group={
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity": {}
},
},
"location": "eastus2",
"properties": {
"containers": [
{
"name": "demo1",
"properties": {
"command": [],
"environmentVariables": [],
"image": "nginx",
"ports": [{"port": 80}],
"resources": {"requests": {"cpu": 1, "memoryInGB": 1.5}},
},
}
],
"encryptionProperties": {
"identity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity",
"keyName": "test-key",
"keyVersion": "<key version>",
"vaultBaseUrl": "https://testkeyvault.vault.azure.net",
},
"imageRegistryCredentials": [],
"ipAddress": {"ports": [{"port": 80, "protocol": "TCP"}], "type": "Public"},
"osType": "Linux",
},
},
).result()
print(response)
# x-ms-original-file: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupEncryptionProperties.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 armcontainerinstance_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/containerinstance/armcontainerinstance/v2"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e60df62e9e0d88462e6abba81a76d94eab000f0d/specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupEncryptionProperties.json
func ExampleContainerGroupsClient_BeginCreateOrUpdate_containerGroupWithEncryptionProperties() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armcontainerinstance.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := clientFactory.NewContainerGroupsClient().BeginCreateOrUpdate(ctx, "demo", "demo1", armcontainerinstance.ContainerGroup{
Identity: &armcontainerinstance.ContainerGroupIdentity{
Type: to.Ptr(armcontainerinstance.ResourceIdentityTypeUserAssigned),
UserAssignedIdentities: map[string]*armcontainerinstance.UserAssignedIdentities{
"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity": {},
},
},
Properties: &armcontainerinstance.ContainerGroupPropertiesProperties{
Containers: []*armcontainerinstance.Container{
{
Name: to.Ptr("demo1"),
Properties: &armcontainerinstance.ContainerProperties{
Command: []*string{},
EnvironmentVariables: []*armcontainerinstance.EnvironmentVariable{},
Image: to.Ptr("nginx"),
Ports: []*armcontainerinstance.ContainerPort{
{
Port: to.Ptr[int32](80),
}},
Resources: &armcontainerinstance.ResourceRequirements{
Requests: &armcontainerinstance.ResourceRequests{
CPU: to.Ptr[float64](1),
MemoryInGB: to.Ptr[float64](1.5),
},
},
},
}},
EncryptionProperties: &armcontainerinstance.EncryptionProperties{
Identity: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity"),
KeyName: to.Ptr("test-key"),
KeyVersion: to.Ptr("<key version>"),
VaultBaseURL: to.Ptr("https://testkeyvault.vault.azure.net"),
},
ImageRegistryCredentials: []*armcontainerinstance.ImageRegistryCredential{},
IPAddress: &armcontainerinstance.IPAddress{
Type: to.Ptr(armcontainerinstance.ContainerGroupIPAddressTypePublic),
Ports: []*armcontainerinstance.Port{
{
Port: to.Ptr[int32](80),
Protocol: to.Ptr(armcontainerinstance.ContainerGroupNetworkProtocolTCP),
}},
},
OSType: to.Ptr(armcontainerinstance.OperatingSystemTypesLinux),
},
Location: to.Ptr("eastus2"),
}, 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.ContainerGroup = armcontainerinstance.ContainerGroup{
// Identity: &armcontainerinstance.ContainerGroupIdentity{
// Type: to.Ptr(armcontainerinstance.ResourceIdentityTypeUserAssigned),
// TenantID: to.Ptr("<tenant id>"),
// UserAssignedIdentities: map[string]*armcontainerinstance.UserAssignedIdentities{
// "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity": &armcontainerinstance.UserAssignedIdentities{
// ClientID: to.Ptr("<client id>"),
// PrincipalID: to.Ptr("<principal id>"),
// },
// },
// },
// Properties: &armcontainerinstance.ContainerGroupPropertiesProperties{
// Containers: []*armcontainerinstance.Container{
// {
// Name: to.Ptr("demo1"),
// Properties: &armcontainerinstance.ContainerProperties{
// Command: []*string{
// },
// EnvironmentVariables: []*armcontainerinstance.EnvironmentVariable{
// },
// Image: to.Ptr("nginx"),
// Ports: []*armcontainerinstance.ContainerPort{
// {
// Port: to.Ptr[int32](80),
// }},
// Resources: &armcontainerinstance.ResourceRequirements{
// Requests: &armcontainerinstance.ResourceRequests{
// CPU: to.Ptr[float64](1),
// MemoryInGB: to.Ptr[float64](1.5),
// },
// },
// },
// }},
// EncryptionProperties: &armcontainerinstance.EncryptionProperties{
// Identity: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity"),
// KeyName: to.Ptr("test-key"),
// KeyVersion: to.Ptr("<key version>"),
// VaultBaseURL: to.Ptr("https://testkeyvault.vault.azure.net/"),
// },
// ImageRegistryCredentials: []*armcontainerinstance.ImageRegistryCredential{
// },
// InitContainers: []*armcontainerinstance.InitContainerDefinition{
// },
// InstanceView: &armcontainerinstance.ContainerGroupPropertiesInstanceView{
// Events: []*armcontainerinstance.Event{
// },
// State: to.Ptr("Pending"),
// },
// IPAddress: &armcontainerinstance.IPAddress{
// Type: to.Ptr(armcontainerinstance.ContainerGroupIPAddressTypePublic),
// Ports: []*armcontainerinstance.Port{
// {
// Port: to.Ptr[int32](80),
// Protocol: to.Ptr(armcontainerinstance.ContainerGroupNetworkProtocolTCP),
// }},
// },
// OSType: to.Ptr(armcontainerinstance.OperatingSystemTypesLinux),
// ProvisioningState: to.Ptr("Succeeded"),
// SKU: to.Ptr(armcontainerinstance.ContainerGroupSKUStandard),
// },
// Name: to.Ptr("demo1"),
// Type: to.Ptr("Microsoft.ContainerInstance/containerGroups"),
// ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ContainerInstance/containerGroups/demo1"),
// Location: to.Ptr("eastus2"),
// }
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { ContainerInstanceManagementClient } = require("@azure/arm-containerinstance");
const { DefaultAzureCredential } = require("@azure/identity");
/**
* This sample demonstrates how to Create or update container groups with specified configurations.
*
* @summary Create or update container groups with specified configurations.
* x-ms-original-file: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupEncryptionProperties.json
*/
async function containerGroupWithEncryptionProperties() {
const subscriptionId = process.env["CONTAINERINSTANCE_SUBSCRIPTION_ID"] || "subid";
const resourceGroupName = process.env["CONTAINERINSTANCE_RESOURCE_GROUP"] || "demo";
const containerGroupName = "demo1";
const containerGroup = {
containers: [
{
name: "demo1",
command: [],
environmentVariables: [],
image: "nginx",
ports: [{ port: 80 }],
resources: { requests: { cpu: 1, memoryInGB: 1.5 } },
},
],
encryptionProperties: {
identity:
"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity",
keyName: "test-key",
keyVersion: "<key version>",
vaultBaseUrl: "https://testkeyvault.vault.azure.net",
},
identity: {
type: "UserAssigned",
userAssignedIdentities: {
"/subscriptions/00000000000000000000000000000000/resourcegroups/testRg/providers/MicrosoftManagedIdentity/userAssignedIdentities/containerGroupIdentity":
{},
},
},
imageRegistryCredentials: [],
ipAddress: { type: "Public", ports: [{ port: 80, protocol: "TCP" }] },
location: "eastus2",
osType: "Linux",
};
const credential = new DefaultAzureCredential();
const client = new ContainerInstanceManagementClient(credential, subscriptionId);
const result = await client.containerGroups.beginCreateOrUpdateAndWait(
resourceGroupName,
containerGroupName,
containerGroup
);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
using Azure;
using Azure.ResourceManager;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.ContainerInstance.Models;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.ContainerInstance;
// Generated from example definition: specification/containerinstance/resource-manager/Microsoft.ContainerInstance/stable/2023-05-01/examples/ContainerGroupEncryptionProperties.json
// this example is just showing the usage of "ContainerGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately.
// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// authenticate your client
ArmClient client = new ArmClient(cred);
// this example assumes you already have this ResourceGroupResource created on azure
// for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
string subscriptionId = "subid";
string resourceGroupName = "demo";
ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
// get the collection of this ContainerGroupResource
ContainerGroupCollection collection = resourceGroupResource.GetContainerGroups();
// invoke the operation
string containerGroupName = "demo1";
ContainerGroupData data = new ContainerGroupData(new AzureLocation("eastus2"), new ContainerInstanceContainer[]
{
new ContainerInstanceContainer("demo1","nginx",new ContainerResourceRequirements(new ContainerResourceRequestsContent(1.5,1)))
{
Command =
{
},
Ports =
{
new ContainerPort(80)
},
EnvironmentVariables =
{
},
}
}, ContainerInstanceOperatingSystemType.Linux)
{
Identity = new ManagedServiceIdentity("UserAssigned")
{
UserAssignedIdentities =
{
[new ResourceIdentifier("/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity")] = new UserAssignedIdentity(),
},
},
ImageRegistryCredentials =
{
},
IPAddress = new ContainerGroupIPAddress(new ContainerGroupPort[]
{
new ContainerGroupPort(80)
{
Protocol = ContainerGroupNetworkProtocol.Tcp,
}
}, ContainerGroupIPAddressType.Public),
EncryptionProperties = new ContainerGroupEncryptionProperties(new Uri("https://testkeyvault.vault.azure.net"), "test-key", "<key version>")
{
Identity = "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity",
},
};
ArmOperation<ContainerGroupResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, containerGroupName, data);
ContainerGroupResource result = lro.Value;
// the variable result is a resource, you could call other operations on this instance as well
// but just for demo, we get its data from this resource instance
ContainerGroupData resourceData = result.Data;
// for demo we just print out the id
Console.WriteLine($"Succeeded on id: {resourceData.Id}");
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Пример ответа
{
"properties": {
"sku": "Standard",
"encryptionProperties": {
"vaultBaseUrl": "https://testkeyvault.vault.azure.net/",
"keyName": "test-key",
"keyVersion": "<key version>",
"identity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity"
},
"provisioningState": "Pending",
"containers": [
{
"name": "demo1",
"properties": {
"image": "nginx",
"command": [],
"ports": [
{
"port": 80
}
],
"environmentVariables": [],
"resources": {
"requests": {
"memoryInGB": 1.5,
"cpu": 1
}
}
}
}
],
"initContainers": [],
"imageRegistryCredentials": [],
"ipAddress": {
"ports": [
{
"protocol": "TCP",
"port": 80
}
],
"type": "Public"
},
"osType": "Linux",
"instanceView": {
"events": [],
"state": "Pending"
}
},
"identity": {
"userAssignedIdentities": {
"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity": {
"principalId": "<principal id>",
"clientId": "<client id>"
}
},
"tenantId": "<tenant id>",
"type": "UserAssigned"
},
"id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ContainerInstance/containerGroups/demo1",
"name": "demo1",
"type": "Microsoft.ContainerInstance/containerGroups",
"location": "eastus2"
}
{
"properties": {
"sku": "Standard",
"encryptionProperties": {
"vaultBaseUrl": "https://testkeyvault.vault.azure.net/",
"keyName": "test-key",
"keyVersion": "key version",
"identity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity"
},
"provisioningState": "Running",
"containers": [
{
"name": "demo1",
"properties": {
"image": "nginx",
"command": [],
"ports": [
{
"port": 80
}
],
"environmentVariables": [],
"resources": {
"requests": {
"memoryInGB": 1.5,
"cpu": 1
}
}
}
}
],
"initContainers": [],
"imageRegistryCredentials": [],
"ipAddress": {
"ports": [
{
"protocol": "TCP",
"port": 80
}
],
"type": "Public"
},
"osType": "Linux",
"instanceView": {
"events": [],
"state": "Pending"
}
},
"identity": {
"userAssignedIdentities": {
"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/container-group-identity": {
"principalId": "<principal id>",
"clientId": "<client id>"
}
},
"tenantId": "<tenant id>",
"type": "UserAssigned"
},
"id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/Microsoft.ContainerInstance/containerGroups/demo1",
"name": "demo1",
"type": "Microsoft.ContainerInstance/containerGroups",
"location": "eastus2"
}
Определения
Имя |
Описание |
AzureFileVolume
|
Свойства тома файлов Azure. Общие папки Azure подключены как тома.
|
CloudError
|
Ответ об ошибке службы экземпляра контейнера.
|
CloudErrorBody
|
Ответ об ошибке службы экземпляра контейнера.
|
ConfidentialComputeProperties
|
Свойства для конфиденциальной группы контейнеров
|
Container
|
Экземпляр контейнера.
|
ContainerExec
|
Команда выполнения контейнера для проверки активности или готовности
|
ContainerGroup
|
Группа контейнеров.
|
ContainerGroupDiagnostics
|
Сведения о диагностике группы контейнеров.
|
ContainerGroupIdentity
|
Удостоверение для группы контейнеров.
|
ContainerGroupIpAddressType
|
Указывает, предоставляется ли IP-адрес общедоступному Интернету или частной виртуальной сети.
|
ContainerGroupNetworkProtocol
|
Протокол, связанный с портом.
|
ContainerGroupPriority
|
Приоритет группы контейнеров.
|
ContainerGroupProperties.properties.InstanceView
|
Представление экземпляра группы контейнеров. Допустимо только в ответе.
|
ContainerGroupRestartPolicy
|
Перезапустите политику для всех контейнеров в группе контейнеров.
-
Always Всегда перезапуск
-
OnFailure перезапуск при сбое
-
Never никогда не перезапускать
|
ContainerGroupSku
|
Номер SKU группы контейнеров.
|
ContainerGroupSubnetId
|
Сведения о подсети группы контейнеров.
|
ContainerHttpGet
|
Параметры Http Get контейнера для проверки активности или готовности
|
ContainerNetworkProtocol
|
Протокол, связанный с портом.
|
ContainerPort
|
Порт, предоставляемый в экземпляре контейнера.
|
ContainerProbe
|
Проба контейнера для активности или готовности
|
ContainerState
|
Состояние экземпляра контейнера.
|
DeploymentExtensionSpec
|
К развертыванию добавляются боковики расширений.
|
DnsConfiguration
|
Конфигурация DNS для группы контейнеров.
|
dnsNameLabelReusePolicy
|
Значение, представляющее перечисление безопасности. Значение "Незащищено" является значением по умолчанию, если не выбрано и означает, что метка доменного имени объекта не защищена от поглощения поддомена. Значение TenantReuse — это значение по умолчанию, если выбрано и означает, что метка доменного имени объекта может использоваться повторно в одном клиенте. Значение SubscriptionReuse означает, что метка доменного имени объекта может использоваться повторно в той же подписке. Значение ResourceGroupReuse означает, что метка доменного имени объекта может использоваться повторно в одной группе ресурсов. Значение NoReuse означает, что метка доменного имени объекта не может использоваться повторно в одной группе ресурсов, подписке или клиенте.
|
EmptyDirVolume
|
Пустой том каталога.
|
EncryptionProperties
|
Свойства шифрования группы контейнеров.
|
EnvironmentVariable
|
Переменная среды, заданная в экземпляре контейнера.
|
Event
|
Событие группы контейнеров или экземпляра контейнера.
|
GitRepoVolume
|
Представляет том, заполненный содержимым репозитория Git
|
GpuResource
|
Ресурс GPU.
|
GpuSku
|
Номер SKU ресурса GPU.
|
HttpHeader
|
Заголовок HTTP.
|
ImageRegistryCredential
|
Учетные данные реестра образов.
|
InitContainerDefinition
|
Определение контейнера init.
|
InitContainerPropertiesDefinition.InstanceView
|
Представление экземпляра контейнера init. Допустимо только в ответе.
|
InstanceView
|
Представление экземпляра экземпляра экземпляра контейнера. Допустимо только в ответе.
|
IpAddress
|
IP-адрес группы контейнеров.
|
LogAnalytics
|
Сведения о log analytics группы контейнеров.
|
LogAnalyticsLogType
|
Используемый тип журнала.
|
OperatingSystemTypes
|
Тип операционной системы, необходимый контейнерам в группе контейнеров.
|
Port
|
Порт, предоставляемый в группе контейнеров.
|
ResourceIdentityType
|
Тип удостоверения, используемого для группы контейнеров. Тип SystemAssigned, UserAssigned включает как неявное созданное удостоверение, так и набор назначенных пользователем удостоверений. Тип None удаляет все удостоверения из группы контейнеров.
|
ResourceLimits
|
Ограничения ресурсов.
|
ResourceRequests
|
Запросы ресурсов.
|
ResourceRequirements
|
Требования к ресурсам.
|
Scheme
|
Схема.
|
SecurityContextCapabilitiesDefinition
|
Возможности добавления или удаления из контейнера.
|
SecurityContextDefinition
|
Контекст безопасности контейнера.
|
UserAssignedIdentities
|
Список удостоверений пользователей, связанных с группой контейнеров. Ссылки на ключ словаря удостоверений пользователя будут идентификаторами ресурсов ARM в форме: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}".
|
Volume
|
Свойства тома.
|
VolumeMount
|
Свойства подключения тома.
|
AzureFileVolume
Object
Свойства тома файлов Azure. Общие папки Azure подключены как тома.
Имя |
Тип |
Описание |
readOnly
|
boolean
|
Флаг, указывающий, подключен ли общий файл Azure в качестве тома только для чтения.
|
shareName
|
string
|
Имя общей папки Azure, подключенной в качестве тома.
|
storageAccountKey
|
string
|
Ключ доступа к учетной записи хранения, используемый для доступа к общей папке Azure.
|
storageAccountName
|
string
|
Имя учетной записи хранения, содержащей общую папку Azure.
|
CloudError
Object
Ответ об ошибке службы экземпляра контейнера.
Имя |
Тип |
Описание |
error
|
CloudErrorBody
|
Ответ об ошибке службы экземпляра контейнера.
|
CloudErrorBody
Object
Ответ об ошибке службы экземпляра контейнера.
Имя |
Тип |
Описание |
code
|
string
|
Идентификатор ошибки. Коды являются инвариантными и предназначены для программного использования.
|
details
|
CloudErrorBody[]
|
Список дополнительных сведений об ошибке.
|
message
|
string
|
Сообщение, описывающее ошибку, предназначенное для отображения в пользовательском интерфейсе.
|
target
|
string
|
Целевой объект конкретной ошибки. Например, имя свойства в ошибке.
|
ConfidentialComputeProperties
Object
Свойства для конфиденциальной группы контейнеров
Имя |
Тип |
Описание |
ccePolicy
|
string
|
Политика принудительного применения конфиденциальных вычислений в кодировке Base64
|
Container
Object
Экземпляр контейнера.
Имя |
Тип |
Описание |
name
|
string
|
Имя экземпляра контейнера, предоставленное пользователем.
|
properties.command
|
string[]
|
Команды, выполняемые в экземпляре контейнера в форме exec.
|
properties.environmentVariables
|
EnvironmentVariable[]
|
Переменные среды, заданные в экземпляре контейнера.
|
properties.image
|
string
|
Имя образа, используемого для создания экземпляра контейнера.
|
properties.instanceView
|
InstanceView
|
Представление экземпляра экземпляра экземпляра контейнера. Допустимо только в ответе.
|
properties.livenessProbe
|
ContainerProbe
|
Проба активности.
|
properties.ports
|
ContainerPort[]
|
Предоставленные порты в экземпляре контейнера.
|
properties.readinessProbe
|
ContainerProbe
|
Проба готовности.
|
properties.resources
|
ResourceRequirements
|
Требования к ресурсам экземпляра контейнера.
|
properties.securityContext
|
SecurityContextDefinition
|
Свойства безопасности контейнера.
|
properties.volumeMounts
|
VolumeMount[]
|
Том подключается к экземпляру контейнера.
|
ContainerExec
Object
Команда выполнения контейнера для проверки активности или готовности
Имя |
Тип |
Описание |
command
|
string[]
|
Команды, выполняемые в контейнере.
|
ContainerGroup
Object
Группа контейнеров.
Имя |
Тип |
Описание |
id
|
string
|
Идентификатор ресурса.
|
identity
|
ContainerGroupIdentity
|
Удостоверение группы контейнеров, если настроено.
|
location
|
string
|
Расположение ресурса.
|
name
|
string
|
Имя ресурса.
|
properties.confidentialComputeProperties
|
ConfidentialComputeProperties
|
Свойства для конфиденциальной группы контейнеров
|
properties.containers
|
Container[]
|
Контейнеры в группе контейнеров.
|
properties.diagnostics
|
ContainerGroupDiagnostics
|
Диагностические сведения для группы контейнеров.
|
properties.dnsConfig
|
DnsConfiguration
|
Сведения о конфигурации DNS для группы контейнеров.
|
properties.encryptionProperties
|
EncryptionProperties
|
Свойства шифрования для группы контейнеров.
|
properties.extensions
|
DeploymentExtensionSpec[]
|
расширения, используемые виртуальным kubelet
|
properties.imageRegistryCredentials
|
ImageRegistryCredential[]
|
Учетные данные реестра образов, из которых создается группа контейнеров.
|
properties.initContainers
|
InitContainerDefinition[]
|
Контейнеры инициализации для группы контейнеров.
|
properties.instanceView
|
ContainerGroupProperties.properties.InstanceView
|
Представление экземпляра группы контейнеров. Допустимо только в ответе.
|
properties.ipAddress
|
IpAddress
|
Тип IP-адреса группы контейнеров.
|
properties.osType
|
OperatingSystemTypes
|
Тип операционной системы, необходимый контейнерам в группе контейнеров.
|
properties.priority
|
ContainerGroupPriority
|
Приоритет группы контейнеров.
|
properties.provisioningState
|
string
|
Состояние подготовки группы контейнеров. Это отображается только в ответе.
|
properties.restartPolicy
|
ContainerGroupRestartPolicy
|
Перезапустите политику для всех контейнеров в группе контейнеров.
-
Always Всегда перезапуск
-
OnFailure перезапуск при сбое
-
Never никогда не перезапускать
|
properties.sku
|
ContainerGroupSku
|
Номер SKU для группы контейнеров.
|
properties.subnetIds
|
ContainerGroupSubnetId[]
|
Идентификаторы ресурсов подсети для группы контейнеров.
|
properties.volumes
|
Volume[]
|
Список томов, которые могут быть подключены контейнерами в этой группе контейнеров.
|
tags
|
object
|
Теги ресурсов.
|
type
|
string
|
Тип ресурса.
|
zones
|
string[]
|
Зоны для группы контейнеров.
|
ContainerGroupDiagnostics
Object
Сведения о диагностике группы контейнеров.
Имя |
Тип |
Описание |
logAnalytics
|
LogAnalytics
|
Сведения о log analytics группы контейнеров.
|
ContainerGroupIdentity
Object
Удостоверение для группы контейнеров.
Имя |
Тип |
Описание |
principalId
|
string
|
Идентификатор субъекта удостоверения группы контейнеров. Это свойство будет предоставлено только для назначаемого системой удостоверения.
|
tenantId
|
string
|
Идентификатор клиента, связанный с группой контейнеров. Это свойство будет предоставлено только для назначаемого системой удостоверения.
|
type
|
ResourceIdentityType
|
Тип удостоверения, используемого для группы контейнеров. Тип SystemAssigned, UserAssigned включает как неявное созданное удостоверение, так и набор назначенных пользователем удостоверений. Тип None удаляет все удостоверения из группы контейнеров.
|
userAssignedIdentities
|
<string,
UserAssignedIdentities>
|
Список удостоверений пользователей, связанных с группой контейнеров.
|
ContainerGroupIpAddressType
Перечисление
Указывает, предоставляется ли IP-адрес общедоступному Интернету или частной виртуальной сети.
Значение |
Описание |
Private
|
|
Public
|
|
ContainerGroupNetworkProtocol
Перечисление
Протокол, связанный с портом.
Значение |
Описание |
TCP
|
|
UDP
|
|
ContainerGroupPriority
Перечисление
Приоритет группы контейнеров.
Значение |
Описание |
Regular
|
|
Spot
|
|
ContainerGroupProperties.properties.InstanceView
Object
Представление экземпляра группы контейнеров. Допустимо только в ответе.
Имя |
Тип |
Описание |
events
|
Event[]
|
События этой группы контейнеров.
|
state
|
string
|
Состояние группы контейнеров. Допустимо только в ответе.
|
ContainerGroupRestartPolicy
Перечисление
Перезапустите политику для всех контейнеров в группе контейнеров.
-
Always
Всегда перезапуск
-
OnFailure
перезапуск при сбое
-
Never
никогда не перезапускать
Значение |
Описание |
Always
|
|
Never
|
|
OnFailure
|
|
ContainerGroupSku
Перечисление
Номер SKU группы контейнеров.
Значение |
Описание |
Confidential
|
|
Dedicated
|
|
Standard
|
|
ContainerGroupSubnetId
Object
Сведения о подсети группы контейнеров.
Имя |
Тип |
Описание |
id
|
string
|
Идентификатор ресурса виртуальной сети и подсети.
|
name
|
string
|
Понятное имя подсети.
|
ContainerHttpGet
Object
Параметры Http Get контейнера для проверки активности или готовности
Имя |
Тип |
Описание |
httpHeaders
|
HttpHeader[]
|
Заголовки HTTP.
|
path
|
string
|
Путь к пробе.
|
port
|
integer
(int32)
|
Номер порта для проверки.
|
scheme
|
Scheme
|
Схема.
|
ContainerNetworkProtocol
Перечисление
Протокол, связанный с портом.
Значение |
Описание |
TCP
|
|
UDP
|
|
ContainerPort
Object
Порт, предоставляемый в экземпляре контейнера.
Имя |
Тип |
Описание |
port
|
integer
(int32)
|
Номер порта, предоставляемый в группе контейнеров.
|
protocol
|
ContainerNetworkProtocol
|
Протокол, связанный с портом.
|
ContainerProbe
Object
Проба контейнера для активности или готовности
Имя |
Тип |
Описание |
exec
|
ContainerExec
|
Команда выполнения для проверки
|
failureThreshold
|
integer
(int32)
|
Порог сбоя.
|
httpGet
|
ContainerHttpGet
|
Параметры Http Get для проверки
|
initialDelaySeconds
|
integer
(int32)
|
Начальная задержка секунд.
|
periodSeconds
|
integer
(int32)
|
Период секунд.
|
successThreshold
|
integer
(int32)
|
Порог успешности.
|
timeoutSeconds
|
integer
(int32)
|
Время ожидания секунд.
|
ContainerState
Object
Состояние экземпляра контейнера.
Имя |
Тип |
Описание |
detailStatus
|
string
|
Состояние экземпляра контейнера, доступное для чтения.
|
exitCode
|
integer
(int32)
|
Коды выхода экземпляра контейнера соответствуют кодам из команды docker run .
|
finishTime
|
string
(date-time)
|
Дата и время завершения состояния экземпляра контейнера.
|
startTime
|
string
(date-time)
|
Дата начала состояния экземпляра контейнера.
|
state
|
string
|
Состояние экземпляра контейнера.
|
DeploymentExtensionSpec
Object
К развертыванию добавляются боковики расширений.
Имя |
Тип |
Описание |
name
|
string
|
Имя расширения.
|
properties.extensionType
|
string
|
Тип добавляемого расширения.
|
properties.protectedSettings
|
object
|
Защищенные параметры расширения.
|
properties.settings
|
object
|
Параметры расширения.
|
properties.version
|
string
|
Версия используемого расширения.
|
DnsConfiguration
Object
Конфигурация DNS для группы контейнеров.
Имя |
Тип |
Описание |
nameServers
|
string[]
|
DNS-серверы для группы контейнеров.
|
options
|
string
|
Параметры DNS для группы контейнеров.
|
searchDomains
|
string
|
Домены поиска DNS для поиска имени узла в группе контейнеров.
|
dnsNameLabelReusePolicy
Перечисление
Значение, представляющее перечисление безопасности. Значение "Незащищено" является значением по умолчанию, если не выбрано и означает, что метка доменного имени объекта не защищена от поглощения поддомена. Значение TenantReuse — это значение по умолчанию, если выбрано и означает, что метка доменного имени объекта может использоваться повторно в одном клиенте. Значение SubscriptionReuse означает, что метка доменного имени объекта может использоваться повторно в той же подписке. Значение ResourceGroupReuse означает, что метка доменного имени объекта может использоваться повторно в одной группе ресурсов. Значение NoReuse означает, что метка доменного имени объекта не может использоваться повторно в одной группе ресурсов, подписке или клиенте.
Значение |
Описание |
Noreuse
|
|
ResourceGroupReuse
|
|
SubscriptionReuse
|
|
TenantReuse
|
|
Unsecure
|
|
EmptyDirVolume
Object
Пустой том каталога.
EncryptionProperties
Object
Свойства шифрования группы контейнеров.
Имя |
Тип |
Описание |
identity
|
string
|
Управляемое удостоверение keyvault.
|
keyName
|
string
|
Имя ключа шифрования.
|
keyVersion
|
string
|
Версия ключа шифрования.
|
vaultBaseUrl
|
string
|
Базовый URL-адрес keyvault.
|
EnvironmentVariable
Object
Переменная среды, заданная в экземпляре контейнера.
Имя |
Тип |
Описание |
name
|
string
|
Имя переменной среды.
|
secureValue
|
string
|
Значение переменной безопасной среды.
|
value
|
string
|
Значение переменной среды.
|
Event
Object
Событие группы контейнеров или экземпляра контейнера.
Имя |
Тип |
Описание |
count
|
integer
(int32)
|
Количество событий.
|
firstTimestamp
|
string
(date-time)
|
Дата и время самого раннего регистрированного события.
|
lastTimestamp
|
string
(date-time)
|
Дата последнего регистрированного события.
|
message
|
string
|
Сообщение о событии.
|
name
|
string
|
Имя события.
|
type
|
string
|
Тип события.
|
GitRepoVolume
Object
Представляет том, заполненный содержимым репозитория Git
Имя |
Тип |
Описание |
directory
|
string
|
Имя целевого каталога. Не должно содержать или начинаться с '.'. Если задано значение ".", каталог томов будет репозиторием Git. В противном случае, если задано, том будет содержать репозиторий Git в подкаталоге с заданным именем.
|
repository
|
string
|
URL-адрес репозитория
|
revision
|
string
|
Зафиксировать хэш для указанной редакции.
|
GpuResource
Object
Ресурс GPU.
Имя |
Тип |
Описание |
count
|
integer
(int32)
|
Количество ресурсов GPU.
|
sku
|
GpuSku
|
Номер SKU ресурса GPU.
|
GpuSku
Перечисление
Номер SKU ресурса GPU.
Значение |
Описание |
K80
|
|
P100
|
|
V100
|
|
Object
Заголовок HTTP.
Имя |
Тип |
Описание |
name
|
string
|
Имя заголовка.
|
value
|
string
|
Значение заголовка.
|
ImageRegistryCredential
Object
Учетные данные реестра образов.
Имя |
Тип |
Описание |
identity
|
string
|
Удостоверение частного реестра.
|
identityUrl
|
string
|
URL-адрес удостоверения для частного реестра.
|
password
|
string
|
Пароль для частного реестра.
|
server
|
string
|
Сервер реестра образов Docker без протокола, например http и https.
|
username
|
string
|
Имя пользователя для частного реестра.
|
InitContainerDefinition
Object
Определение контейнера init.
Имя |
Тип |
Описание |
name
|
string
|
Имя контейнера инициализации.
|
properties.command
|
string[]
|
Команда, выполняемая в контейнере init в форме exec.
|
properties.environmentVariables
|
EnvironmentVariable[]
|
Переменные среды, заданные в контейнере init.
|
properties.image
|
string
|
Изображение контейнера инициализации.
|
properties.instanceView
|
InitContainerPropertiesDefinition.InstanceView
|
Представление экземпляра контейнера init. Допустимо только в ответе.
|
properties.securityContext
|
SecurityContextDefinition
|
Свойства безопасности контейнера.
|
properties.volumeMounts
|
VolumeMount[]
|
Том подключается к контейнеру init.
|
InitContainerPropertiesDefinition.InstanceView
Object
Представление экземпляра контейнера init. Допустимо только в ответе.
Имя |
Тип |
Описание |
currentState
|
ContainerState
|
Текущее состояние контейнера инициализации.
|
events
|
Event[]
|
События контейнера инициализации.
|
previousState
|
ContainerState
|
Предыдущее состояние контейнера инициализации.
|
restartCount
|
integer
(int32)
|
Количество раз перезапуска контейнера инициализации.
|
InstanceView
Object
Представление экземпляра экземпляра экземпляра контейнера. Допустимо только в ответе.
Имя |
Тип |
Описание |
currentState
|
ContainerState
|
Текущее состояние экземпляра контейнера.
|
events
|
Event[]
|
События экземпляра контейнера.
|
previousState
|
ContainerState
|
Предыдущее состояние экземпляра контейнера.
|
restartCount
|
integer
(int32)
|
Количество перезапуска экземпляра контейнера.
|
IpAddress
Object
IP-адрес группы контейнеров.
Имя |
Тип |
Default value |
Описание |
autoGeneratedDomainNameLabelScope
|
dnsNameLabelReusePolicy
|
Unsecure
|
Значение, представляющее перечисление безопасности. Значение "Незащищено" является значением по умолчанию, если не выбрано и означает, что метка доменного имени объекта не защищена от поглощения поддомена. Значение TenantReuse — это значение по умолчанию, если выбрано и означает, что метка доменного имени объекта может использоваться повторно в одном клиенте. Значение SubscriptionReuse означает, что метка доменного имени объекта может использоваться повторно в той же подписке. Значение ResourceGroupReuse означает, что метка доменного имени объекта может использоваться повторно в одной группе ресурсов. Значение NoReuse означает, что метка доменного имени объекта не может использоваться повторно в одной группе ресурсов, подписке или клиенте.
|
dnsNameLabel
|
string
|
|
Метка DNS-имени для IP-адреса.
|
fqdn
|
string
|
|
Полное доменное имя для IP-адреса.
|
ip
|
string
|
|
IP-адрес, предоставляемый общедоступному Интернету.
|
ports
|
Port[]
|
|
Список портов, предоставляемых в группе контейнеров.
|
type
|
ContainerGroupIpAddressType
|
|
Указывает, предоставляется ли IP-адрес общедоступному Интернету или частной виртуальной сети.
|
LogAnalytics
Object
Сведения о log analytics группы контейнеров.
Имя |
Тип |
Описание |
logType
|
LogAnalyticsLogType
|
Используемый тип журнала.
|
metadata
|
object
|
Метаданные для log analytics.
|
workspaceId
|
string
|
Идентификатор рабочей области для log analytics
|
workspaceKey
|
string
|
Ключ рабочей области для log analytics
|
workspaceResourceId
|
string
|
Идентификатор ресурса рабочей области для log analytics
|
LogAnalyticsLogType
Перечисление
Используемый тип журнала.
Значение |
Описание |
ContainerInsights
|
|
ContainerInstanceLogs
|
|
OperatingSystemTypes
Перечисление
Тип операционной системы, необходимый контейнерам в группе контейнеров.
Значение |
Описание |
Linux
|
|
Windows
|
|
Port
Object
Порт, предоставляемый в группе контейнеров.
ResourceIdentityType
Перечисление
Тип удостоверения, используемого для группы контейнеров. Тип SystemAssigned, UserAssigned включает как неявное созданное удостоверение, так и набор назначенных пользователем удостоверений. Тип None удаляет все удостоверения из группы контейнеров.
Значение |
Описание |
None
|
|
SystemAssigned
|
|
SystemAssigned, UserAssigned
|
|
UserAssigned
|
|
ResourceLimits
Object
Ограничения ресурсов.
Имя |
Тип |
Описание |
cpu
|
number
(double)
|
Ограничение ЦП этого экземпляра контейнера.
|
gpu
|
GpuResource
|
Ограничение GPU этого экземпляра контейнера.
|
memoryInGB
|
number
(double)
|
Ограничение памяти в ГБ этого экземпляра контейнера.
|
ResourceRequests
Object
Запросы ресурсов.
Имя |
Тип |
Описание |
cpu
|
number
(double)
|
Запрос ЦП этого экземпляра контейнера.
|
gpu
|
GpuResource
|
Запрос GPU этого экземпляра контейнера.
|
memoryInGB
|
number
(double)
|
Запрос памяти в ГБ этого экземпляра контейнера.
|
ResourceRequirements
Object
Требования к ресурсам.
Имя |
Тип |
Описание |
limits
|
ResourceLimits
|
Ограничения ресурсов этого экземпляра контейнера.
|
requests
|
ResourceRequests
|
Запросы ресурсов этого экземпляра контейнера.
|
Scheme
Перечисление
Схема.
Значение |
Описание |
http
|
|
https
|
|
SecurityContextCapabilitiesDefinition
Object
Возможности добавления или удаления из контейнера.
Имя |
Тип |
Описание |
add
|
string[]
|
Возможности для добавления в контейнер.
|
drop
|
string[]
|
Возможности для удаления из контейнера.
|
SecurityContextDefinition
Object
Контекст безопасности контейнера.
Имя |
Тип |
Описание |
allowPrivilegeEscalation
|
boolean
|
Логическое значение, указывающее, может ли процесс инициализации повысить привилегии.
|
capabilities
|
SecurityContextCapabilitiesDefinition
|
Возможности добавления или удаления из контейнера.
|
privileged
|
boolean
|
Флаг, определяющий, являются ли разрешения контейнера повышенными привилегиями.
|
runAsGroup
|
integer
(int32)
|
Задает ИДЕНТИФИКАТОР пользователя для контейнера.
|
runAsUser
|
integer
(int32)
|
Задает идентификатор пользовательского интерфейса пользователя для контейнера.
|
seccompProfile
|
string
|
Строка в кодировке Base64, содержащая содержимое JSON в профиле seccomp
|
UserAssignedIdentities
Object
Список удостоверений пользователей, связанных с группой контейнеров. Ссылки на ключ словаря удостоверений пользователя будут идентификаторами ресурсов ARM в форме: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}".
Имя |
Тип |
Описание |
clientId
|
string
|
Идентификатор клиента назначаемого пользователем удостоверения.
|
principalId
|
string
|
Идентификатор субъекта назначаемого пользователем удостоверения.
|
Volume
Object
Свойства тома.
VolumeMount
Object
Свойства подключения тома.
Имя |
Тип |
Описание |
mountPath
|
string
|
Путь в контейнере, в котором должен быть подключен том. Не должен содержать двоеточие (:).
|
name
|
string
|
Имя подключения тома.
|
readOnly
|
boolean
|
Флаг, указывающий, доступен ли подключение тома только для чтения.
|