upload/azure: user newer resourcemanager packages

The older azure sdk and autorest packages are deprecated.

Signed-off-by: Sanne Raymaekers <sanne.raymaekers@gmail.com>
This commit is contained in:
Sanne Raymaekers 2023-12-15 13:37:04 +01:00
parent d5e1bc28e9
commit 828d82e871
301 changed files with 108023 additions and 32863 deletions

View file

@ -763,21 +763,29 @@ func (impl *OSBuildJobImpl) Run(job worker.Job) error {
break
}
c, err := azure.NewClient(*impl.AzureConfig.Creds, targetOptions.TenantID)
c, err := azure.NewClient(*impl.AzureConfig.Creds, targetOptions.TenantID, targetOptions.SubscriptionID)
if err != nil {
targetResult.TargetError = clienterrors.WorkerClientError(clienterrors.ErrorInvalidTargetConfig, err.Error(), nil)
break
}
logWithId.Info("[Azure] 🔑 Logged in Azure")
location := targetOptions.Location
if location == "" {
location, err = c.GetResourceGroupLocation(ctx, targetOptions.ResourceGroup)
if err != nil {
targetResult.TargetError = clienterrors.WorkerClientError(clienterrors.ErrorInvalidTargetConfig, fmt.Sprintf("retrieving resource group location failed: %v", err), nil)
break
}
}
storageAccountTag := azure.Tag{
Name: "imageBuilderStorageAccount",
Value: fmt.Sprintf("location=%s", targetOptions.Location),
Value: fmt.Sprintf("location=%s", location),
}
storageAccount, err := c.GetResourceNameByTag(
ctx,
targetOptions.SubscriptionID,
targetOptions.ResourceGroup,
storageAccountTag,
)
@ -793,10 +801,9 @@ func (impl *OSBuildJobImpl) Run(job worker.Job) error {
err := c.CreateStorageAccount(
ctx,
targetOptions.SubscriptionID,
targetOptions.ResourceGroup,
storageAccount,
targetOptions.Location,
location,
storageAccountTag,
)
if err != nil {
@ -808,7 +815,6 @@ func (impl *OSBuildJobImpl) Run(job worker.Job) error {
logWithId.Info("[Azure] 🔑📦 Retrieving a storage account key")
storageAccessKey, err := c.GetStorageAccountKey(
ctx,
targetOptions.SubscriptionID,
targetOptions.ResourceGroup,
storageAccount,
)
@ -873,7 +879,7 @@ func (impl *OSBuildJobImpl) Run(job worker.Job) error {
storageContainer,
blobName,
jobTarget.ImageName,
targetOptions.Location,
location,
)
if err != nil {
targetResult.TargetError = clienterrors.WorkerClientError(clienterrors.ErrorImportingImage, fmt.Sprintf("registering the image failed: %v", err), nil)

8
go.mod
View file

@ -8,6 +8,10 @@ require (
cloud.google.com/go/compute v1.23.3
cloud.google.com/go/storage v1.36.0
github.com/Azure/azure-sdk-for-go v68.0.0+incompatible
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.4.0
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.3.0
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.5.0
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.2.1
github.com/Azure/go-autorest/autorest v0.11.29
github.com/Azure/go-autorest/autorest/azure/auth v0.5.12
@ -62,6 +66,7 @@ require (
github.com/Azure/go-autorest/autorest/validation v0.3.1 // indirect
github.com/Azure/go-autorest/logger v0.2.1 // indirect
github.com/Azure/go-autorest/tracing v0.6.0 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.1.1 // indirect
github.com/VividCortex/ewma v1.2.0 // indirect
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d // indirect
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
@ -100,6 +105,7 @@ require (
github.com/go-openapi/swag v0.22.4 // indirect
github.com/go-openapi/validate v0.22.1 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/golang-jwt/jwt/v5 v5.0.0 // indirect
github.com/golang/glog v1.1.2 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.3 // indirect
@ -127,6 +133,7 @@ require (
github.com/klauspost/compress v1.17.3 // indirect
github.com/klauspost/pgzip v1.2.6 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/letsencrypt/boulder v0.0.0-20230213213521-fdfea0d469b6 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
@ -146,6 +153,7 @@ require (
github.com/opencontainers/image-spec v1.1.0-rc5 // indirect
github.com/opencontainers/runc v1.1.10 // indirect
github.com/opencontainers/runtime-spec v1.1.0 // indirect
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/proglottis/gpgme v0.1.3 // indirect

13
go.sum
View file

@ -15,9 +15,17 @@ github.com/Azure/azure-sdk-for-go v68.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9mo
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1 h1:lGlwhPtrX6EVml1hO0ivjkUxsSyl4dsiw9qcA1k/3IQ=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1/go.mod h1:RKUqNu35KJYcVG/fqTRqmuXJZYNhYkBrnC/hX7yGbTA=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.4.0 h1:BMAjVKJM0U/CYF27gA0ZMmXGkOcvfFtD0oHVZ1TIPRI=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.4.0/go.mod h1:1fXstnBMas5kzG+S3q8UoJcmyU6nUeunJcMDHcRYHhs=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1 h1:6oNBlSdi1QqM1PNW7FPA6xOGA5UNsXnkaYZz9vdPGhA=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1/go.mod h1:s4kgfzA0covAXNicZHDMN58jExvcng2mC/DepXiF1EI=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.3.0 h1:qgs/VAMSR+9qFhwTw4OwF2NbVuw+2m83pVZJjqkKQMw=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.3.0/go.mod h1:uYt4CfhkJA9o0FN7jfE5minm/i4nUE4MjGUJkzB6Zs8=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v2 v2.0.0 h1:PTFGRSlMKCQelWwxUyYVEUqseBJVemLyqWJjvMyt0do=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/managementgroups/armmanagementgroups v1.0.0 h1:pPvTJ1dY0sA35JOeFq6TsY2xj6Z85Yo23Pj4wCCvu4o=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0 h1:Dd+RhdJn0OTtVGaeDLZpcumkIVCtA/3/Fo42+eoYvVM=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0/go.mod h1:5kakwfW5CjC9KK+Q4wjXAg+ShuIm2mBMua0ZFj2C8PE=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.5.0 h1:AifHbc4mg0x9zW52WOpKbsHaDKuRhlI7TVl47thgQ70=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.5.0/go.mod h1:T5RfihdXtBDxt1Ch2wobif3TvzTdumDy29kahv6AV9A=
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.2.1 h1:AMf7YbZOZIW5b66cXNHMWWT/zkjhz5+a+k/3x40EO7E=
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.2.1/go.mod h1:uwfk06ZBcvL/g4VHNjurPfVln9NMbsk2XIZxJ+hu81k=
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
@ -48,6 +56,7 @@ github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZ
github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUMfuitfgcfuo=
github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU=
github.com/AzureAD/microsoft-authentication-library-for-go v1.1.1 h1:WpB/QDNLpMw72xHJc34BNNykqSOeEJDAWkhf0u12/Jk=
github.com/AzureAD/microsoft-authentication-library-for-go v1.1.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
@ -226,6 +235,7 @@ github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzw
github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE=
github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/glog v1.1.2 h1:DVjP2PbBOzHyzA+dn3WhHIq4NdVu3Q+pvivFICf/7fo=
github.com/golang/glog v1.1.2/go.mod h1:zR+okUeTbrL6EL3xHUDxZuEtGv04p5shwip1+mL/rLQ=
@ -383,6 +393,7 @@ github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/labstack/echo/v4 v4.2.1/go.mod h1:AA49e0DZ8kk5jTOOCKNuPR6oTnBS0dYiM4FW1e6jwpg=
github.com/labstack/echo/v4 v4.11.4 h1:vDZmA+qNeh1pd/cCkEicDMrjtrnMGQ1QFI9gWN1zGq8=
github.com/labstack/echo/v4 v4.11.4/go.mod h1:noh7EvLwqDsmh/X/HWKPUl1AjzJrhyptRyEbQJfxen8=
@ -471,6 +482,7 @@ github.com/osbuild/pulp-client v0.1.0/go.mod h1:rd/MLdfwwO2cQI1s056h8z32zAi3Bo90
github.com/otiai10/copy v1.14.0 h1:dCI/t1iTdYGtkvCuBG2BgR6KZa83PTclw4U5n2wAllU=
github.com/pelletier/go-toml v1.7.0/go.mod h1:vwGMzjaWMwyfHwgIBhI2YUM4fB6nL6lVAvS1LBMMhTE=
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU=
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
@ -697,6 +709,7 @@ golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=

View file

@ -5,29 +5,43 @@ import (
"errors"
"fmt"
"github.com/Azure/azure-sdk-for-go/profiles/2019-03-01/compute/mgmt/compute"
"github.com/Azure/azure-sdk-for-go/profiles/2019-03-01/resources/mgmt/resources"
"github.com/Azure/azure-sdk-for-go/profiles/2019-03-01/storage/mgmt/storage"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure/auth"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage"
"github.com/osbuild/osbuild-composer/internal/common"
)
type Client struct {
authorizer autorest.Authorizer
creds *azidentity.ClientSecretCredential
resFact *armresources.ClientFactory
storFact *armstorage.ClientFactory
}
// NewClient creates a client for accessing the Azure API.
// See https://docs.microsoft.com/en-us/rest/api/azure/
// If you need to work with the Azure Storage API, see NewStorageClient
func NewClient(credentials Credentials, tenantID string) (*Client, error) {
credentialsConfig := auth.NewClientCredentialsConfig(credentials.clientID, credentials.clientSecret, tenantID)
authorizer, err := credentialsConfig.Authorizer()
func NewClient(credentials Credentials, tenantID, subscriptionID string) (*Client, error) {
creds, err := azidentity.NewClientSecretCredential(tenantID, credentials.clientID, credentials.clientSecret, nil)
if err != nil {
return nil, fmt.Errorf("creating an azure authorizer failed: %v", err)
return nil, fmt.Errorf("creating azure ClientSecretCredential failed: %v", err)
}
resFact, err := armresources.NewClientFactory(subscriptionID, creds, nil)
if err != nil {
return nil, fmt.Errorf("creating resources client factory failed: %v", err)
}
storFact, err := armstorage.NewClientFactory(subscriptionID, creds, nil)
if err != nil {
return nil, fmt.Errorf("creating storage client factory failed: %v", err)
}
return &Client{
authorizer: authorizer,
creds,
resFact,
storFact,
}, nil
}
@ -41,29 +55,29 @@ type Tag struct {
// given `tag`. Note that if multiple resources with the same tag exists
// in the specified resource group, only one name is returned. It's undefined
// which one it is.
func (ac Client) GetResourceNameByTag(ctx context.Context, subscriptionID, resourceGroup string, tag Tag) (string, error) {
c := resources.NewClient(subscriptionID)
c.Authorizer = ac.authorizer
func (ac Client) GetResourceNameByTag(ctx context.Context, resourceGroup string, tag Tag) (string, error) {
c := ac.resFact.NewClient()
filter := fmt.Sprintf("tagName eq '%s' and tagValue eq '%s'", tag.Name, tag.Value)
result, err := c.ListByResourceGroup(ctx, resourceGroup, filter, "", nil)
pager := c.NewListByResourceGroupPager(resourceGroup, &armresources.ClientListByResourceGroupOptions{
Filter: common.ToPtr(fmt.Sprintf("tagName eq '%s' and tagValue eq '%s'", tag.Name, tag.Value)),
})
result, err := pager.NextPage(ctx)
if err != nil {
return "", fmt.Errorf("listing resources failed: %v", err)
}
if len(result.Values()) < 1 {
if len(result.Value) < 1 {
return "", nil
}
return *result.Values()[0].Name, nil
return *result.Value[0].Name, nil
}
// GetResourceGroupLocation returns the location of the given resource group.
func (ac Client) GetResourceGroupLocation(ctx context.Context, subscriptionID, resourceGroup string) (string, error) {
c := resources.NewGroupsClient(subscriptionID)
c.Authorizer = ac.authorizer
func (ac Client) GetResourceGroupLocation(ctx context.Context, resourceGroup string) (string, error) {
c := ac.resFact.NewResourceGroupsClient()
group, err := c.Get(ctx, resourceGroup)
group, err := c.Get(ctx, resourceGroup, nil)
if err != nil {
return "", fmt.Errorf("retrieving resource group failed: %v", err)
}
@ -76,38 +90,32 @@ func (ac Client) GetResourceGroupLocation(ctx context.Context, subscriptionID, r
// can be used to specify a tag attached to the account.
// The location is optional and if not provided, it is determined
// from the resource group.
func (ac Client) CreateStorageAccount(ctx context.Context, subscriptionID, resourceGroup, name, location string, tag Tag) error {
c := storage.NewAccountsClient(subscriptionID)
c.Authorizer = ac.authorizer
func (ac Client) CreateStorageAccount(ctx context.Context, resourceGroup, name, location string, tag Tag) error {
c := ac.storFact.NewAccountsClient()
var err error
if location == "" {
location, err = ac.GetResourceGroupLocation(ctx, subscriptionID, resourceGroup)
location, err = ac.GetResourceGroupLocation(ctx, resourceGroup)
if err != nil {
return fmt.Errorf("retrieving resource group location failed: %v", err)
}
}
result, err := c.Create(ctx, resourceGroup, name, storage.AccountCreateParameters{
Sku: &storage.Sku{
Name: storage.StandardLRS,
Tier: storage.Standard,
poller, err := c.BeginCreate(ctx, resourceGroup, name, armstorage.AccountCreateParameters{
SKU: &armstorage.SKU{
Name: common.ToPtr(armstorage.SKUNameStandardLRS),
Tier: common.ToPtr(armstorage.SKUTierStandard),
},
Location: &location,
Tags: map[string]*string{
tag.Name: &tag.Value,
},
})
}, nil)
if err != nil {
return fmt.Errorf("sending the create storage account request failed: %v", err)
}
err = result.WaitForCompletionRef(ctx, c.Client)
if err != nil {
return fmt.Errorf("waiting for the create storage account request failed: %v", err)
}
_, err = result.Result(c)
_, err = poller.PollUntilDone(ctx, nil)
if err != nil {
return fmt.Errorf("create storage account request failed: %v", err)
}
@ -118,63 +126,56 @@ func (ac Client) CreateStorageAccount(ctx context.Context, subscriptionID, resou
// GetStorageAccountKey returns a storage account key that can be used to
// access the given storage account. This method always returns only the first
// key.
func (ac Client) GetStorageAccountKey(ctx context.Context, subscriptionID, resourceGroup string, storageAccount string) (string, error) {
c := storage.NewAccountsClient(subscriptionID)
c.Authorizer = ac.authorizer
keys, err := c.ListKeys(ctx, resourceGroup, storageAccount)
func (ac Client) GetStorageAccountKey(ctx context.Context, resourceGroup string, storageAccount string) (string, error) {
c := ac.storFact.NewAccountsClient()
keys, err := c.ListKeys(ctx, resourceGroup, storageAccount, nil)
if err != nil {
return "", fmt.Errorf("retrieving keys for a storage account failed: %v", err)
}
if len(*keys.Keys) == 0 {
if len(keys.Keys) == 0 {
return "", errors.New("azure returned an empty list of keys")
}
return *(*keys.Keys)[0].Value, nil
return *keys.Keys[0].Value, nil
}
// RegisterImage creates a generalized V1 Linux image from a given blob.
// The location is optional and if not provided, it is determined
// from the resource group.
func (ac Client) RegisterImage(ctx context.Context, subscriptionID, resourceGroup, storageAccount, storageContainer, blobName, imageName, location string) error {
c := compute.NewImagesClient(subscriptionID)
c.Authorizer = ac.authorizer
c, err := armcompute.NewImagesClient(subscriptionID, ac.creds, nil)
if err != nil {
return fmt.Errorf("unable to create compute client: %v", err)
}
blobURI := fmt.Sprintf("https://%s.blob.core.windows.net/%s/%s", storageAccount, storageContainer, blobName)
var err error
if location == "" {
location, err = ac.GetResourceGroupLocation(ctx, subscriptionID, resourceGroup)
location, err = ac.GetResourceGroupLocation(ctx, resourceGroup)
if err != nil {
return fmt.Errorf("retrieving resource group location failed: %v", err)
}
}
imageFuture, err := c.CreateOrUpdate(ctx, resourceGroup, imageName, compute.Image{
Response: autorest.Response{},
ImageProperties: &compute.ImageProperties{
imageFuture, err := c.BeginCreateOrUpdate(ctx, resourceGroup, imageName, armcompute.Image{
Properties: &armcompute.ImageProperties{
SourceVirtualMachine: nil,
StorageProfile: &compute.ImageStorageProfile{
OsDisk: &compute.ImageOSDisk{
OsType: compute.Linux,
StorageProfile: &armcompute.ImageStorageProfile{
OSDisk: &armcompute.ImageOSDisk{
OSType: common.ToPtr(armcompute.OperatingSystemTypesLinux),
BlobURI: &blobURI,
OsState: compute.Generalized,
OSState: common.ToPtr(armcompute.OperatingSystemStateTypesGeneralized),
},
},
},
Location: &location,
})
}, nil)
if err != nil {
return fmt.Errorf("sending the create image request failed: %v", err)
}
err = imageFuture.WaitForCompletionRef(ctx, c.Client)
if err != nil {
return fmt.Errorf("waiting for the create image request failed: %v", err)
}
_, err = imageFuture.Result(c)
_, err = imageFuture.PollUntilDone(ctx, nil)
if err != nil {
return fmt.Errorf("create image request failed: %v", err)
}

View file

@ -1,992 +0,0 @@
//go:build go1.9
// +build go1.9
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// This code was auto-generated by:
// github.com/Azure/azure-sdk-for-go/eng/tools/profileBuilder
package compute
import (
"context"
original "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2017-12-01/compute"
)
const (
DefaultBaseURI = original.DefaultBaseURI
)
type AccessLevel = original.AccessLevel
const (
None AccessLevel = original.None
Read AccessLevel = original.Read
)
type CachingTypes = original.CachingTypes
const (
CachingTypesNone CachingTypes = original.CachingTypesNone
CachingTypesReadOnly CachingTypes = original.CachingTypesReadOnly
CachingTypesReadWrite CachingTypes = original.CachingTypesReadWrite
)
type ComponentNames = original.ComponentNames
const (
MicrosoftWindowsShellSetup ComponentNames = original.MicrosoftWindowsShellSetup
)
type DiskCreateOption = original.DiskCreateOption
const (
Attach DiskCreateOption = original.Attach
Copy DiskCreateOption = original.Copy
Empty DiskCreateOption = original.Empty
FromImage DiskCreateOption = original.FromImage
Import DiskCreateOption = original.Import
)
type DiskCreateOptionTypes = original.DiskCreateOptionTypes
const (
DiskCreateOptionTypesAttach DiskCreateOptionTypes = original.DiskCreateOptionTypesAttach
DiskCreateOptionTypesEmpty DiskCreateOptionTypes = original.DiskCreateOptionTypesEmpty
DiskCreateOptionTypesFromImage DiskCreateOptionTypes = original.DiskCreateOptionTypesFromImage
)
type IPVersion = original.IPVersion
const (
IPv4 IPVersion = original.IPv4
IPv6 IPVersion = original.IPv6
)
type InstanceViewTypes = original.InstanceViewTypes
const (
InstanceView InstanceViewTypes = original.InstanceView
)
type IntervalInMins = original.IntervalInMins
const (
FiveMins IntervalInMins = original.FiveMins
SixtyMins IntervalInMins = original.SixtyMins
ThirtyMins IntervalInMins = original.ThirtyMins
ThreeMins IntervalInMins = original.ThreeMins
)
type MaintenanceOperationResultCodeTypes = original.MaintenanceOperationResultCodeTypes
const (
MaintenanceOperationResultCodeTypesMaintenanceAborted MaintenanceOperationResultCodeTypes = original.MaintenanceOperationResultCodeTypesMaintenanceAborted
MaintenanceOperationResultCodeTypesMaintenanceCompleted MaintenanceOperationResultCodeTypes = original.MaintenanceOperationResultCodeTypesMaintenanceCompleted
MaintenanceOperationResultCodeTypesNone MaintenanceOperationResultCodeTypes = original.MaintenanceOperationResultCodeTypesNone
MaintenanceOperationResultCodeTypesRetryLater MaintenanceOperationResultCodeTypes = original.MaintenanceOperationResultCodeTypesRetryLater
)
type OperatingSystemStateTypes = original.OperatingSystemStateTypes
const (
Generalized OperatingSystemStateTypes = original.Generalized
Specialized OperatingSystemStateTypes = original.Specialized
)
type OperatingSystemTypes = original.OperatingSystemTypes
const (
Linux OperatingSystemTypes = original.Linux
Windows OperatingSystemTypes = original.Windows
)
type PassNames = original.PassNames
const (
OobeSystem PassNames = original.OobeSystem
)
type ProtocolTypes = original.ProtocolTypes
const (
HTTP ProtocolTypes = original.HTTP
HTTPS ProtocolTypes = original.HTTPS
)
type ResourceIdentityType = original.ResourceIdentityType
const (
ResourceIdentityTypeNone ResourceIdentityType = original.ResourceIdentityTypeNone
ResourceIdentityTypeSystemAssigned ResourceIdentityType = original.ResourceIdentityTypeSystemAssigned
ResourceIdentityTypeSystemAssignedUserAssigned ResourceIdentityType = original.ResourceIdentityTypeSystemAssignedUserAssigned
ResourceIdentityTypeUserAssigned ResourceIdentityType = original.ResourceIdentityTypeUserAssigned
)
type ResourceSkuCapacityScaleType = original.ResourceSkuCapacityScaleType
const (
ResourceSkuCapacityScaleTypeAutomatic ResourceSkuCapacityScaleType = original.ResourceSkuCapacityScaleTypeAutomatic
ResourceSkuCapacityScaleTypeManual ResourceSkuCapacityScaleType = original.ResourceSkuCapacityScaleTypeManual
ResourceSkuCapacityScaleTypeNone ResourceSkuCapacityScaleType = original.ResourceSkuCapacityScaleTypeNone
)
type ResourceSkuRestrictionsReasonCode = original.ResourceSkuRestrictionsReasonCode
const (
NotAvailableForSubscription ResourceSkuRestrictionsReasonCode = original.NotAvailableForSubscription
QuotaID ResourceSkuRestrictionsReasonCode = original.QuotaID
)
type ResourceSkuRestrictionsType = original.ResourceSkuRestrictionsType
const (
Location ResourceSkuRestrictionsType = original.Location
Zone ResourceSkuRestrictionsType = original.Zone
)
type RollingUpgradeActionType = original.RollingUpgradeActionType
const (
Cancel RollingUpgradeActionType = original.Cancel
Start RollingUpgradeActionType = original.Start
)
type RollingUpgradeStatusCode = original.RollingUpgradeStatusCode
const (
Cancelled RollingUpgradeStatusCode = original.Cancelled
Completed RollingUpgradeStatusCode = original.Completed
Faulted RollingUpgradeStatusCode = original.Faulted
RollingForward RollingUpgradeStatusCode = original.RollingForward
)
type SettingNames = original.SettingNames
const (
AutoLogon SettingNames = original.AutoLogon
FirstLogonCommands SettingNames = original.FirstLogonCommands
)
type StatusLevelTypes = original.StatusLevelTypes
const (
Error StatusLevelTypes = original.Error
Info StatusLevelTypes = original.Info
Warning StatusLevelTypes = original.Warning
)
type StorageAccountTypes = original.StorageAccountTypes
const (
PremiumLRS StorageAccountTypes = original.PremiumLRS
StandardLRS StorageAccountTypes = original.StandardLRS
)
type UpgradeMode = original.UpgradeMode
const (
Automatic UpgradeMode = original.Automatic
Manual UpgradeMode = original.Manual
Rolling UpgradeMode = original.Rolling
)
type UpgradeOperationInvoker = original.UpgradeOperationInvoker
const (
Platform UpgradeOperationInvoker = original.Platform
Unknown UpgradeOperationInvoker = original.Unknown
User UpgradeOperationInvoker = original.User
)
type UpgradeState = original.UpgradeState
const (
UpgradeStateCancelled UpgradeState = original.UpgradeStateCancelled
UpgradeStateCompleted UpgradeState = original.UpgradeStateCompleted
UpgradeStateFaulted UpgradeState = original.UpgradeStateFaulted
UpgradeStateRollingForward UpgradeState = original.UpgradeStateRollingForward
)
type VirtualMachineEvictionPolicyTypes = original.VirtualMachineEvictionPolicyTypes
const (
Deallocate VirtualMachineEvictionPolicyTypes = original.Deallocate
Delete VirtualMachineEvictionPolicyTypes = original.Delete
)
type VirtualMachinePriorityTypes = original.VirtualMachinePriorityTypes
const (
Low VirtualMachinePriorityTypes = original.Low
Regular VirtualMachinePriorityTypes = original.Regular
)
type VirtualMachineScaleSetSkuScaleType = original.VirtualMachineScaleSetSkuScaleType
const (
VirtualMachineScaleSetSkuScaleTypeAutomatic VirtualMachineScaleSetSkuScaleType = original.VirtualMachineScaleSetSkuScaleTypeAutomatic
VirtualMachineScaleSetSkuScaleTypeNone VirtualMachineScaleSetSkuScaleType = original.VirtualMachineScaleSetSkuScaleTypeNone
)
type VirtualMachineSizeTypes = original.VirtualMachineSizeTypes
const (
BasicA0 VirtualMachineSizeTypes = original.BasicA0
BasicA1 VirtualMachineSizeTypes = original.BasicA1
BasicA2 VirtualMachineSizeTypes = original.BasicA2
BasicA3 VirtualMachineSizeTypes = original.BasicA3
BasicA4 VirtualMachineSizeTypes = original.BasicA4
StandardA0 VirtualMachineSizeTypes = original.StandardA0
StandardA1 VirtualMachineSizeTypes = original.StandardA1
StandardA10 VirtualMachineSizeTypes = original.StandardA10
StandardA11 VirtualMachineSizeTypes = original.StandardA11
StandardA1V2 VirtualMachineSizeTypes = original.StandardA1V2
StandardA2 VirtualMachineSizeTypes = original.StandardA2
StandardA2mV2 VirtualMachineSizeTypes = original.StandardA2mV2
StandardA2V2 VirtualMachineSizeTypes = original.StandardA2V2
StandardA3 VirtualMachineSizeTypes = original.StandardA3
StandardA4 VirtualMachineSizeTypes = original.StandardA4
StandardA4mV2 VirtualMachineSizeTypes = original.StandardA4mV2
StandardA4V2 VirtualMachineSizeTypes = original.StandardA4V2
StandardA5 VirtualMachineSizeTypes = original.StandardA5
StandardA6 VirtualMachineSizeTypes = original.StandardA6
StandardA7 VirtualMachineSizeTypes = original.StandardA7
StandardA8 VirtualMachineSizeTypes = original.StandardA8
StandardA8mV2 VirtualMachineSizeTypes = original.StandardA8mV2
StandardA8V2 VirtualMachineSizeTypes = original.StandardA8V2
StandardA9 VirtualMachineSizeTypes = original.StandardA9
StandardB1ms VirtualMachineSizeTypes = original.StandardB1ms
StandardB1s VirtualMachineSizeTypes = original.StandardB1s
StandardB2ms VirtualMachineSizeTypes = original.StandardB2ms
StandardB2s VirtualMachineSizeTypes = original.StandardB2s
StandardB4ms VirtualMachineSizeTypes = original.StandardB4ms
StandardB8ms VirtualMachineSizeTypes = original.StandardB8ms
StandardD1 VirtualMachineSizeTypes = original.StandardD1
StandardD11 VirtualMachineSizeTypes = original.StandardD11
StandardD11V2 VirtualMachineSizeTypes = original.StandardD11V2
StandardD12 VirtualMachineSizeTypes = original.StandardD12
StandardD12V2 VirtualMachineSizeTypes = original.StandardD12V2
StandardD13 VirtualMachineSizeTypes = original.StandardD13
StandardD13V2 VirtualMachineSizeTypes = original.StandardD13V2
StandardD14 VirtualMachineSizeTypes = original.StandardD14
StandardD14V2 VirtualMachineSizeTypes = original.StandardD14V2
StandardD15V2 VirtualMachineSizeTypes = original.StandardD15V2
StandardD16sV3 VirtualMachineSizeTypes = original.StandardD16sV3
StandardD16V3 VirtualMachineSizeTypes = original.StandardD16V3
StandardD1V2 VirtualMachineSizeTypes = original.StandardD1V2
StandardD2 VirtualMachineSizeTypes = original.StandardD2
StandardD2sV3 VirtualMachineSizeTypes = original.StandardD2sV3
StandardD2V2 VirtualMachineSizeTypes = original.StandardD2V2
StandardD2V3 VirtualMachineSizeTypes = original.StandardD2V3
StandardD3 VirtualMachineSizeTypes = original.StandardD3
StandardD32sV3 VirtualMachineSizeTypes = original.StandardD32sV3
StandardD32V3 VirtualMachineSizeTypes = original.StandardD32V3
StandardD3V2 VirtualMachineSizeTypes = original.StandardD3V2
StandardD4 VirtualMachineSizeTypes = original.StandardD4
StandardD4sV3 VirtualMachineSizeTypes = original.StandardD4sV3
StandardD4V2 VirtualMachineSizeTypes = original.StandardD4V2
StandardD4V3 VirtualMachineSizeTypes = original.StandardD4V3
StandardD5V2 VirtualMachineSizeTypes = original.StandardD5V2
StandardD64sV3 VirtualMachineSizeTypes = original.StandardD64sV3
StandardD64V3 VirtualMachineSizeTypes = original.StandardD64V3
StandardD8sV3 VirtualMachineSizeTypes = original.StandardD8sV3
StandardD8V3 VirtualMachineSizeTypes = original.StandardD8V3
StandardDS1 VirtualMachineSizeTypes = original.StandardDS1
StandardDS11 VirtualMachineSizeTypes = original.StandardDS11
StandardDS11V2 VirtualMachineSizeTypes = original.StandardDS11V2
StandardDS12 VirtualMachineSizeTypes = original.StandardDS12
StandardDS12V2 VirtualMachineSizeTypes = original.StandardDS12V2
StandardDS13 VirtualMachineSizeTypes = original.StandardDS13
StandardDS132V2 VirtualMachineSizeTypes = original.StandardDS132V2
StandardDS134V2 VirtualMachineSizeTypes = original.StandardDS134V2
StandardDS13V2 VirtualMachineSizeTypes = original.StandardDS13V2
StandardDS14 VirtualMachineSizeTypes = original.StandardDS14
StandardDS144V2 VirtualMachineSizeTypes = original.StandardDS144V2
StandardDS148V2 VirtualMachineSizeTypes = original.StandardDS148V2
StandardDS14V2 VirtualMachineSizeTypes = original.StandardDS14V2
StandardDS15V2 VirtualMachineSizeTypes = original.StandardDS15V2
StandardDS1V2 VirtualMachineSizeTypes = original.StandardDS1V2
StandardDS2 VirtualMachineSizeTypes = original.StandardDS2
StandardDS2V2 VirtualMachineSizeTypes = original.StandardDS2V2
StandardDS3 VirtualMachineSizeTypes = original.StandardDS3
StandardDS3V2 VirtualMachineSizeTypes = original.StandardDS3V2
StandardDS4 VirtualMachineSizeTypes = original.StandardDS4
StandardDS4V2 VirtualMachineSizeTypes = original.StandardDS4V2
StandardDS5V2 VirtualMachineSizeTypes = original.StandardDS5V2
StandardE16sV3 VirtualMachineSizeTypes = original.StandardE16sV3
StandardE16V3 VirtualMachineSizeTypes = original.StandardE16V3
StandardE2sV3 VirtualMachineSizeTypes = original.StandardE2sV3
StandardE2V3 VirtualMachineSizeTypes = original.StandardE2V3
StandardE3216V3 VirtualMachineSizeTypes = original.StandardE3216V3
StandardE328sV3 VirtualMachineSizeTypes = original.StandardE328sV3
StandardE32sV3 VirtualMachineSizeTypes = original.StandardE32sV3
StandardE32V3 VirtualMachineSizeTypes = original.StandardE32V3
StandardE4sV3 VirtualMachineSizeTypes = original.StandardE4sV3
StandardE4V3 VirtualMachineSizeTypes = original.StandardE4V3
StandardE6416sV3 VirtualMachineSizeTypes = original.StandardE6416sV3
StandardE6432sV3 VirtualMachineSizeTypes = original.StandardE6432sV3
StandardE64sV3 VirtualMachineSizeTypes = original.StandardE64sV3
StandardE64V3 VirtualMachineSizeTypes = original.StandardE64V3
StandardE8sV3 VirtualMachineSizeTypes = original.StandardE8sV3
StandardE8V3 VirtualMachineSizeTypes = original.StandardE8V3
StandardF1 VirtualMachineSizeTypes = original.StandardF1
StandardF16 VirtualMachineSizeTypes = original.StandardF16
StandardF16s VirtualMachineSizeTypes = original.StandardF16s
StandardF16sV2 VirtualMachineSizeTypes = original.StandardF16sV2
StandardF1s VirtualMachineSizeTypes = original.StandardF1s
StandardF2 VirtualMachineSizeTypes = original.StandardF2
StandardF2s VirtualMachineSizeTypes = original.StandardF2s
StandardF2sV2 VirtualMachineSizeTypes = original.StandardF2sV2
StandardF32sV2 VirtualMachineSizeTypes = original.StandardF32sV2
StandardF4 VirtualMachineSizeTypes = original.StandardF4
StandardF4s VirtualMachineSizeTypes = original.StandardF4s
StandardF4sV2 VirtualMachineSizeTypes = original.StandardF4sV2
StandardF64sV2 VirtualMachineSizeTypes = original.StandardF64sV2
StandardF72sV2 VirtualMachineSizeTypes = original.StandardF72sV2
StandardF8 VirtualMachineSizeTypes = original.StandardF8
StandardF8s VirtualMachineSizeTypes = original.StandardF8s
StandardF8sV2 VirtualMachineSizeTypes = original.StandardF8sV2
StandardG1 VirtualMachineSizeTypes = original.StandardG1
StandardG2 VirtualMachineSizeTypes = original.StandardG2
StandardG3 VirtualMachineSizeTypes = original.StandardG3
StandardG4 VirtualMachineSizeTypes = original.StandardG4
StandardG5 VirtualMachineSizeTypes = original.StandardG5
StandardGS1 VirtualMachineSizeTypes = original.StandardGS1
StandardGS2 VirtualMachineSizeTypes = original.StandardGS2
StandardGS3 VirtualMachineSizeTypes = original.StandardGS3
StandardGS4 VirtualMachineSizeTypes = original.StandardGS4
StandardGS44 VirtualMachineSizeTypes = original.StandardGS44
StandardGS48 VirtualMachineSizeTypes = original.StandardGS48
StandardGS5 VirtualMachineSizeTypes = original.StandardGS5
StandardGS516 VirtualMachineSizeTypes = original.StandardGS516
StandardGS58 VirtualMachineSizeTypes = original.StandardGS58
StandardH16 VirtualMachineSizeTypes = original.StandardH16
StandardH16m VirtualMachineSizeTypes = original.StandardH16m
StandardH16mr VirtualMachineSizeTypes = original.StandardH16mr
StandardH16r VirtualMachineSizeTypes = original.StandardH16r
StandardH8 VirtualMachineSizeTypes = original.StandardH8
StandardH8m VirtualMachineSizeTypes = original.StandardH8m
StandardL16s VirtualMachineSizeTypes = original.StandardL16s
StandardL32s VirtualMachineSizeTypes = original.StandardL32s
StandardL4s VirtualMachineSizeTypes = original.StandardL4s
StandardL8s VirtualMachineSizeTypes = original.StandardL8s
StandardM12832ms VirtualMachineSizeTypes = original.StandardM12832ms
StandardM12864ms VirtualMachineSizeTypes = original.StandardM12864ms
StandardM128ms VirtualMachineSizeTypes = original.StandardM128ms
StandardM128s VirtualMachineSizeTypes = original.StandardM128s
StandardM6416ms VirtualMachineSizeTypes = original.StandardM6416ms
StandardM6432ms VirtualMachineSizeTypes = original.StandardM6432ms
StandardM64ms VirtualMachineSizeTypes = original.StandardM64ms
StandardM64s VirtualMachineSizeTypes = original.StandardM64s
StandardNC12 VirtualMachineSizeTypes = original.StandardNC12
StandardNC12sV2 VirtualMachineSizeTypes = original.StandardNC12sV2
StandardNC12sV3 VirtualMachineSizeTypes = original.StandardNC12sV3
StandardNC24 VirtualMachineSizeTypes = original.StandardNC24
StandardNC24r VirtualMachineSizeTypes = original.StandardNC24r
StandardNC24rsV2 VirtualMachineSizeTypes = original.StandardNC24rsV2
StandardNC24rsV3 VirtualMachineSizeTypes = original.StandardNC24rsV3
StandardNC24sV2 VirtualMachineSizeTypes = original.StandardNC24sV2
StandardNC24sV3 VirtualMachineSizeTypes = original.StandardNC24sV3
StandardNC6 VirtualMachineSizeTypes = original.StandardNC6
StandardNC6sV2 VirtualMachineSizeTypes = original.StandardNC6sV2
StandardNC6sV3 VirtualMachineSizeTypes = original.StandardNC6sV3
StandardND12s VirtualMachineSizeTypes = original.StandardND12s
StandardND24rs VirtualMachineSizeTypes = original.StandardND24rs
StandardND24s VirtualMachineSizeTypes = original.StandardND24s
StandardND6s VirtualMachineSizeTypes = original.StandardND6s
StandardNV12 VirtualMachineSizeTypes = original.StandardNV12
StandardNV24 VirtualMachineSizeTypes = original.StandardNV24
StandardNV6 VirtualMachineSizeTypes = original.StandardNV6
)
type APIEntityReference = original.APIEntityReference
type APIError = original.APIError
type APIErrorBase = original.APIErrorBase
type AccessURI = original.AccessURI
type AccessURIOutput = original.AccessURIOutput
type AccessURIRaw = original.AccessURIRaw
type AdditionalUnattendContent = original.AdditionalUnattendContent
type AutoOSUpgradePolicy = original.AutoOSUpgradePolicy
type AvailabilitySet = original.AvailabilitySet
type AvailabilitySetListResult = original.AvailabilitySetListResult
type AvailabilitySetListResultIterator = original.AvailabilitySetListResultIterator
type AvailabilitySetListResultPage = original.AvailabilitySetListResultPage
type AvailabilitySetProperties = original.AvailabilitySetProperties
type AvailabilitySetUpdate = original.AvailabilitySetUpdate
type AvailabilitySetsClient = original.AvailabilitySetsClient
type BaseClient = original.BaseClient
type BootDiagnostics = original.BootDiagnostics
type BootDiagnosticsInstanceView = original.BootDiagnosticsInstanceView
type CreationData = original.CreationData
type DataDisk = original.DataDisk
type DataDiskImage = original.DataDiskImage
type DiagnosticsProfile = original.DiagnosticsProfile
type Disk = original.Disk
type DiskEncryptionSettings = original.DiskEncryptionSettings
type DiskInstanceView = original.DiskInstanceView
type DiskList = original.DiskList
type DiskListIterator = original.DiskListIterator
type DiskListPage = original.DiskListPage
type DiskProperties = original.DiskProperties
type DiskSku = original.DiskSku
type DiskUpdate = original.DiskUpdate
type DiskUpdateProperties = original.DiskUpdateProperties
type DisksClient = original.DisksClient
type DisksCreateOrUpdateFuture = original.DisksCreateOrUpdateFuture
type DisksDeleteFuture = original.DisksDeleteFuture
type DisksGrantAccessFuture = original.DisksGrantAccessFuture
type DisksRevokeAccessFuture = original.DisksRevokeAccessFuture
type DisksUpdateFuture = original.DisksUpdateFuture
type EncryptionSettings = original.EncryptionSettings
type GrantAccessData = original.GrantAccessData
type HardwareProfile = original.HardwareProfile
type Image = original.Image
type ImageDataDisk = original.ImageDataDisk
type ImageDiskReference = original.ImageDiskReference
type ImageListResult = original.ImageListResult
type ImageListResultIterator = original.ImageListResultIterator
type ImageListResultPage = original.ImageListResultPage
type ImageOSDisk = original.ImageOSDisk
type ImageProperties = original.ImageProperties
type ImageReference = original.ImageReference
type ImageStorageProfile = original.ImageStorageProfile
type ImageUpdate = original.ImageUpdate
type ImagesClient = original.ImagesClient
type ImagesCreateOrUpdateFuture = original.ImagesCreateOrUpdateFuture
type ImagesDeleteFuture = original.ImagesDeleteFuture
type ImagesUpdateFuture = original.ImagesUpdateFuture
type InnerError = original.InnerError
type InstanceViewStatus = original.InstanceViewStatus
type KeyVaultAndKeyReference = original.KeyVaultAndKeyReference
type KeyVaultAndSecretReference = original.KeyVaultAndSecretReference
type KeyVaultKeyReference = original.KeyVaultKeyReference
type KeyVaultSecretReference = original.KeyVaultSecretReference
type LinuxConfiguration = original.LinuxConfiguration
type ListUsagesResult = original.ListUsagesResult
type ListUsagesResultIterator = original.ListUsagesResultIterator
type ListUsagesResultPage = original.ListUsagesResultPage
type ListVirtualMachineExtensionImage = original.ListVirtualMachineExtensionImage
type ListVirtualMachineImageResource = original.ListVirtualMachineImageResource
type LogAnalyticsClient = original.LogAnalyticsClient
type LogAnalyticsExportRequestRateByIntervalFuture = original.LogAnalyticsExportRequestRateByIntervalFuture
type LogAnalyticsExportThrottledRequestsFuture = original.LogAnalyticsExportThrottledRequestsFuture
type LogAnalyticsInputBase = original.LogAnalyticsInputBase
type LogAnalyticsOperationResult = original.LogAnalyticsOperationResult
type LogAnalyticsOutput = original.LogAnalyticsOutput
type LongRunningOperationProperties = original.LongRunningOperationProperties
type MaintenanceRedeployStatus = original.MaintenanceRedeployStatus
type ManagedDiskParameters = original.ManagedDiskParameters
type NetworkInterfaceReference = original.NetworkInterfaceReference
type NetworkInterfaceReferenceProperties = original.NetworkInterfaceReferenceProperties
type NetworkProfile = original.NetworkProfile
type OSDisk = original.OSDisk
type OSDiskImage = original.OSDiskImage
type OSProfile = original.OSProfile
type OperationListResult = original.OperationListResult
type OperationStatusResponse = original.OperationStatusResponse
type OperationValue = original.OperationValue
type OperationValueDisplay = original.OperationValueDisplay
type OperationsClient = original.OperationsClient
type Plan = original.Plan
type PurchasePlan = original.PurchasePlan
type RecoveryWalkResponse = original.RecoveryWalkResponse
type RequestRateByIntervalInput = original.RequestRateByIntervalInput
type Resource = original.Resource
type ResourceSku = original.ResourceSku
type ResourceSkuCapabilities = original.ResourceSkuCapabilities
type ResourceSkuCapacity = original.ResourceSkuCapacity
type ResourceSkuCosts = original.ResourceSkuCosts
type ResourceSkuLocationInfo = original.ResourceSkuLocationInfo
type ResourceSkuRestrictionInfo = original.ResourceSkuRestrictionInfo
type ResourceSkuRestrictions = original.ResourceSkuRestrictions
type ResourceSkusClient = original.ResourceSkusClient
type ResourceSkusResult = original.ResourceSkusResult
type ResourceSkusResultIterator = original.ResourceSkusResultIterator
type ResourceSkusResultPage = original.ResourceSkusResultPage
type ResourceUpdate = original.ResourceUpdate
type RollbackStatusInfo = original.RollbackStatusInfo
type RollingUpgradePolicy = original.RollingUpgradePolicy
type RollingUpgradeProgressInfo = original.RollingUpgradeProgressInfo
type RollingUpgradeRunningStatus = original.RollingUpgradeRunningStatus
type RollingUpgradeStatusInfo = original.RollingUpgradeStatusInfo
type RollingUpgradeStatusInfoProperties = original.RollingUpgradeStatusInfoProperties
type RunCommandDocument = original.RunCommandDocument
type RunCommandDocumentBase = original.RunCommandDocumentBase
type RunCommandInput = original.RunCommandInput
type RunCommandInputParameter = original.RunCommandInputParameter
type RunCommandListResult = original.RunCommandListResult
type RunCommandListResultIterator = original.RunCommandListResultIterator
type RunCommandListResultPage = original.RunCommandListResultPage
type RunCommandParameterDefinition = original.RunCommandParameterDefinition
type RunCommandResult = original.RunCommandResult
type RunCommandResultProperties = original.RunCommandResultProperties
type SSHConfiguration = original.SSHConfiguration
type SSHPublicKey = original.SSHPublicKey
type Sku = original.Sku
type Snapshot = original.Snapshot
type SnapshotList = original.SnapshotList
type SnapshotListIterator = original.SnapshotListIterator
type SnapshotListPage = original.SnapshotListPage
type SnapshotUpdate = original.SnapshotUpdate
type SnapshotsClient = original.SnapshotsClient
type SnapshotsCreateOrUpdateFuture = original.SnapshotsCreateOrUpdateFuture
type SnapshotsDeleteFuture = original.SnapshotsDeleteFuture
type SnapshotsGrantAccessFuture = original.SnapshotsGrantAccessFuture
type SnapshotsRevokeAccessFuture = original.SnapshotsRevokeAccessFuture
type SnapshotsUpdateFuture = original.SnapshotsUpdateFuture
type SourceVault = original.SourceVault
type StorageProfile = original.StorageProfile
type SubResource = original.SubResource
type SubResourceReadOnly = original.SubResourceReadOnly
type ThrottledRequestsInput = original.ThrottledRequestsInput
type UpdateResource = original.UpdateResource
type UpgradeOperationHistoricalStatusInfo = original.UpgradeOperationHistoricalStatusInfo
type UpgradeOperationHistoricalStatusInfoProperties = original.UpgradeOperationHistoricalStatusInfoProperties
type UpgradeOperationHistoryStatus = original.UpgradeOperationHistoryStatus
type UpgradePolicy = original.UpgradePolicy
type Usage = original.Usage
type UsageClient = original.UsageClient
type UsageName = original.UsageName
type VaultCertificate = original.VaultCertificate
type VaultSecretGroup = original.VaultSecretGroup
type VirtualHardDisk = original.VirtualHardDisk
type VirtualMachine = original.VirtualMachine
type VirtualMachineAgentInstanceView = original.VirtualMachineAgentInstanceView
type VirtualMachineCaptureParameters = original.VirtualMachineCaptureParameters
type VirtualMachineCaptureResult = original.VirtualMachineCaptureResult
type VirtualMachineCaptureResultProperties = original.VirtualMachineCaptureResultProperties
type VirtualMachineExtension = original.VirtualMachineExtension
type VirtualMachineExtensionHandlerInstanceView = original.VirtualMachineExtensionHandlerInstanceView
type VirtualMachineExtensionImage = original.VirtualMachineExtensionImage
type VirtualMachineExtensionImageProperties = original.VirtualMachineExtensionImageProperties
type VirtualMachineExtensionImagesClient = original.VirtualMachineExtensionImagesClient
type VirtualMachineExtensionInstanceView = original.VirtualMachineExtensionInstanceView
type VirtualMachineExtensionProperties = original.VirtualMachineExtensionProperties
type VirtualMachineExtensionUpdate = original.VirtualMachineExtensionUpdate
type VirtualMachineExtensionUpdateProperties = original.VirtualMachineExtensionUpdateProperties
type VirtualMachineExtensionsClient = original.VirtualMachineExtensionsClient
type VirtualMachineExtensionsCreateOrUpdateFuture = original.VirtualMachineExtensionsCreateOrUpdateFuture
type VirtualMachineExtensionsDeleteFuture = original.VirtualMachineExtensionsDeleteFuture
type VirtualMachineExtensionsListResult = original.VirtualMachineExtensionsListResult
type VirtualMachineExtensionsUpdateFuture = original.VirtualMachineExtensionsUpdateFuture
type VirtualMachineHealthStatus = original.VirtualMachineHealthStatus
type VirtualMachineIdentity = original.VirtualMachineIdentity
type VirtualMachineImage = original.VirtualMachineImage
type VirtualMachineImageProperties = original.VirtualMachineImageProperties
type VirtualMachineImageResource = original.VirtualMachineImageResource
type VirtualMachineImagesClient = original.VirtualMachineImagesClient
type VirtualMachineInstanceView = original.VirtualMachineInstanceView
type VirtualMachineListResult = original.VirtualMachineListResult
type VirtualMachineListResultIterator = original.VirtualMachineListResultIterator
type VirtualMachineListResultPage = original.VirtualMachineListResultPage
type VirtualMachineProperties = original.VirtualMachineProperties
type VirtualMachineRunCommandsClient = original.VirtualMachineRunCommandsClient
type VirtualMachineScaleSet = original.VirtualMachineScaleSet
type VirtualMachineScaleSetDataDisk = original.VirtualMachineScaleSetDataDisk
type VirtualMachineScaleSetExtension = original.VirtualMachineScaleSetExtension
type VirtualMachineScaleSetExtensionListResult = original.VirtualMachineScaleSetExtensionListResult
type VirtualMachineScaleSetExtensionListResultIterator = original.VirtualMachineScaleSetExtensionListResultIterator
type VirtualMachineScaleSetExtensionListResultPage = original.VirtualMachineScaleSetExtensionListResultPage
type VirtualMachineScaleSetExtensionProfile = original.VirtualMachineScaleSetExtensionProfile
type VirtualMachineScaleSetExtensionProperties = original.VirtualMachineScaleSetExtensionProperties
type VirtualMachineScaleSetExtensionsClient = original.VirtualMachineScaleSetExtensionsClient
type VirtualMachineScaleSetExtensionsCreateOrUpdateFuture = original.VirtualMachineScaleSetExtensionsCreateOrUpdateFuture
type VirtualMachineScaleSetExtensionsDeleteFuture = original.VirtualMachineScaleSetExtensionsDeleteFuture
type VirtualMachineScaleSetIPConfiguration = original.VirtualMachineScaleSetIPConfiguration
type VirtualMachineScaleSetIPConfigurationProperties = original.VirtualMachineScaleSetIPConfigurationProperties
type VirtualMachineScaleSetIdentity = original.VirtualMachineScaleSetIdentity
type VirtualMachineScaleSetInstanceView = original.VirtualMachineScaleSetInstanceView
type VirtualMachineScaleSetInstanceViewStatusesSummary = original.VirtualMachineScaleSetInstanceViewStatusesSummary
type VirtualMachineScaleSetListOSUpgradeHistory = original.VirtualMachineScaleSetListOSUpgradeHistory
type VirtualMachineScaleSetListOSUpgradeHistoryIterator = original.VirtualMachineScaleSetListOSUpgradeHistoryIterator
type VirtualMachineScaleSetListOSUpgradeHistoryPage = original.VirtualMachineScaleSetListOSUpgradeHistoryPage
type VirtualMachineScaleSetListResult = original.VirtualMachineScaleSetListResult
type VirtualMachineScaleSetListResultIterator = original.VirtualMachineScaleSetListResultIterator
type VirtualMachineScaleSetListResultPage = original.VirtualMachineScaleSetListResultPage
type VirtualMachineScaleSetListSkusResult = original.VirtualMachineScaleSetListSkusResult
type VirtualMachineScaleSetListSkusResultIterator = original.VirtualMachineScaleSetListSkusResultIterator
type VirtualMachineScaleSetListSkusResultPage = original.VirtualMachineScaleSetListSkusResultPage
type VirtualMachineScaleSetListWithLinkResult = original.VirtualMachineScaleSetListWithLinkResult
type VirtualMachineScaleSetListWithLinkResultIterator = original.VirtualMachineScaleSetListWithLinkResultIterator
type VirtualMachineScaleSetListWithLinkResultPage = original.VirtualMachineScaleSetListWithLinkResultPage
type VirtualMachineScaleSetManagedDiskParameters = original.VirtualMachineScaleSetManagedDiskParameters
type VirtualMachineScaleSetNetworkConfiguration = original.VirtualMachineScaleSetNetworkConfiguration
type VirtualMachineScaleSetNetworkConfigurationDNSSettings = original.VirtualMachineScaleSetNetworkConfigurationDNSSettings
type VirtualMachineScaleSetNetworkConfigurationProperties = original.VirtualMachineScaleSetNetworkConfigurationProperties
type VirtualMachineScaleSetNetworkProfile = original.VirtualMachineScaleSetNetworkProfile
type VirtualMachineScaleSetOSDisk = original.VirtualMachineScaleSetOSDisk
type VirtualMachineScaleSetOSProfile = original.VirtualMachineScaleSetOSProfile
type VirtualMachineScaleSetProperties = original.VirtualMachineScaleSetProperties
type VirtualMachineScaleSetPublicIPAddressConfiguration = original.VirtualMachineScaleSetPublicIPAddressConfiguration
type VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings = original.VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings
type VirtualMachineScaleSetPublicIPAddressConfigurationProperties = original.VirtualMachineScaleSetPublicIPAddressConfigurationProperties
type VirtualMachineScaleSetRollingUpgradesCancelFuture = original.VirtualMachineScaleSetRollingUpgradesCancelFuture
type VirtualMachineScaleSetRollingUpgradesClient = original.VirtualMachineScaleSetRollingUpgradesClient
type VirtualMachineScaleSetRollingUpgradesStartOSUpgradeFuture = original.VirtualMachineScaleSetRollingUpgradesStartOSUpgradeFuture
type VirtualMachineScaleSetSku = original.VirtualMachineScaleSetSku
type VirtualMachineScaleSetSkuCapacity = original.VirtualMachineScaleSetSkuCapacity
type VirtualMachineScaleSetStorageProfile = original.VirtualMachineScaleSetStorageProfile
type VirtualMachineScaleSetUpdate = original.VirtualMachineScaleSetUpdate
type VirtualMachineScaleSetUpdateIPConfiguration = original.VirtualMachineScaleSetUpdateIPConfiguration
type VirtualMachineScaleSetUpdateIPConfigurationProperties = original.VirtualMachineScaleSetUpdateIPConfigurationProperties
type VirtualMachineScaleSetUpdateNetworkConfiguration = original.VirtualMachineScaleSetUpdateNetworkConfiguration
type VirtualMachineScaleSetUpdateNetworkConfigurationProperties = original.VirtualMachineScaleSetUpdateNetworkConfigurationProperties
type VirtualMachineScaleSetUpdateNetworkProfile = original.VirtualMachineScaleSetUpdateNetworkProfile
type VirtualMachineScaleSetUpdateOSDisk = original.VirtualMachineScaleSetUpdateOSDisk
type VirtualMachineScaleSetUpdateOSProfile = original.VirtualMachineScaleSetUpdateOSProfile
type VirtualMachineScaleSetUpdateProperties = original.VirtualMachineScaleSetUpdateProperties
type VirtualMachineScaleSetUpdatePublicIPAddressConfiguration = original.VirtualMachineScaleSetUpdatePublicIPAddressConfiguration
type VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties = original.VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties
type VirtualMachineScaleSetUpdateStorageProfile = original.VirtualMachineScaleSetUpdateStorageProfile
type VirtualMachineScaleSetUpdateVMProfile = original.VirtualMachineScaleSetUpdateVMProfile
type VirtualMachineScaleSetVM = original.VirtualMachineScaleSetVM
type VirtualMachineScaleSetVMExtensionsSummary = original.VirtualMachineScaleSetVMExtensionsSummary
type VirtualMachineScaleSetVMInstanceIDs = original.VirtualMachineScaleSetVMInstanceIDs
type VirtualMachineScaleSetVMInstanceRequiredIDs = original.VirtualMachineScaleSetVMInstanceRequiredIDs
type VirtualMachineScaleSetVMInstanceView = original.VirtualMachineScaleSetVMInstanceView
type VirtualMachineScaleSetVMListResult = original.VirtualMachineScaleSetVMListResult
type VirtualMachineScaleSetVMListResultIterator = original.VirtualMachineScaleSetVMListResultIterator
type VirtualMachineScaleSetVMListResultPage = original.VirtualMachineScaleSetVMListResultPage
type VirtualMachineScaleSetVMProfile = original.VirtualMachineScaleSetVMProfile
type VirtualMachineScaleSetVMProperties = original.VirtualMachineScaleSetVMProperties
type VirtualMachineScaleSetVMsClient = original.VirtualMachineScaleSetVMsClient
type VirtualMachineScaleSetVMsDeallocateFuture = original.VirtualMachineScaleSetVMsDeallocateFuture
type VirtualMachineScaleSetVMsDeleteFuture = original.VirtualMachineScaleSetVMsDeleteFuture
type VirtualMachineScaleSetVMsPerformMaintenanceFuture = original.VirtualMachineScaleSetVMsPerformMaintenanceFuture
type VirtualMachineScaleSetVMsPowerOffFuture = original.VirtualMachineScaleSetVMsPowerOffFuture
type VirtualMachineScaleSetVMsRedeployFuture = original.VirtualMachineScaleSetVMsRedeployFuture
type VirtualMachineScaleSetVMsReimageAllFuture = original.VirtualMachineScaleSetVMsReimageAllFuture
type VirtualMachineScaleSetVMsReimageFuture = original.VirtualMachineScaleSetVMsReimageFuture
type VirtualMachineScaleSetVMsRestartFuture = original.VirtualMachineScaleSetVMsRestartFuture
type VirtualMachineScaleSetVMsStartFuture = original.VirtualMachineScaleSetVMsStartFuture
type VirtualMachineScaleSetVMsUpdateFuture = original.VirtualMachineScaleSetVMsUpdateFuture
type VirtualMachineScaleSetsClient = original.VirtualMachineScaleSetsClient
type VirtualMachineScaleSetsCreateOrUpdateFuture = original.VirtualMachineScaleSetsCreateOrUpdateFuture
type VirtualMachineScaleSetsDeallocateFuture = original.VirtualMachineScaleSetsDeallocateFuture
type VirtualMachineScaleSetsDeleteFuture = original.VirtualMachineScaleSetsDeleteFuture
type VirtualMachineScaleSetsDeleteInstancesFuture = original.VirtualMachineScaleSetsDeleteInstancesFuture
type VirtualMachineScaleSetsPerformMaintenanceFuture = original.VirtualMachineScaleSetsPerformMaintenanceFuture
type VirtualMachineScaleSetsPowerOffFuture = original.VirtualMachineScaleSetsPowerOffFuture
type VirtualMachineScaleSetsRedeployFuture = original.VirtualMachineScaleSetsRedeployFuture
type VirtualMachineScaleSetsReimageAllFuture = original.VirtualMachineScaleSetsReimageAllFuture
type VirtualMachineScaleSetsReimageFuture = original.VirtualMachineScaleSetsReimageFuture
type VirtualMachineScaleSetsRestartFuture = original.VirtualMachineScaleSetsRestartFuture
type VirtualMachineScaleSetsStartFuture = original.VirtualMachineScaleSetsStartFuture
type VirtualMachineScaleSetsUpdateFuture = original.VirtualMachineScaleSetsUpdateFuture
type VirtualMachineScaleSetsUpdateInstancesFuture = original.VirtualMachineScaleSetsUpdateInstancesFuture
type VirtualMachineSize = original.VirtualMachineSize
type VirtualMachineSizeListResult = original.VirtualMachineSizeListResult
type VirtualMachineSizesClient = original.VirtualMachineSizesClient
type VirtualMachineStatusCodeCount = original.VirtualMachineStatusCodeCount
type VirtualMachineUpdate = original.VirtualMachineUpdate
type VirtualMachinesCaptureFuture = original.VirtualMachinesCaptureFuture
type VirtualMachinesClient = original.VirtualMachinesClient
type VirtualMachinesConvertToManagedDisksFuture = original.VirtualMachinesConvertToManagedDisksFuture
type VirtualMachinesCreateOrUpdateFuture = original.VirtualMachinesCreateOrUpdateFuture
type VirtualMachinesDeallocateFuture = original.VirtualMachinesDeallocateFuture
type VirtualMachinesDeleteFuture = original.VirtualMachinesDeleteFuture
type VirtualMachinesPerformMaintenanceFuture = original.VirtualMachinesPerformMaintenanceFuture
type VirtualMachinesPowerOffFuture = original.VirtualMachinesPowerOffFuture
type VirtualMachinesRedeployFuture = original.VirtualMachinesRedeployFuture
type VirtualMachinesRestartFuture = original.VirtualMachinesRestartFuture
type VirtualMachinesRunCommandFuture = original.VirtualMachinesRunCommandFuture
type VirtualMachinesStartFuture = original.VirtualMachinesStartFuture
type VirtualMachinesUpdateFuture = original.VirtualMachinesUpdateFuture
type WinRMConfiguration = original.WinRMConfiguration
type WinRMListener = original.WinRMListener
type WindowsConfiguration = original.WindowsConfiguration
func New(subscriptionID string) BaseClient {
return original.New(subscriptionID)
}
func NewAvailabilitySetListResultIterator(page AvailabilitySetListResultPage) AvailabilitySetListResultIterator {
return original.NewAvailabilitySetListResultIterator(page)
}
func NewAvailabilitySetListResultPage(cur AvailabilitySetListResult, getNextPage func(context.Context, AvailabilitySetListResult) (AvailabilitySetListResult, error)) AvailabilitySetListResultPage {
return original.NewAvailabilitySetListResultPage(cur, getNextPage)
}
func NewAvailabilitySetsClient(subscriptionID string) AvailabilitySetsClient {
return original.NewAvailabilitySetsClient(subscriptionID)
}
func NewAvailabilitySetsClientWithBaseURI(baseURI string, subscriptionID string) AvailabilitySetsClient {
return original.NewAvailabilitySetsClientWithBaseURI(baseURI, subscriptionID)
}
func NewDiskListIterator(page DiskListPage) DiskListIterator {
return original.NewDiskListIterator(page)
}
func NewDiskListPage(cur DiskList, getNextPage func(context.Context, DiskList) (DiskList, error)) DiskListPage {
return original.NewDiskListPage(cur, getNextPage)
}
func NewDisksClient(subscriptionID string) DisksClient {
return original.NewDisksClient(subscriptionID)
}
func NewDisksClientWithBaseURI(baseURI string, subscriptionID string) DisksClient {
return original.NewDisksClientWithBaseURI(baseURI, subscriptionID)
}
func NewImageListResultIterator(page ImageListResultPage) ImageListResultIterator {
return original.NewImageListResultIterator(page)
}
func NewImageListResultPage(cur ImageListResult, getNextPage func(context.Context, ImageListResult) (ImageListResult, error)) ImageListResultPage {
return original.NewImageListResultPage(cur, getNextPage)
}
func NewImagesClient(subscriptionID string) ImagesClient {
return original.NewImagesClient(subscriptionID)
}
func NewImagesClientWithBaseURI(baseURI string, subscriptionID string) ImagesClient {
return original.NewImagesClientWithBaseURI(baseURI, subscriptionID)
}
func NewListUsagesResultIterator(page ListUsagesResultPage) ListUsagesResultIterator {
return original.NewListUsagesResultIterator(page)
}
func NewListUsagesResultPage(cur ListUsagesResult, getNextPage func(context.Context, ListUsagesResult) (ListUsagesResult, error)) ListUsagesResultPage {
return original.NewListUsagesResultPage(cur, getNextPage)
}
func NewLogAnalyticsClient(subscriptionID string) LogAnalyticsClient {
return original.NewLogAnalyticsClient(subscriptionID)
}
func NewLogAnalyticsClientWithBaseURI(baseURI string, subscriptionID string) LogAnalyticsClient {
return original.NewLogAnalyticsClientWithBaseURI(baseURI, subscriptionID)
}
func NewOperationsClient(subscriptionID string) OperationsClient {
return original.NewOperationsClient(subscriptionID)
}
func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {
return original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)
}
func NewResourceSkusClient(subscriptionID string) ResourceSkusClient {
return original.NewResourceSkusClient(subscriptionID)
}
func NewResourceSkusClientWithBaseURI(baseURI string, subscriptionID string) ResourceSkusClient {
return original.NewResourceSkusClientWithBaseURI(baseURI, subscriptionID)
}
func NewResourceSkusResultIterator(page ResourceSkusResultPage) ResourceSkusResultIterator {
return original.NewResourceSkusResultIterator(page)
}
func NewResourceSkusResultPage(cur ResourceSkusResult, getNextPage func(context.Context, ResourceSkusResult) (ResourceSkusResult, error)) ResourceSkusResultPage {
return original.NewResourceSkusResultPage(cur, getNextPage)
}
func NewRunCommandListResultIterator(page RunCommandListResultPage) RunCommandListResultIterator {
return original.NewRunCommandListResultIterator(page)
}
func NewRunCommandListResultPage(cur RunCommandListResult, getNextPage func(context.Context, RunCommandListResult) (RunCommandListResult, error)) RunCommandListResultPage {
return original.NewRunCommandListResultPage(cur, getNextPage)
}
func NewSnapshotListIterator(page SnapshotListPage) SnapshotListIterator {
return original.NewSnapshotListIterator(page)
}
func NewSnapshotListPage(cur SnapshotList, getNextPage func(context.Context, SnapshotList) (SnapshotList, error)) SnapshotListPage {
return original.NewSnapshotListPage(cur, getNextPage)
}
func NewSnapshotsClient(subscriptionID string) SnapshotsClient {
return original.NewSnapshotsClient(subscriptionID)
}
func NewSnapshotsClientWithBaseURI(baseURI string, subscriptionID string) SnapshotsClient {
return original.NewSnapshotsClientWithBaseURI(baseURI, subscriptionID)
}
func NewUsageClient(subscriptionID string) UsageClient {
return original.NewUsageClient(subscriptionID)
}
func NewUsageClientWithBaseURI(baseURI string, subscriptionID string) UsageClient {
return original.NewUsageClientWithBaseURI(baseURI, subscriptionID)
}
func NewVirtualMachineExtensionImagesClient(subscriptionID string) VirtualMachineExtensionImagesClient {
return original.NewVirtualMachineExtensionImagesClient(subscriptionID)
}
func NewVirtualMachineExtensionImagesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineExtensionImagesClient {
return original.NewVirtualMachineExtensionImagesClientWithBaseURI(baseURI, subscriptionID)
}
func NewVirtualMachineExtensionsClient(subscriptionID string) VirtualMachineExtensionsClient {
return original.NewVirtualMachineExtensionsClient(subscriptionID)
}
func NewVirtualMachineExtensionsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineExtensionsClient {
return original.NewVirtualMachineExtensionsClientWithBaseURI(baseURI, subscriptionID)
}
func NewVirtualMachineImagesClient(subscriptionID string) VirtualMachineImagesClient {
return original.NewVirtualMachineImagesClient(subscriptionID)
}
func NewVirtualMachineImagesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineImagesClient {
return original.NewVirtualMachineImagesClientWithBaseURI(baseURI, subscriptionID)
}
func NewVirtualMachineListResultIterator(page VirtualMachineListResultPage) VirtualMachineListResultIterator {
return original.NewVirtualMachineListResultIterator(page)
}
func NewVirtualMachineListResultPage(cur VirtualMachineListResult, getNextPage func(context.Context, VirtualMachineListResult) (VirtualMachineListResult, error)) VirtualMachineListResultPage {
return original.NewVirtualMachineListResultPage(cur, getNextPage)
}
func NewVirtualMachineRunCommandsClient(subscriptionID string) VirtualMachineRunCommandsClient {
return original.NewVirtualMachineRunCommandsClient(subscriptionID)
}
func NewVirtualMachineRunCommandsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineRunCommandsClient {
return original.NewVirtualMachineRunCommandsClientWithBaseURI(baseURI, subscriptionID)
}
func NewVirtualMachineScaleSetExtensionListResultIterator(page VirtualMachineScaleSetExtensionListResultPage) VirtualMachineScaleSetExtensionListResultIterator {
return original.NewVirtualMachineScaleSetExtensionListResultIterator(page)
}
func NewVirtualMachineScaleSetExtensionListResultPage(cur VirtualMachineScaleSetExtensionListResult, getNextPage func(context.Context, VirtualMachineScaleSetExtensionListResult) (VirtualMachineScaleSetExtensionListResult, error)) VirtualMachineScaleSetExtensionListResultPage {
return original.NewVirtualMachineScaleSetExtensionListResultPage(cur, getNextPage)
}
func NewVirtualMachineScaleSetExtensionsClient(subscriptionID string) VirtualMachineScaleSetExtensionsClient {
return original.NewVirtualMachineScaleSetExtensionsClient(subscriptionID)
}
func NewVirtualMachineScaleSetExtensionsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineScaleSetExtensionsClient {
return original.NewVirtualMachineScaleSetExtensionsClientWithBaseURI(baseURI, subscriptionID)
}
func NewVirtualMachineScaleSetListOSUpgradeHistoryIterator(page VirtualMachineScaleSetListOSUpgradeHistoryPage) VirtualMachineScaleSetListOSUpgradeHistoryIterator {
return original.NewVirtualMachineScaleSetListOSUpgradeHistoryIterator(page)
}
func NewVirtualMachineScaleSetListOSUpgradeHistoryPage(cur VirtualMachineScaleSetListOSUpgradeHistory, getNextPage func(context.Context, VirtualMachineScaleSetListOSUpgradeHistory) (VirtualMachineScaleSetListOSUpgradeHistory, error)) VirtualMachineScaleSetListOSUpgradeHistoryPage {
return original.NewVirtualMachineScaleSetListOSUpgradeHistoryPage(cur, getNextPage)
}
func NewVirtualMachineScaleSetListResultIterator(page VirtualMachineScaleSetListResultPage) VirtualMachineScaleSetListResultIterator {
return original.NewVirtualMachineScaleSetListResultIterator(page)
}
func NewVirtualMachineScaleSetListResultPage(cur VirtualMachineScaleSetListResult, getNextPage func(context.Context, VirtualMachineScaleSetListResult) (VirtualMachineScaleSetListResult, error)) VirtualMachineScaleSetListResultPage {
return original.NewVirtualMachineScaleSetListResultPage(cur, getNextPage)
}
func NewVirtualMachineScaleSetListSkusResultIterator(page VirtualMachineScaleSetListSkusResultPage) VirtualMachineScaleSetListSkusResultIterator {
return original.NewVirtualMachineScaleSetListSkusResultIterator(page)
}
func NewVirtualMachineScaleSetListSkusResultPage(cur VirtualMachineScaleSetListSkusResult, getNextPage func(context.Context, VirtualMachineScaleSetListSkusResult) (VirtualMachineScaleSetListSkusResult, error)) VirtualMachineScaleSetListSkusResultPage {
return original.NewVirtualMachineScaleSetListSkusResultPage(cur, getNextPage)
}
func NewVirtualMachineScaleSetListWithLinkResultIterator(page VirtualMachineScaleSetListWithLinkResultPage) VirtualMachineScaleSetListWithLinkResultIterator {
return original.NewVirtualMachineScaleSetListWithLinkResultIterator(page)
}
func NewVirtualMachineScaleSetListWithLinkResultPage(cur VirtualMachineScaleSetListWithLinkResult, getNextPage func(context.Context, VirtualMachineScaleSetListWithLinkResult) (VirtualMachineScaleSetListWithLinkResult, error)) VirtualMachineScaleSetListWithLinkResultPage {
return original.NewVirtualMachineScaleSetListWithLinkResultPage(cur, getNextPage)
}
func NewVirtualMachineScaleSetRollingUpgradesClient(subscriptionID string) VirtualMachineScaleSetRollingUpgradesClient {
return original.NewVirtualMachineScaleSetRollingUpgradesClient(subscriptionID)
}
func NewVirtualMachineScaleSetRollingUpgradesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineScaleSetRollingUpgradesClient {
return original.NewVirtualMachineScaleSetRollingUpgradesClientWithBaseURI(baseURI, subscriptionID)
}
func NewVirtualMachineScaleSetVMListResultIterator(page VirtualMachineScaleSetVMListResultPage) VirtualMachineScaleSetVMListResultIterator {
return original.NewVirtualMachineScaleSetVMListResultIterator(page)
}
func NewVirtualMachineScaleSetVMListResultPage(cur VirtualMachineScaleSetVMListResult, getNextPage func(context.Context, VirtualMachineScaleSetVMListResult) (VirtualMachineScaleSetVMListResult, error)) VirtualMachineScaleSetVMListResultPage {
return original.NewVirtualMachineScaleSetVMListResultPage(cur, getNextPage)
}
func NewVirtualMachineScaleSetVMsClient(subscriptionID string) VirtualMachineScaleSetVMsClient {
return original.NewVirtualMachineScaleSetVMsClient(subscriptionID)
}
func NewVirtualMachineScaleSetVMsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineScaleSetVMsClient {
return original.NewVirtualMachineScaleSetVMsClientWithBaseURI(baseURI, subscriptionID)
}
func NewVirtualMachineScaleSetsClient(subscriptionID string) VirtualMachineScaleSetsClient {
return original.NewVirtualMachineScaleSetsClient(subscriptionID)
}
func NewVirtualMachineScaleSetsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineScaleSetsClient {
return original.NewVirtualMachineScaleSetsClientWithBaseURI(baseURI, subscriptionID)
}
func NewVirtualMachineSizesClient(subscriptionID string) VirtualMachineSizesClient {
return original.NewVirtualMachineSizesClient(subscriptionID)
}
func NewVirtualMachineSizesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineSizesClient {
return original.NewVirtualMachineSizesClientWithBaseURI(baseURI, subscriptionID)
}
func NewVirtualMachinesClient(subscriptionID string) VirtualMachinesClient {
return original.NewVirtualMachinesClient(subscriptionID)
}
func NewVirtualMachinesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachinesClient {
return original.NewVirtualMachinesClientWithBaseURI(baseURI, subscriptionID)
}
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
return original.NewWithBaseURI(baseURI, subscriptionID)
}
func PossibleAccessLevelValues() []AccessLevel {
return original.PossibleAccessLevelValues()
}
func PossibleCachingTypesValues() []CachingTypes {
return original.PossibleCachingTypesValues()
}
func PossibleComponentNamesValues() []ComponentNames {
return original.PossibleComponentNamesValues()
}
func PossibleDiskCreateOptionTypesValues() []DiskCreateOptionTypes {
return original.PossibleDiskCreateOptionTypesValues()
}
func PossibleDiskCreateOptionValues() []DiskCreateOption {
return original.PossibleDiskCreateOptionValues()
}
func PossibleIPVersionValues() []IPVersion {
return original.PossibleIPVersionValues()
}
func PossibleInstanceViewTypesValues() []InstanceViewTypes {
return original.PossibleInstanceViewTypesValues()
}
func PossibleIntervalInMinsValues() []IntervalInMins {
return original.PossibleIntervalInMinsValues()
}
func PossibleMaintenanceOperationResultCodeTypesValues() []MaintenanceOperationResultCodeTypes {
return original.PossibleMaintenanceOperationResultCodeTypesValues()
}
func PossibleOperatingSystemStateTypesValues() []OperatingSystemStateTypes {
return original.PossibleOperatingSystemStateTypesValues()
}
func PossibleOperatingSystemTypesValues() []OperatingSystemTypes {
return original.PossibleOperatingSystemTypesValues()
}
func PossiblePassNamesValues() []PassNames {
return original.PossiblePassNamesValues()
}
func PossibleProtocolTypesValues() []ProtocolTypes {
return original.PossibleProtocolTypesValues()
}
func PossibleResourceIdentityTypeValues() []ResourceIdentityType {
return original.PossibleResourceIdentityTypeValues()
}
func PossibleResourceSkuCapacityScaleTypeValues() []ResourceSkuCapacityScaleType {
return original.PossibleResourceSkuCapacityScaleTypeValues()
}
func PossibleResourceSkuRestrictionsReasonCodeValues() []ResourceSkuRestrictionsReasonCode {
return original.PossibleResourceSkuRestrictionsReasonCodeValues()
}
func PossibleResourceSkuRestrictionsTypeValues() []ResourceSkuRestrictionsType {
return original.PossibleResourceSkuRestrictionsTypeValues()
}
func PossibleRollingUpgradeActionTypeValues() []RollingUpgradeActionType {
return original.PossibleRollingUpgradeActionTypeValues()
}
func PossibleRollingUpgradeStatusCodeValues() []RollingUpgradeStatusCode {
return original.PossibleRollingUpgradeStatusCodeValues()
}
func PossibleSettingNamesValues() []SettingNames {
return original.PossibleSettingNamesValues()
}
func PossibleStatusLevelTypesValues() []StatusLevelTypes {
return original.PossibleStatusLevelTypesValues()
}
func PossibleStorageAccountTypesValues() []StorageAccountTypes {
return original.PossibleStorageAccountTypesValues()
}
func PossibleUpgradeModeValues() []UpgradeMode {
return original.PossibleUpgradeModeValues()
}
func PossibleUpgradeOperationInvokerValues() []UpgradeOperationInvoker {
return original.PossibleUpgradeOperationInvokerValues()
}
func PossibleUpgradeStateValues() []UpgradeState {
return original.PossibleUpgradeStateValues()
}
func PossibleVirtualMachineEvictionPolicyTypesValues() []VirtualMachineEvictionPolicyTypes {
return original.PossibleVirtualMachineEvictionPolicyTypesValues()
}
func PossibleVirtualMachinePriorityTypesValues() []VirtualMachinePriorityTypes {
return original.PossibleVirtualMachinePriorityTypesValues()
}
func PossibleVirtualMachineScaleSetSkuScaleTypeValues() []VirtualMachineScaleSetSkuScaleType {
return original.PossibleVirtualMachineScaleSetSkuScaleTypeValues()
}
func PossibleVirtualMachineSizeTypesValues() []VirtualMachineSizeTypes {
return original.PossibleVirtualMachineSizeTypesValues()
}
func UserAgent() string {
return original.UserAgent() + " profiles/2019-03-01"
}
func Version() string {
return original.Version()
}

View file

@ -1,241 +0,0 @@
//go:build go1.9
// +build go1.9
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// This code was auto-generated by:
// github.com/Azure/azure-sdk-for-go/eng/tools/profileBuilder
package resources
import (
"context"
original "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources"
)
const (
DefaultBaseURI = original.DefaultBaseURI
)
type DeploymentMode = original.DeploymentMode
const (
Complete DeploymentMode = original.Complete
Incremental DeploymentMode = original.Incremental
)
type OnErrorDeploymentType = original.OnErrorDeploymentType
const (
LastSuccessful OnErrorDeploymentType = original.LastSuccessful
SpecificDeployment OnErrorDeploymentType = original.SpecificDeployment
)
type ResourceIdentityType = original.ResourceIdentityType
const (
None ResourceIdentityType = original.None
SystemAssigned ResourceIdentityType = original.SystemAssigned
SystemAssignedUserAssigned ResourceIdentityType = original.SystemAssignedUserAssigned
UserAssigned ResourceIdentityType = original.UserAssigned
)
type AliasPathType = original.AliasPathType
type AliasType = original.AliasType
type BaseClient = original.BaseClient
type BasicDependency = original.BasicDependency
type Client = original.Client
type CloudError = original.CloudError
type CreateOrUpdateByIDFuture = original.CreateOrUpdateByIDFuture
type CreateOrUpdateFuture = original.CreateOrUpdateFuture
type DebugSetting = original.DebugSetting
type DeleteByIDFuture = original.DeleteByIDFuture
type DeleteFuture = original.DeleteFuture
type Dependency = original.Dependency
type Deployment = original.Deployment
type DeploymentExportResult = original.DeploymentExportResult
type DeploymentExtended = original.DeploymentExtended
type DeploymentExtendedFilter = original.DeploymentExtendedFilter
type DeploymentListResult = original.DeploymentListResult
type DeploymentListResultIterator = original.DeploymentListResultIterator
type DeploymentListResultPage = original.DeploymentListResultPage
type DeploymentOperation = original.DeploymentOperation
type DeploymentOperationProperties = original.DeploymentOperationProperties
type DeploymentOperationsClient = original.DeploymentOperationsClient
type DeploymentOperationsListResult = original.DeploymentOperationsListResult
type DeploymentOperationsListResultIterator = original.DeploymentOperationsListResultIterator
type DeploymentOperationsListResultPage = original.DeploymentOperationsListResultPage
type DeploymentProperties = original.DeploymentProperties
type DeploymentPropertiesExtended = original.DeploymentPropertiesExtended
type DeploymentValidateResult = original.DeploymentValidateResult
type DeploymentsClient = original.DeploymentsClient
type DeploymentsCreateOrUpdateAtSubscriptionScopeFuture = original.DeploymentsCreateOrUpdateAtSubscriptionScopeFuture
type DeploymentsCreateOrUpdateFuture = original.DeploymentsCreateOrUpdateFuture
type DeploymentsDeleteAtSubscriptionScopeFuture = original.DeploymentsDeleteAtSubscriptionScopeFuture
type DeploymentsDeleteFuture = original.DeploymentsDeleteFuture
type ErrorAdditionalInfo = original.ErrorAdditionalInfo
type ErrorResponse = original.ErrorResponse
type ExportTemplateRequest = original.ExportTemplateRequest
type GenericResource = original.GenericResource
type GenericResourceExpanded = original.GenericResourceExpanded
type GenericResourceFilter = original.GenericResourceFilter
type Group = original.Group
type GroupExportResult = original.GroupExportResult
type GroupFilter = original.GroupFilter
type GroupListResult = original.GroupListResult
type GroupListResultIterator = original.GroupListResultIterator
type GroupListResultPage = original.GroupListResultPage
type GroupPatchable = original.GroupPatchable
type GroupProperties = original.GroupProperties
type GroupsClient = original.GroupsClient
type GroupsDeleteFuture = original.GroupsDeleteFuture
type HTTPMessage = original.HTTPMessage
type Identity = original.Identity
type IdentityUserAssignedIdentitiesValue = original.IdentityUserAssignedIdentitiesValue
type ListResult = original.ListResult
type ListResultIterator = original.ListResultIterator
type ListResultPage = original.ListResultPage
type ManagementErrorWithDetails = original.ManagementErrorWithDetails
type MoveInfo = original.MoveInfo
type MoveResourcesFuture = original.MoveResourcesFuture
type OnErrorDeployment = original.OnErrorDeployment
type OnErrorDeploymentExtended = original.OnErrorDeploymentExtended
type Operation = original.Operation
type OperationDisplay = original.OperationDisplay
type OperationListResult = original.OperationListResult
type OperationListResultIterator = original.OperationListResultIterator
type OperationListResultPage = original.OperationListResultPage
type OperationsClient = original.OperationsClient
type ParametersLink = original.ParametersLink
type Plan = original.Plan
type Provider = original.Provider
type ProviderListResult = original.ProviderListResult
type ProviderListResultIterator = original.ProviderListResultIterator
type ProviderListResultPage = original.ProviderListResultPage
type ProviderOperationDisplayProperties = original.ProviderOperationDisplayProperties
type ProviderResourceType = original.ProviderResourceType
type ProvidersClient = original.ProvidersClient
type Resource = original.Resource
type Sku = original.Sku
type SubResource = original.SubResource
type TagCount = original.TagCount
type TagDetails = original.TagDetails
type TagValue = original.TagValue
type TagsClient = original.TagsClient
type TagsListResult = original.TagsListResult
type TagsListResultIterator = original.TagsListResultIterator
type TagsListResultPage = original.TagsListResultPage
type TargetResource = original.TargetResource
type TemplateHashResult = original.TemplateHashResult
type TemplateLink = original.TemplateLink
type UpdateByIDFuture = original.UpdateByIDFuture
type UpdateFuture = original.UpdateFuture
type ValidateMoveResourcesFuture = original.ValidateMoveResourcesFuture
func New(subscriptionID string) BaseClient {
return original.New(subscriptionID)
}
func NewClient(subscriptionID string) Client {
return original.NewClient(subscriptionID)
}
func NewClientWithBaseURI(baseURI string, subscriptionID string) Client {
return original.NewClientWithBaseURI(baseURI, subscriptionID)
}
func NewDeploymentListResultIterator(page DeploymentListResultPage) DeploymentListResultIterator {
return original.NewDeploymentListResultIterator(page)
}
func NewDeploymentListResultPage(cur DeploymentListResult, getNextPage func(context.Context, DeploymentListResult) (DeploymentListResult, error)) DeploymentListResultPage {
return original.NewDeploymentListResultPage(cur, getNextPage)
}
func NewDeploymentOperationsClient(subscriptionID string) DeploymentOperationsClient {
return original.NewDeploymentOperationsClient(subscriptionID)
}
func NewDeploymentOperationsClientWithBaseURI(baseURI string, subscriptionID string) DeploymentOperationsClient {
return original.NewDeploymentOperationsClientWithBaseURI(baseURI, subscriptionID)
}
func NewDeploymentOperationsListResultIterator(page DeploymentOperationsListResultPage) DeploymentOperationsListResultIterator {
return original.NewDeploymentOperationsListResultIterator(page)
}
func NewDeploymentOperationsListResultPage(cur DeploymentOperationsListResult, getNextPage func(context.Context, DeploymentOperationsListResult) (DeploymentOperationsListResult, error)) DeploymentOperationsListResultPage {
return original.NewDeploymentOperationsListResultPage(cur, getNextPage)
}
func NewDeploymentsClient(subscriptionID string) DeploymentsClient {
return original.NewDeploymentsClient(subscriptionID)
}
func NewDeploymentsClientWithBaseURI(baseURI string, subscriptionID string) DeploymentsClient {
return original.NewDeploymentsClientWithBaseURI(baseURI, subscriptionID)
}
func NewGroupListResultIterator(page GroupListResultPage) GroupListResultIterator {
return original.NewGroupListResultIterator(page)
}
func NewGroupListResultPage(cur GroupListResult, getNextPage func(context.Context, GroupListResult) (GroupListResult, error)) GroupListResultPage {
return original.NewGroupListResultPage(cur, getNextPage)
}
func NewGroupsClient(subscriptionID string) GroupsClient {
return original.NewGroupsClient(subscriptionID)
}
func NewGroupsClientWithBaseURI(baseURI string, subscriptionID string) GroupsClient {
return original.NewGroupsClientWithBaseURI(baseURI, subscriptionID)
}
func NewListResultIterator(page ListResultPage) ListResultIterator {
return original.NewListResultIterator(page)
}
func NewListResultPage(cur ListResult, getNextPage func(context.Context, ListResult) (ListResult, error)) ListResultPage {
return original.NewListResultPage(cur, getNextPage)
}
func NewOperationListResultIterator(page OperationListResultPage) OperationListResultIterator {
return original.NewOperationListResultIterator(page)
}
func NewOperationListResultPage(cur OperationListResult, getNextPage func(context.Context, OperationListResult) (OperationListResult, error)) OperationListResultPage {
return original.NewOperationListResultPage(cur, getNextPage)
}
func NewOperationsClient(subscriptionID string) OperationsClient {
return original.NewOperationsClient(subscriptionID)
}
func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {
return original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)
}
func NewProviderListResultIterator(page ProviderListResultPage) ProviderListResultIterator {
return original.NewProviderListResultIterator(page)
}
func NewProviderListResultPage(cur ProviderListResult, getNextPage func(context.Context, ProviderListResult) (ProviderListResult, error)) ProviderListResultPage {
return original.NewProviderListResultPage(cur, getNextPage)
}
func NewProvidersClient(subscriptionID string) ProvidersClient {
return original.NewProvidersClient(subscriptionID)
}
func NewProvidersClientWithBaseURI(baseURI string, subscriptionID string) ProvidersClient {
return original.NewProvidersClientWithBaseURI(baseURI, subscriptionID)
}
func NewTagsClient(subscriptionID string) TagsClient {
return original.NewTagsClient(subscriptionID)
}
func NewTagsClientWithBaseURI(baseURI string, subscriptionID string) TagsClient {
return original.NewTagsClientWithBaseURI(baseURI, subscriptionID)
}
func NewTagsListResultIterator(page TagsListResultPage) TagsListResultIterator {
return original.NewTagsListResultIterator(page)
}
func NewTagsListResultPage(cur TagsListResult, getNextPage func(context.Context, TagsListResult) (TagsListResult, error)) TagsListResultPage {
return original.NewTagsListResultPage(cur, getNextPage)
}
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
return original.NewWithBaseURI(baseURI, subscriptionID)
}
func PossibleDeploymentModeValues() []DeploymentMode {
return original.PossibleDeploymentModeValues()
}
func PossibleOnErrorDeploymentTypeValues() []OnErrorDeploymentType {
return original.PossibleOnErrorDeploymentTypeValues()
}
func PossibleResourceIdentityTypeValues() []ResourceIdentityType {
return original.PossibleResourceIdentityTypeValues()
}
func UserAgent() string {
return original.UserAgent() + " profiles/2019-03-01"
}
func Version() string {
return original.Version()
}

View file

@ -1,325 +0,0 @@
//go:build go1.9
// +build go1.9
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// This code was auto-generated by:
// github.com/Azure/azure-sdk-for-go/eng/tools/profileBuilder
package storage
import original "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2017-10-01/storage"
const (
DefaultBaseURI = original.DefaultBaseURI
)
type AccessTier = original.AccessTier
const (
Cool AccessTier = original.Cool
Hot AccessTier = original.Hot
)
type AccountStatus = original.AccountStatus
const (
Available AccountStatus = original.Available
Unavailable AccountStatus = original.Unavailable
)
type Action = original.Action
const (
Allow Action = original.Allow
)
type Bypass = original.Bypass
const (
AzureServices Bypass = original.AzureServices
Logging Bypass = original.Logging
Metrics Bypass = original.Metrics
None Bypass = original.None
)
type DefaultAction = original.DefaultAction
const (
DefaultActionAllow DefaultAction = original.DefaultActionAllow
DefaultActionDeny DefaultAction = original.DefaultActionDeny
)
type HTTPProtocol = original.HTTPProtocol
const (
HTTPS HTTPProtocol = original.HTTPS
Httpshttp HTTPProtocol = original.Httpshttp
)
type KeyPermission = original.KeyPermission
const (
Full KeyPermission = original.Full
Read KeyPermission = original.Read
)
type KeySource = original.KeySource
const (
MicrosoftKeyvault KeySource = original.MicrosoftKeyvault
MicrosoftStorage KeySource = original.MicrosoftStorage
)
type Kind = original.Kind
const (
BlobStorage Kind = original.BlobStorage
Storage Kind = original.Storage
StorageV2 Kind = original.StorageV2
)
type Permissions = original.Permissions
const (
A Permissions = original.A
C Permissions = original.C
D Permissions = original.D
L Permissions = original.L
P Permissions = original.P
R Permissions = original.R
U Permissions = original.U
W Permissions = original.W
)
type ProvisioningState = original.ProvisioningState
const (
Creating ProvisioningState = original.Creating
ResolvingDNS ProvisioningState = original.ResolvingDNS
Succeeded ProvisioningState = original.Succeeded
)
type Reason = original.Reason
const (
AccountNameInvalid Reason = original.AccountNameInvalid
AlreadyExists Reason = original.AlreadyExists
)
type ReasonCode = original.ReasonCode
const (
NotAvailableForSubscription ReasonCode = original.NotAvailableForSubscription
QuotaID ReasonCode = original.QuotaID
)
type Services = original.Services
const (
B Services = original.B
F Services = original.F
Q Services = original.Q
T Services = original.T
)
type SignedResource = original.SignedResource
const (
SignedResourceB SignedResource = original.SignedResourceB
SignedResourceC SignedResource = original.SignedResourceC
SignedResourceF SignedResource = original.SignedResourceF
SignedResourceS SignedResource = original.SignedResourceS
)
type SignedResourceTypes = original.SignedResourceTypes
const (
SignedResourceTypesC SignedResourceTypes = original.SignedResourceTypesC
SignedResourceTypesO SignedResourceTypes = original.SignedResourceTypesO
SignedResourceTypesS SignedResourceTypes = original.SignedResourceTypesS
)
type SkuName = original.SkuName
const (
PremiumLRS SkuName = original.PremiumLRS
StandardGRS SkuName = original.StandardGRS
StandardLRS SkuName = original.StandardLRS
StandardRAGRS SkuName = original.StandardRAGRS
StandardZRS SkuName = original.StandardZRS
)
type SkuTier = original.SkuTier
const (
Premium SkuTier = original.Premium
Standard SkuTier = original.Standard
)
type State = original.State
const (
StateDeprovisioning State = original.StateDeprovisioning
StateFailed State = original.StateFailed
StateNetworkSourceDeleted State = original.StateNetworkSourceDeleted
StateProvisioning State = original.StateProvisioning
StateSucceeded State = original.StateSucceeded
)
type UsageUnit = original.UsageUnit
const (
Bytes UsageUnit = original.Bytes
BytesPerSecond UsageUnit = original.BytesPerSecond
Count UsageUnit = original.Count
CountsPerSecond UsageUnit = original.CountsPerSecond
Percent UsageUnit = original.Percent
Seconds UsageUnit = original.Seconds
)
type Account = original.Account
type AccountCheckNameAvailabilityParameters = original.AccountCheckNameAvailabilityParameters
type AccountCreateParameters = original.AccountCreateParameters
type AccountKey = original.AccountKey
type AccountListKeysResult = original.AccountListKeysResult
type AccountListResult = original.AccountListResult
type AccountProperties = original.AccountProperties
type AccountPropertiesCreateParameters = original.AccountPropertiesCreateParameters
type AccountPropertiesUpdateParameters = original.AccountPropertiesUpdateParameters
type AccountRegenerateKeyParameters = original.AccountRegenerateKeyParameters
type AccountSasParameters = original.AccountSasParameters
type AccountUpdateParameters = original.AccountUpdateParameters
type AccountsClient = original.AccountsClient
type AccountsCreateFuture = original.AccountsCreateFuture
type BaseClient = original.BaseClient
type CheckNameAvailabilityResult = original.CheckNameAvailabilityResult
type CustomDomain = original.CustomDomain
type Dimension = original.Dimension
type Encryption = original.Encryption
type EncryptionService = original.EncryptionService
type EncryptionServices = original.EncryptionServices
type Endpoints = original.Endpoints
type IPRule = original.IPRule
type Identity = original.Identity
type KeyVaultProperties = original.KeyVaultProperties
type ListAccountSasResponse = original.ListAccountSasResponse
type ListServiceSasResponse = original.ListServiceSasResponse
type MetricSpecification = original.MetricSpecification
type NetworkRuleSet = original.NetworkRuleSet
type Operation = original.Operation
type OperationDisplay = original.OperationDisplay
type OperationListResult = original.OperationListResult
type OperationProperties = original.OperationProperties
type OperationsClient = original.OperationsClient
type Resource = original.Resource
type Restriction = original.Restriction
type SKUCapability = original.SKUCapability
type ServiceSasParameters = original.ServiceSasParameters
type ServiceSpecification = original.ServiceSpecification
type Sku = original.Sku
type SkuListResult = original.SkuListResult
type SkusClient = original.SkusClient
type Usage = original.Usage
type UsageClient = original.UsageClient
type UsageListResult = original.UsageListResult
type UsageName = original.UsageName
type VirtualNetworkRule = original.VirtualNetworkRule
func New(subscriptionID string) BaseClient {
return original.New(subscriptionID)
}
func NewAccountsClient(subscriptionID string) AccountsClient {
return original.NewAccountsClient(subscriptionID)
}
func NewAccountsClientWithBaseURI(baseURI string, subscriptionID string) AccountsClient {
return original.NewAccountsClientWithBaseURI(baseURI, subscriptionID)
}
func NewOperationsClient(subscriptionID string) OperationsClient {
return original.NewOperationsClient(subscriptionID)
}
func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {
return original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)
}
func NewSkusClient(subscriptionID string) SkusClient {
return original.NewSkusClient(subscriptionID)
}
func NewSkusClientWithBaseURI(baseURI string, subscriptionID string) SkusClient {
return original.NewSkusClientWithBaseURI(baseURI, subscriptionID)
}
func NewUsageClient(subscriptionID string) UsageClient {
return original.NewUsageClient(subscriptionID)
}
func NewUsageClientWithBaseURI(baseURI string, subscriptionID string) UsageClient {
return original.NewUsageClientWithBaseURI(baseURI, subscriptionID)
}
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
return original.NewWithBaseURI(baseURI, subscriptionID)
}
func PossibleAccessTierValues() []AccessTier {
return original.PossibleAccessTierValues()
}
func PossibleAccountStatusValues() []AccountStatus {
return original.PossibleAccountStatusValues()
}
func PossibleActionValues() []Action {
return original.PossibleActionValues()
}
func PossibleBypassValues() []Bypass {
return original.PossibleBypassValues()
}
func PossibleDefaultActionValues() []DefaultAction {
return original.PossibleDefaultActionValues()
}
func PossibleHTTPProtocolValues() []HTTPProtocol {
return original.PossibleHTTPProtocolValues()
}
func PossibleKeyPermissionValues() []KeyPermission {
return original.PossibleKeyPermissionValues()
}
func PossibleKeySourceValues() []KeySource {
return original.PossibleKeySourceValues()
}
func PossibleKindValues() []Kind {
return original.PossibleKindValues()
}
func PossiblePermissionsValues() []Permissions {
return original.PossiblePermissionsValues()
}
func PossibleProvisioningStateValues() []ProvisioningState {
return original.PossibleProvisioningStateValues()
}
func PossibleReasonCodeValues() []ReasonCode {
return original.PossibleReasonCodeValues()
}
func PossibleReasonValues() []Reason {
return original.PossibleReasonValues()
}
func PossibleServicesValues() []Services {
return original.PossibleServicesValues()
}
func PossibleSignedResourceTypesValues() []SignedResourceTypes {
return original.PossibleSignedResourceTypesValues()
}
func PossibleSignedResourceValues() []SignedResource {
return original.PossibleSignedResourceValues()
}
func PossibleSkuNameValues() []SkuName {
return original.PossibleSkuNameValues()
}
func PossibleSkuTierValues() []SkuTier {
return original.PossibleSkuTierValues()
}
func PossibleStateValues() []State {
return original.PossibleStateValues()
}
func PossibleUsageUnitValues() []UsageUnit {
return original.PossibleUsageUnitValues()
}
func UserAgent() string {
return original.UserAgent() + " profiles/2019-03-01"
}
func Version() string {
return original.Version()
}

View file

@ -0,0 +1,72 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package arm
import (
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
armpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy"
armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing"
)
// ClientOptions contains configuration settings for a client's pipeline.
type ClientOptions = armpolicy.ClientOptions
// Client is a HTTP client for use with ARM endpoints. It consists of an endpoint, pipeline, and tracing provider.
type Client struct {
ep string
pl runtime.Pipeline
tr tracing.Tracer
}
// NewClient creates a new Client instance with the provided values.
// This client is intended to be used with Azure Resource Manager endpoints.
// - moduleName - the fully qualified name of the module where the client is defined; used by the telemetry policy and tracing provider.
// - moduleVersion - the semantic version of the module; used by the telemetry policy and tracing provider.
// - cred - the TokenCredential used to authenticate the request
// - options - optional client configurations; pass nil to accept the default values
func NewClient(moduleName, moduleVersion string, cred azcore.TokenCredential, options *ClientOptions) (*Client, error) {
if options == nil {
options = &ClientOptions{}
}
if !options.Telemetry.Disabled {
if err := shared.ValidateModVer(moduleVersion); err != nil {
return nil, err
}
}
ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
ep = c.Endpoint
}
pl, err := armruntime.NewPipeline(moduleName, moduleVersion, cred, runtime.PipelineOptions{}, options)
if err != nil {
return nil, err
}
tr := options.TracingProvider.NewTracer(moduleName, moduleVersion)
return &Client{ep: ep, pl: pl, tr: tr}, nil
}
// Endpoint returns the service's base URL for this client.
func (c *Client) Endpoint() string {
return c.ep
}
// Pipeline returns the pipeline for this client.
func (c *Client) Pipeline() runtime.Pipeline {
return c.pl
}
// Tracer returns the tracer for this client.
func (c *Client) Tracer() tracing.Tracer {
return c.tr
}

View file

@ -0,0 +1,9 @@
//go:build go1.18
// +build go1.18
// Copyright 2017 Microsoft Corporation. All rights reserved.
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
// Package arm contains functionality specific to Azure Resource Manager clients.
package arm

View file

@ -0,0 +1,224 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package resource
import (
"fmt"
"strings"
)
const (
providersKey = "providers"
subscriptionsKey = "subscriptions"
resourceGroupsLowerKey = "resourcegroups"
locationsKey = "locations"
builtInResourceNamespace = "Microsoft.Resources"
)
// RootResourceID defines the tenant as the root parent of all other ResourceID.
var RootResourceID = &ResourceID{
Parent: nil,
ResourceType: TenantResourceType,
Name: "",
}
// ResourceID represents a resource ID such as `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myRg`.
// Don't create this type directly, use ParseResourceID instead.
type ResourceID struct {
// Parent is the parent ResourceID of this instance.
// Can be nil if there is no parent.
Parent *ResourceID
// SubscriptionID is the subscription ID in this resource ID.
// The value can be empty if the resource ID does not contain a subscription ID.
SubscriptionID string
// ResourceGroupName is the resource group name in this resource ID.
// The value can be empty if the resource ID does not contain a resource group name.
ResourceGroupName string
// Provider represents the provider name in this resource ID.
// This is only valid when the resource ID represents a resource provider.
// Example: `/subscriptions/00000000-0000-0000-0000-000000000000/providers/Microsoft.Insights`
Provider string
// Location is the location in this resource ID.
// The value can be empty if the resource ID does not contain a location name.
Location string
// ResourceType represents the type of this resource ID.
ResourceType ResourceType
// Name is the resource name of this resource ID.
Name string
isChild bool
stringValue string
}
// ParseResourceID parses a string to an instance of ResourceID
func ParseResourceID(id string) (*ResourceID, error) {
if len(id) == 0 {
return nil, fmt.Errorf("invalid resource ID: id cannot be empty")
}
if !strings.HasPrefix(id, "/") {
return nil, fmt.Errorf("invalid resource ID: resource id '%s' must start with '/'", id)
}
parts := splitStringAndOmitEmpty(id, "/")
if len(parts) < 2 {
return nil, fmt.Errorf("invalid resource ID: %s", id)
}
if !strings.EqualFold(parts[0], subscriptionsKey) && !strings.EqualFold(parts[0], providersKey) {
return nil, fmt.Errorf("invalid resource ID: %s", id)
}
return appendNext(RootResourceID, parts, id)
}
// String returns the string of the ResourceID
func (id *ResourceID) String() string {
if len(id.stringValue) > 0 {
return id.stringValue
}
if id.Parent == nil {
return ""
}
builder := strings.Builder{}
builder.WriteString(id.Parent.String())
if id.isChild {
builder.WriteString(fmt.Sprintf("/%s", id.ResourceType.lastType()))
if len(id.Name) > 0 {
builder.WriteString(fmt.Sprintf("/%s", id.Name))
}
} else {
builder.WriteString(fmt.Sprintf("/providers/%s/%s/%s", id.ResourceType.Namespace, id.ResourceType.Type, id.Name))
}
id.stringValue = builder.String()
return id.stringValue
}
func newResourceID(parent *ResourceID, resourceTypeName string, resourceName string) *ResourceID {
id := &ResourceID{}
id.init(parent, chooseResourceType(resourceTypeName, parent), resourceName, true)
return id
}
func newResourceIDWithResourceType(parent *ResourceID, resourceType ResourceType, resourceName string) *ResourceID {
id := &ResourceID{}
id.init(parent, resourceType, resourceName, true)
return id
}
func newResourceIDWithProvider(parent *ResourceID, providerNamespace, resourceTypeName, resourceName string) *ResourceID {
id := &ResourceID{}
id.init(parent, NewResourceType(providerNamespace, resourceTypeName), resourceName, false)
return id
}
func chooseResourceType(resourceTypeName string, parent *ResourceID) ResourceType {
if strings.EqualFold(resourceTypeName, resourceGroupsLowerKey) {
return ResourceGroupResourceType
} else if strings.EqualFold(resourceTypeName, subscriptionsKey) && parent != nil && parent.ResourceType.String() == TenantResourceType.String() {
return SubscriptionResourceType
}
return parent.ResourceType.AppendChild(resourceTypeName)
}
func (id *ResourceID) init(parent *ResourceID, resourceType ResourceType, name string, isChild bool) {
if parent != nil {
id.Provider = parent.Provider
id.SubscriptionID = parent.SubscriptionID
id.ResourceGroupName = parent.ResourceGroupName
id.Location = parent.Location
}
if resourceType.String() == SubscriptionResourceType.String() {
id.SubscriptionID = name
}
if resourceType.lastType() == locationsKey {
id.Location = name
}
if resourceType.String() == ResourceGroupResourceType.String() {
id.ResourceGroupName = name
}
if resourceType.String() == ProviderResourceType.String() {
id.Provider = name
}
if parent == nil {
id.Parent = RootResourceID
} else {
id.Parent = parent
}
id.isChild = isChild
id.ResourceType = resourceType
id.Name = name
}
func appendNext(parent *ResourceID, parts []string, id string) (*ResourceID, error) {
if len(parts) == 0 {
return parent, nil
}
if len(parts) == 1 {
// subscriptions and resourceGroups are not valid ids without their names
if strings.EqualFold(parts[0], subscriptionsKey) || strings.EqualFold(parts[0], resourceGroupsLowerKey) {
return nil, fmt.Errorf("invalid resource ID: %s", id)
}
// resourceGroup must contain either child or provider resource type
if parent.ResourceType.String() == ResourceGroupResourceType.String() {
return nil, fmt.Errorf("invalid resource ID: %s", id)
}
return newResourceID(parent, parts[0], ""), nil
}
if strings.EqualFold(parts[0], providersKey) && (len(parts) == 2 || strings.EqualFold(parts[2], providersKey)) {
//provider resource can only be on a tenant or a subscription parent
if parent.ResourceType.String() != SubscriptionResourceType.String() && parent.ResourceType.String() != TenantResourceType.String() {
return nil, fmt.Errorf("invalid resource ID: %s", id)
}
return appendNext(newResourceIDWithResourceType(parent, ProviderResourceType, parts[1]), parts[2:], id)
}
if len(parts) > 3 && strings.EqualFold(parts[0], providersKey) {
return appendNext(newResourceIDWithProvider(parent, parts[1], parts[2], parts[3]), parts[4:], id)
}
if len(parts) > 1 && !strings.EqualFold(parts[0], providersKey) {
return appendNext(newResourceID(parent, parts[0], parts[1]), parts[2:], id)
}
return nil, fmt.Errorf("invalid resource ID: %s", id)
}
func splitStringAndOmitEmpty(v, sep string) []string {
r := make([]string, 0)
for _, s := range strings.Split(v, sep) {
if len(s) == 0 {
continue
}
r = append(r, s)
}
return r
}

View file

@ -0,0 +1,114 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package resource
import (
"fmt"
"strings"
)
// SubscriptionResourceType is the ResourceType of a subscription
var SubscriptionResourceType = NewResourceType(builtInResourceNamespace, "subscriptions")
// ResourceGroupResourceType is the ResourceType of a resource group
var ResourceGroupResourceType = NewResourceType(builtInResourceNamespace, "resourceGroups")
// TenantResourceType is the ResourceType of a tenant
var TenantResourceType = NewResourceType(builtInResourceNamespace, "tenants")
// ProviderResourceType is the ResourceType of a provider
var ProviderResourceType = NewResourceType(builtInResourceNamespace, "providers")
// ResourceType represents an Azure resource type, e.g. "Microsoft.Network/virtualNetworks/subnets".
// Don't create this type directly, use ParseResourceType or NewResourceType instead.
type ResourceType struct {
// Namespace is the namespace of the resource type.
// e.g. "Microsoft.Network" in resource type "Microsoft.Network/virtualNetworks/subnets"
Namespace string
// Type is the full type name of the resource type.
// e.g. "virtualNetworks/subnets" in resource type "Microsoft.Network/virtualNetworks/subnets"
Type string
// Types is the slice of all the sub-types of this resource type.
// e.g. ["virtualNetworks", "subnets"] in resource type "Microsoft.Network/virtualNetworks/subnets"
Types []string
stringValue string
}
// String returns the string of the ResourceType
func (t ResourceType) String() string {
return t.stringValue
}
// IsParentOf returns true when the receiver is the parent resource type of the child.
func (t ResourceType) IsParentOf(child ResourceType) bool {
if !strings.EqualFold(t.Namespace, child.Namespace) {
return false
}
if len(t.Types) >= len(child.Types) {
return false
}
for i := range t.Types {
if !strings.EqualFold(t.Types[i], child.Types[i]) {
return false
}
}
return true
}
// AppendChild creates an instance of ResourceType using the receiver as the parent with childType appended to it.
func (t ResourceType) AppendChild(childType string) ResourceType {
return NewResourceType(t.Namespace, fmt.Sprintf("%s/%s", t.Type, childType))
}
// NewResourceType creates an instance of ResourceType using a provider namespace
// such as "Microsoft.Network" and type such as "virtualNetworks/subnets".
func NewResourceType(providerNamespace, typeName string) ResourceType {
return ResourceType{
Namespace: providerNamespace,
Type: typeName,
Types: splitStringAndOmitEmpty(typeName, "/"),
stringValue: fmt.Sprintf("%s/%s", providerNamespace, typeName),
}
}
// ParseResourceType parses the ResourceType from a resource type string (e.g. Microsoft.Network/virtualNetworks/subsets)
// or a resource identifier string.
// e.g. /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myRg/providers/Microsoft.Network/virtualNetworks/vnet/subnets/mySubnet)
func ParseResourceType(resourceIDOrType string) (ResourceType, error) {
// split the path into segments
parts := splitStringAndOmitEmpty(resourceIDOrType, "/")
// There must be at least a namespace and type name
if len(parts) < 1 {
return ResourceType{}, fmt.Errorf("invalid resource ID or type: %s", resourceIDOrType)
}
// if the type is just subscriptions, it is a built-in type in the Microsoft.Resources namespace
if len(parts) == 1 {
// Simple resource type
return NewResourceType(builtInResourceNamespace, parts[0]), nil
} else if strings.Contains(parts[0], ".") {
// Handle resource types (Microsoft.Compute/virtualMachines, Microsoft.Network/virtualNetworks/subnets)
// it is a full type name
return NewResourceType(parts[0], strings.Join(parts[1:], "/")), nil
} else {
// Check if ResourceID
id, err := ParseResourceID(resourceIDOrType)
if err != nil {
return ResourceType{}, err
}
return NewResourceType(id.ResourceType.Namespace, id.ResourceType.Type), nil
}
}
func (t ResourceType) lastType() string {
return t.Types[len(t.Types)-1]
}

View file

@ -0,0 +1,98 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package policy
import (
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
)
// BearerTokenOptions configures the bearer token policy's behavior.
type BearerTokenOptions struct {
// AuxiliaryTenants are additional tenant IDs for authenticating cross-tenant requests.
// The policy will add a token from each of these tenants to every request. The
// authenticating user or service principal must be a guest in these tenants, and the
// policy's credential must support multitenant authentication.
AuxiliaryTenants []string
// Scopes contains the list of permission scopes required for the token.
Scopes []string
}
// RegistrationOptions configures the registration policy's behavior.
// All zero-value fields will be initialized with their default values.
type RegistrationOptions struct {
policy.ClientOptions
// MaxAttempts is the total number of times to attempt automatic registration
// in the event that an attempt fails.
// The default value is 3.
// Set to a value less than zero to disable the policy.
MaxAttempts int
// PollingDelay is the amount of time to sleep between polling intervals.
// The default value is 15 seconds.
// A value less than zero means no delay between polling intervals (not recommended).
PollingDelay time.Duration
// PollingDuration is the amount of time to wait before abandoning polling.
// The default valule is 5 minutes.
// NOTE: Setting this to a small value might cause the policy to prematurely fail.
PollingDuration time.Duration
}
// ClientOptions contains configuration settings for a client's pipeline.
type ClientOptions struct {
policy.ClientOptions
// AuxiliaryTenants are additional tenant IDs for authenticating cross-tenant requests.
// The client will add a token from each of these tenants to every request. The
// authenticating user or service principal must be a guest in these tenants, and the
// client's credential must support multitenant authentication.
AuxiliaryTenants []string
// DisableRPRegistration disables the auto-RP registration policy. Defaults to false.
DisableRPRegistration bool
}
// Clone return a deep copy of the current options.
func (o *ClientOptions) Clone() *ClientOptions {
if o == nil {
return nil
}
copiedOptions := *o
copiedOptions.Cloud.Services = copyMap(copiedOptions.Cloud.Services)
copiedOptions.Logging.AllowedHeaders = copyArray(copiedOptions.Logging.AllowedHeaders)
copiedOptions.Logging.AllowedQueryParams = copyArray(copiedOptions.Logging.AllowedQueryParams)
copiedOptions.Retry.StatusCodes = copyArray(copiedOptions.Retry.StatusCodes)
copiedOptions.PerRetryPolicies = copyArray(copiedOptions.PerRetryPolicies)
copiedOptions.PerCallPolicies = copyArray(copiedOptions.PerCallPolicies)
return &copiedOptions
}
// copyMap return a new map with all the key value pair in the src map
func copyMap[K comparable, V any](src map[K]V) map[K]V {
if src == nil {
return nil
}
copiedMap := make(map[K]V)
for k, v := range src {
copiedMap[k] = v
}
return copiedMap
}
// copyMap return a new array with all the elements in the src array
func copyArray[T any](src []T) []T {
if src == nil {
return nil
}
copiedArray := make([]T, len(src))
copy(copiedArray, src)
return copiedArray
}

View file

@ -0,0 +1,23 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package arm
import (
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource"
)
// RootResourceID defines the tenant as the root parent of all other ResourceID.
var RootResourceID = resource.RootResourceID
// ResourceID represents a resource ID such as `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myRg`.
// Don't create this type directly, use ParseResourceID instead.
type ResourceID = resource.ResourceID
// ParseResourceID parses a string to an instance of ResourceID
func ParseResourceID(id string) (*ResourceID, error) {
return resource.ParseResourceID(id)
}

View file

@ -0,0 +1,40 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package arm
import (
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource"
)
// SubscriptionResourceType is the ResourceType of a subscription
var SubscriptionResourceType = resource.SubscriptionResourceType
// ResourceGroupResourceType is the ResourceType of a resource group
var ResourceGroupResourceType = resource.ResourceGroupResourceType
// TenantResourceType is the ResourceType of a tenant
var TenantResourceType = resource.TenantResourceType
// ProviderResourceType is the ResourceType of a provider
var ProviderResourceType = resource.ProviderResourceType
// ResourceType represents an Azure resource type, e.g. "Microsoft.Network/virtualNetworks/subnets".
// Don't create this type directly, use ParseResourceType or NewResourceType instead.
type ResourceType = resource.ResourceType
// NewResourceType creates an instance of ResourceType using a provider namespace
// such as "Microsoft.Network" and type such as "virtualNetworks/subnets".
func NewResourceType(providerNamespace, typeName string) ResourceType {
return resource.NewResourceType(providerNamespace, typeName)
}
// ParseResourceType parses the ResourceType from a resource type string (e.g. Microsoft.Network/virtualNetworks/subsets)
// or a resource identifier string.
// e.g. /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myRg/providers/Microsoft.Network/virtualNetworks/vnet/subnets/mySubnet)
func ParseResourceType(resourceIDOrType string) (ResourceType, error) {
return resource.ParseResourceType(resourceIDOrType)
}

View file

@ -0,0 +1,65 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package runtime
import (
"errors"
"reflect"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
armpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported"
azpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
)
// NewPipeline creates a pipeline from connection options. Policies from ClientOptions are
// placed after policies from PipelineOptions. The telemetry policy, when enabled, will
// use the specified module and version info.
func NewPipeline(module, version string, cred azcore.TokenCredential, plOpts azruntime.PipelineOptions, options *armpolicy.ClientOptions) (azruntime.Pipeline, error) {
if options == nil {
options = &armpolicy.ClientOptions{}
}
conf, err := getConfiguration(&options.ClientOptions)
if err != nil {
return azruntime.Pipeline{}, err
}
authPolicy := NewBearerTokenPolicy(cred, &armpolicy.BearerTokenOptions{
AuxiliaryTenants: options.AuxiliaryTenants,
Scopes: []string{conf.Audience + "/.default"},
})
perRetry := make([]azpolicy.Policy, len(plOpts.PerRetry), len(plOpts.PerRetry)+1)
copy(perRetry, plOpts.PerRetry)
plOpts.PerRetry = append(perRetry, authPolicy, exported.PolicyFunc(httpTraceNamespacePolicy))
if !options.DisableRPRegistration {
regRPOpts := armpolicy.RegistrationOptions{ClientOptions: options.ClientOptions}
regPolicy, err := NewRPRegistrationPolicy(cred, &regRPOpts)
if err != nil {
return azruntime.Pipeline{}, err
}
perCall := make([]azpolicy.Policy, len(plOpts.PerCall), len(plOpts.PerCall)+1)
copy(perCall, plOpts.PerCall)
plOpts.PerCall = append(perCall, regPolicy)
}
if plOpts.APIVersion.Name == "" {
plOpts.APIVersion.Name = "api-version"
}
return azruntime.NewPipeline(module, version, plOpts, &options.ClientOptions), nil
}
func getConfiguration(o *azpolicy.ClientOptions) (cloud.ServiceConfiguration, error) {
c := cloud.AzurePublic
if !reflect.ValueOf(o.Cloud).IsZero() {
c = o.Cloud
}
if conf, ok := c.Services[cloud.ResourceManager]; ok && conf.Endpoint != "" && conf.Audience != "" {
return conf, nil
} else {
return conf, errors.New("provided Cloud field is missing Azure Resource Manager configuration")
}
}

View file

@ -0,0 +1,145 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package runtime
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
armpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared"
azpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/temporal"
)
const headerAuxiliaryAuthorization = "x-ms-authorization-auxiliary"
// acquiringResourceState holds data for an auxiliary token request
type acquiringResourceState struct {
ctx context.Context
p *BearerTokenPolicy
tenant string
}
// acquireAuxToken acquires a token from an auxiliary tenant. Only one thread/goroutine at a time ever calls this function.
func acquireAuxToken(state acquiringResourceState) (newResource azcore.AccessToken, newExpiration time.Time, err error) {
tk, err := state.p.cred.GetToken(state.ctx, azpolicy.TokenRequestOptions{
EnableCAE: true,
Scopes: state.p.scopes,
TenantID: state.tenant,
})
if err != nil {
return azcore.AccessToken{}, time.Time{}, err
}
return tk, tk.ExpiresOn, nil
}
// BearerTokenPolicy authorizes requests with bearer tokens acquired from a TokenCredential.
type BearerTokenPolicy struct {
auxResources map[string]*temporal.Resource[azcore.AccessToken, acquiringResourceState]
btp *azruntime.BearerTokenPolicy
cred azcore.TokenCredential
scopes []string
}
// NewBearerTokenPolicy creates a policy object that authorizes requests with bearer tokens.
// cred: an azcore.TokenCredential implementation such as a credential object from azidentity
// opts: optional settings. Pass nil to accept default values; this is the same as passing a zero-value options.
func NewBearerTokenPolicy(cred azcore.TokenCredential, opts *armpolicy.BearerTokenOptions) *BearerTokenPolicy {
if opts == nil {
opts = &armpolicy.BearerTokenOptions{}
}
p := &BearerTokenPolicy{cred: cred}
p.auxResources = make(map[string]*temporal.Resource[azcore.AccessToken, acquiringResourceState], len(opts.AuxiliaryTenants))
for _, t := range opts.AuxiliaryTenants {
p.auxResources[t] = temporal.NewResource(acquireAuxToken)
}
p.scopes = make([]string, len(opts.Scopes))
copy(p.scopes, opts.Scopes)
p.btp = azruntime.NewBearerTokenPolicy(cred, opts.Scopes, &azpolicy.BearerTokenOptions{
AuthorizationHandler: azpolicy.AuthorizationHandler{
OnChallenge: p.onChallenge,
OnRequest: p.onRequest,
},
})
return p
}
func (b *BearerTokenPolicy) onChallenge(req *azpolicy.Request, res *http.Response, authNZ func(azpolicy.TokenRequestOptions) error) error {
challenge := res.Header.Get(shared.HeaderWWWAuthenticate)
claims, err := parseChallenge(challenge)
if err != nil {
// the challenge contains claims we can't parse
return err
} else if claims != "" {
// request a new token having the specified claims, send the request again
return authNZ(azpolicy.TokenRequestOptions{Claims: claims, EnableCAE: true, Scopes: b.scopes})
}
// auth challenge didn't include claims, so this is a simple authorization failure
return azruntime.NewResponseError(res)
}
// onRequest authorizes requests with one or more bearer tokens
func (b *BearerTokenPolicy) onRequest(req *azpolicy.Request, authNZ func(azpolicy.TokenRequestOptions) error) error {
// authorize the request with a token for the primary tenant
err := authNZ(azpolicy.TokenRequestOptions{EnableCAE: true, Scopes: b.scopes})
if err != nil || len(b.auxResources) == 0 {
return err
}
// add tokens for auxiliary tenants
as := acquiringResourceState{
ctx: req.Raw().Context(),
p: b,
}
auxTokens := make([]string, 0, len(b.auxResources))
for tenant, er := range b.auxResources {
as.tenant = tenant
auxTk, err := er.Get(as)
if err != nil {
return err
}
auxTokens = append(auxTokens, fmt.Sprintf("%s%s", shared.BearerTokenPrefix, auxTk.Token))
}
req.Raw().Header.Set(headerAuxiliaryAuthorization, strings.Join(auxTokens, ", "))
return nil
}
// Do authorizes a request with a bearer token
func (b *BearerTokenPolicy) Do(req *azpolicy.Request) (*http.Response, error) {
return b.btp.Do(req)
}
// parseChallenge parses claims from an authentication challenge issued by ARM so a client can request a token
// that will satisfy conditional access policies. It returns a non-nil error when the given value contains
// claims it can't parse. If the value contains no claims, it returns an empty string and a nil error.
func parseChallenge(wwwAuthenticate string) (string, error) {
claims := ""
var err error
for _, param := range strings.Split(wwwAuthenticate, ",") {
if _, after, found := strings.Cut(param, "claims="); found {
if claims != "" {
// The header contains multiple challenges, at least two of which specify claims. The specs allow this
// but it's unclear what a client should do in this case and there's as yet no concrete example of it.
err = fmt.Errorf("found multiple claims challenges in %q", wwwAuthenticate)
break
}
// trim stuff that would get an error from RawURLEncoding; claims may or may not be padded
claims = strings.Trim(after, `\"=`)
// we don't return this error because it's something unhelpful like "illegal base64 data at input byte 42"
if b, decErr := base64.RawURLEncoding.DecodeString(claims); decErr == nil {
claims = string(b)
} else {
err = fmt.Errorf("failed to parse claims from %q", wwwAuthenticate)
break
}
}
}
return claims, err
}

View file

@ -0,0 +1,347 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package runtime
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
armpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared"
azpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/log"
)
const (
// LogRPRegistration entries contain information specific to the automatic registration of an RP.
// Entries of this classification are written IFF the policy needs to take any action.
LogRPRegistration log.Event = "RPRegistration"
)
// init sets any default values
func setDefaults(r *armpolicy.RegistrationOptions) {
if r.MaxAttempts == 0 {
r.MaxAttempts = 3
} else if r.MaxAttempts < 0 {
r.MaxAttempts = 0
}
if r.PollingDelay == 0 {
r.PollingDelay = 15 * time.Second
} else if r.PollingDelay < 0 {
r.PollingDelay = 0
}
if r.PollingDuration == 0 {
r.PollingDuration = 5 * time.Minute
}
}
// NewRPRegistrationPolicy creates a policy object configured using the specified options.
// The policy controls whether an unregistered resource provider should automatically be
// registered. See https://aka.ms/rps-not-found for more information.
func NewRPRegistrationPolicy(cred azcore.TokenCredential, o *armpolicy.RegistrationOptions) (azpolicy.Policy, error) {
if o == nil {
o = &armpolicy.RegistrationOptions{}
}
conf, err := getConfiguration(&o.ClientOptions)
if err != nil {
return nil, err
}
authPolicy := NewBearerTokenPolicy(cred, &armpolicy.BearerTokenOptions{Scopes: []string{conf.Audience + "/.default"}})
p := &rpRegistrationPolicy{
endpoint: conf.Endpoint,
pipeline: runtime.NewPipeline(shared.Module, shared.Version, runtime.PipelineOptions{PerRetry: []azpolicy.Policy{authPolicy}}, &o.ClientOptions),
options: *o,
}
// init the copy
setDefaults(&p.options)
return p, nil
}
type rpRegistrationPolicy struct {
endpoint string
pipeline runtime.Pipeline
options armpolicy.RegistrationOptions
}
func (r *rpRegistrationPolicy) Do(req *azpolicy.Request) (*http.Response, error) {
if r.options.MaxAttempts == 0 {
// policy is disabled
return req.Next()
}
const registeredState = "Registered"
var rp string
var resp *http.Response
for attempts := 0; attempts < r.options.MaxAttempts; attempts++ {
var err error
// make the original request
resp, err = req.Next()
// getting a 409 is the first indication that the RP might need to be registered, check error response
if err != nil || resp.StatusCode != http.StatusConflict {
return resp, err
}
var reqErr requestError
if err = runtime.UnmarshalAsJSON(resp, &reqErr); err != nil {
return resp, err
}
if reqErr.ServiceError == nil {
// missing service error info. just return the response
// to the caller so its error unmarshalling will kick in
return resp, err
}
if !isUnregisteredRPCode(reqErr.ServiceError.Code) {
// not a 409 due to unregistered RP. just return the response
// to the caller so its error unmarshalling will kick in
return resp, err
}
// RP needs to be registered. start by getting the subscription ID from the original request
subID, err := getSubscription(req.Raw().URL.Path)
if err != nil {
return resp, err
}
// now get the RP from the error
rp, err = getProvider(reqErr)
if err != nil {
return resp, err
}
logRegistrationExit := func(v interface{}) {
log.Writef(LogRPRegistration, "END registration for %s: %v", rp, v)
}
log.Writef(LogRPRegistration, "BEGIN registration for %s", rp)
// create client and make the registration request
// we use the scheme and host from the original request
rpOps := &providersOperations{
p: r.pipeline,
u: r.endpoint,
subID: subID,
}
if _, err = rpOps.Register(&shared.ContextWithDeniedValues{Context: req.Raw().Context()}, rp); err != nil {
logRegistrationExit(err)
return resp, err
}
// RP was registered, however we need to wait for the registration to complete
pollCtx, pollCancel := context.WithTimeout(&shared.ContextWithDeniedValues{Context: req.Raw().Context()}, r.options.PollingDuration)
var lastRegState string
for {
// get the current registration state
getResp, err := rpOps.Get(pollCtx, rp)
if err != nil {
pollCancel()
logRegistrationExit(err)
return resp, err
}
if getResp.Provider.RegistrationState != nil && !strings.EqualFold(*getResp.Provider.RegistrationState, lastRegState) {
// registration state has changed, or was updated for the first time
lastRegState = *getResp.Provider.RegistrationState
log.Writef(LogRPRegistration, "registration state is %s", lastRegState)
}
if strings.EqualFold(lastRegState, registeredState) {
// registration complete
pollCancel()
logRegistrationExit(lastRegState)
break
}
// wait before trying again
select {
case <-time.After(r.options.PollingDelay):
// continue polling
case <-pollCtx.Done():
pollCancel()
logRegistrationExit(pollCtx.Err())
return resp, pollCtx.Err()
}
}
// RP was successfully registered, retry the original request
err = req.RewindBody()
if err != nil {
return resp, err
}
}
// if we get here it means we exceeded the number of attempts
return resp, fmt.Errorf("exceeded attempts to register %s", rp)
}
var unregisteredRPCodes = []string{
"MissingSubscriptionRegistration",
"MissingRegistrationForResourceProvider",
"Subscription Not Registered",
"SubscriptionNotRegistered",
}
func isUnregisteredRPCode(errorCode string) bool {
for _, code := range unregisteredRPCodes {
if strings.EqualFold(errorCode, code) {
return true
}
}
return false
}
func getSubscription(path string) (string, error) {
parts := strings.Split(path, "/")
for i, v := range parts {
if v == "subscriptions" && (i+1) < len(parts) {
return parts[i+1], nil
}
}
return "", fmt.Errorf("failed to obtain subscription ID from %s", path)
}
func getProvider(re requestError) (string, error) {
if len(re.ServiceError.Details) > 0 {
return re.ServiceError.Details[0].Target, nil
}
return "", errors.New("unexpected empty Details")
}
// minimal error definitions to simplify detection
type requestError struct {
ServiceError *serviceError `json:"error"`
}
type serviceError struct {
Code string `json:"code"`
Details []serviceErrorDetails `json:"details"`
}
type serviceErrorDetails struct {
Code string `json:"code"`
Target string `json:"target"`
}
///////////////////////////////////////////////////////////////////////////////////////////////
// the following code was copied from module armresources, providers.go and models.go
// only the minimum amount of code was copied to get this working and some edits were made.
///////////////////////////////////////////////////////////////////////////////////////////////
type providersOperations struct {
p runtime.Pipeline
u string
subID string
}
// Get - Gets the specified resource provider.
func (client *providersOperations) Get(ctx context.Context, resourceProviderNamespace string) (providerResponse, error) {
req, err := client.getCreateRequest(ctx, resourceProviderNamespace)
if err != nil {
return providerResponse{}, err
}
resp, err := client.p.Do(req)
if err != nil {
return providerResponse{}, err
}
result, err := client.getHandleResponse(resp)
if err != nil {
return providerResponse{}, err
}
return result, nil
}
// getCreateRequest creates the Get request.
func (client *providersOperations) getCreateRequest(ctx context.Context, resourceProviderNamespace string) (*azpolicy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}"
urlPath = strings.ReplaceAll(urlPath, "{resourceProviderNamespace}", url.PathEscape(resourceProviderNamespace))
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.u, urlPath))
if err != nil {
return nil, err
}
query := req.Raw().URL.Query()
query.Set("api-version", "2019-05-01")
req.Raw().URL.RawQuery = query.Encode()
return req, nil
}
// getHandleResponse handles the Get response.
func (client *providersOperations) getHandleResponse(resp *http.Response) (providerResponse, error) {
if !runtime.HasStatusCode(resp, http.StatusOK) {
return providerResponse{}, exported.NewResponseError(resp)
}
result := providerResponse{RawResponse: resp}
err := runtime.UnmarshalAsJSON(resp, &result.Provider)
if err != nil {
return providerResponse{}, err
}
return result, err
}
// Register - Registers a subscription with a resource provider.
func (client *providersOperations) Register(ctx context.Context, resourceProviderNamespace string) (providerResponse, error) {
req, err := client.registerCreateRequest(ctx, resourceProviderNamespace)
if err != nil {
return providerResponse{}, err
}
resp, err := client.p.Do(req)
if err != nil {
return providerResponse{}, err
}
result, err := client.registerHandleResponse(resp)
if err != nil {
return providerResponse{}, err
}
return result, nil
}
// registerCreateRequest creates the Register request.
func (client *providersOperations) registerCreateRequest(ctx context.Context, resourceProviderNamespace string) (*azpolicy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/register"
urlPath = strings.ReplaceAll(urlPath, "{resourceProviderNamespace}", url.PathEscape(resourceProviderNamespace))
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subID))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.u, urlPath))
if err != nil {
return nil, err
}
query := req.Raw().URL.Query()
query.Set("api-version", "2019-05-01")
req.Raw().URL.RawQuery = query.Encode()
return req, nil
}
// registerHandleResponse handles the Register response.
func (client *providersOperations) registerHandleResponse(resp *http.Response) (providerResponse, error) {
if !runtime.HasStatusCode(resp, http.StatusOK) {
return providerResponse{}, exported.NewResponseError(resp)
}
result := providerResponse{RawResponse: resp}
err := runtime.UnmarshalAsJSON(resp, &result.Provider)
if err != nil {
return providerResponse{}, err
}
return result, err
}
// ProviderResponse is the response envelope for operations that return a Provider type.
type providerResponse struct {
// Resource provider information.
Provider *provider
// RawResponse contains the underlying HTTP response.
RawResponse *http.Response
}
// Provider - Resource provider information.
type provider struct {
// The provider ID.
ID *string `json:"id,omitempty"`
// The namespace of the resource provider.
Namespace *string `json:"namespace,omitempty"`
// The registration policy of the resource provider.
RegistrationPolicy *string `json:"registrationPolicy,omitempty"`
// The registration state of the resource provider.
RegistrationState *string `json:"registrationState,omitempty"`
}

View file

@ -0,0 +1,30 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package runtime
import (
"net/http"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing"
)
// httpTraceNamespacePolicy is a policy that adds the az.namespace attribute to the current Span
func httpTraceNamespacePolicy(req *policy.Request) (resp *http.Response, err error) {
rawTracer := req.Raw().Context().Value(shared.CtxWithTracingTracer{})
if tracer, ok := rawTracer.(tracing.Tracer); ok && tracer.Enabled() {
rt, err := resource.ParseResourceType(req.Raw().URL.Path)
if err == nil {
// add the namespace attribute to the current span
span := tracer.SpanFromContext(req.Raw().Context())
span.SetAttributes(tracing.Attribute{Key: shared.TracingNamespaceAttrName, Value: rt.Namespace})
}
}
return req.Next()
}

View file

@ -0,0 +1,24 @@
//go:build go1.16
// +build go1.16
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package runtime
import "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
func init() {
cloud.AzureChina.Services[cloud.ResourceManager] = cloud.ServiceConfiguration{
Audience: "https://management.core.chinacloudapi.cn",
Endpoint: "https://management.chinacloudapi.cn",
}
cloud.AzureGovernment.Services[cloud.ResourceManager] = cloud.ServiceConfiguration{
Audience: "https://management.core.usgovcloudapi.net",
Endpoint: "https://management.usgovcloudapi.net",
}
cloud.AzurePublic.Services[cloud.ResourceManager] = cloud.ServiceConfiguration{
Audience: "https://management.core.windows.net/",
Endpoint: "https://management.azure.com",
}
}

View file

@ -0,0 +1,457 @@
# Release History
## 1.4.0 (2023-10-10)
### Bugs Fixed
* `ManagedIdentityCredential` will now retry when IMDS responds 410 or 503
## 1.4.0-beta.5 (2023-09-12)
### Features Added
* Service principal credentials can request CAE tokens
### Breaking Changes
> These changes affect only code written against a beta version such as v1.4.0-beta.4
* Whether `GetToken` requests a CAE token is now determined by `TokenRequestOptions.EnableCAE`. Azure
SDK clients which support CAE will set this option automatically. Credentials no longer request CAE
tokens by default or observe the environment variable "AZURE_IDENTITY_DISABLE_CP1".
### Bugs Fixed
* Credential chains such as `DefaultAzureCredential` now try their next credential, if any, when
managed identity authentication fails in a Docker Desktop container
([#21417](https://github.com/Azure/azure-sdk-for-go/issues/21417))
## 1.4.0-beta.4 (2023-08-16)
### Other Changes
* Upgraded dependencies
## 1.3.1 (2023-08-16)
### Other Changes
* Upgraded dependencies
## 1.4.0-beta.3 (2023-08-08)
### Bugs Fixed
* One invocation of `AzureCLICredential.GetToken()` and `OnBehalfOfCredential.GetToken()`
can no longer make two authentication attempts
## 1.4.0-beta.2 (2023-07-14)
### Other Changes
* `DefaultAzureCredentialOptions.TenantID` applies to workload identity authentication
* Upgraded dependencies
## 1.4.0-beta.1 (2023-06-06)
### Other Changes
* Re-enabled CAE support as in v1.3.0-beta.3
## 1.3.0 (2023-05-09)
### Breaking Changes
> These changes affect only code written against a beta version such as v1.3.0-beta.5
* Renamed `NewOnBehalfOfCredentialFromCertificate` to `NewOnBehalfOfCredentialWithCertificate`
* Renamed `NewOnBehalfOfCredentialFromSecret` to `NewOnBehalfOfCredentialWithSecret`
### Other Changes
* Upgraded to MSAL v1.0.0
## 1.3.0-beta.5 (2023-04-11)
### Breaking Changes
> These changes affect only code written against a beta version such as v1.3.0-beta.4
* Moved `NewWorkloadIdentityCredential()` parameters into `WorkloadIdentityCredentialOptions`.
The constructor now reads default configuration from environment variables set by the Azure
workload identity webhook by default.
([#20478](https://github.com/Azure/azure-sdk-for-go/pull/20478))
* Removed CAE support. It will return in v1.4.0-beta.1
([#20479](https://github.com/Azure/azure-sdk-for-go/pull/20479))
### Bugs Fixed
* Fixed an issue in `DefaultAzureCredential` that could cause the managed identity endpoint check to fail in rare circumstances.
## 1.3.0-beta.4 (2023-03-08)
### Features Added
* Added `WorkloadIdentityCredentialOptions.AdditionallyAllowedTenants` and `.DisableInstanceDiscovery`
### Bugs Fixed
* Credentials now synchronize within `GetToken()` so a single instance can be shared among goroutines
([#20044](https://github.com/Azure/azure-sdk-for-go/issues/20044))
### Other Changes
* Upgraded dependencies
## 1.2.2 (2023-03-07)
### Other Changes
* Upgraded dependencies
## 1.3.0-beta.3 (2023-02-07)
### Features Added
* By default, credentials set client capability "CP1" to enable support for
[Continuous Access Evaluation (CAE)](https://docs.microsoft.com/azure/active-directory/develop/app-resilience-continuous-access-evaluation).
This indicates to Azure Active Directory that your application can handle CAE claims challenges.
You can disable this behavior by setting the environment variable "AZURE_IDENTITY_DISABLE_CP1" to "true".
* `InteractiveBrowserCredentialOptions.LoginHint` enables pre-populating the login
prompt with a username ([#15599](https://github.com/Azure/azure-sdk-for-go/pull/15599))
* Service principal and user credentials support ADFS authentication on Azure Stack.
Specify "adfs" as the credential's tenant.
* Applications running in private or disconnected clouds can prevent credentials from
requesting Azure AD instance metadata by setting the `DisableInstanceDiscovery`
field on credential options.
* Many credentials can now be configured to authenticate in multiple tenants. The
options types for these credentials have an `AdditionallyAllowedTenants` field
that specifies additional tenants in which the credential may authenticate.
## 1.3.0-beta.2 (2023-01-10)
### Features Added
* Added `OnBehalfOfCredential` to support the on-behalf-of flow
([#16642](https://github.com/Azure/azure-sdk-for-go/issues/16642))
### Bugs Fixed
* `AzureCLICredential` reports token expiration in local time (should be UTC)
### Other Changes
* `AzureCLICredential` imposes its default timeout only when the `Context`
passed to `GetToken()` has no deadline
* Added `NewCredentialUnavailableError()`. This function constructs an error indicating
a credential can't authenticate and an encompassing `ChainedTokenCredential` should
try its next credential, if any.
## 1.3.0-beta.1 (2022-12-13)
### Features Added
* `WorkloadIdentityCredential` and `DefaultAzureCredential` support
Workload Identity Federation on Kubernetes. `DefaultAzureCredential`
support requires environment variable configuration as set by the
Workload Identity webhook.
([#15615](https://github.com/Azure/azure-sdk-for-go/issues/15615))
## 1.2.0 (2022-11-08)
### Other Changes
* This version includes all fixes and features from 1.2.0-beta.*
## 1.2.0-beta.3 (2022-10-11)
### Features Added
* `ManagedIdentityCredential` caches tokens in memory
### Bugs Fixed
* `ClientCertificateCredential` sends only the leaf cert for SNI authentication
## 1.2.0-beta.2 (2022-08-10)
### Features Added
* Added `ClientAssertionCredential` to enable applications to authenticate
with custom client assertions
### Other Changes
* Updated AuthenticationFailedError with links to TROUBLESHOOTING.md for relevant errors
* Upgraded `microsoft-authentication-library-for-go` requirement to v0.6.0
## 1.2.0-beta.1 (2022-06-07)
### Features Added
* `EnvironmentCredential` reads certificate passwords from `AZURE_CLIENT_CERTIFICATE_PASSWORD`
([#17099](https://github.com/Azure/azure-sdk-for-go/pull/17099))
## 1.1.0 (2022-06-07)
### Features Added
* `ClientCertificateCredential` and `ClientSecretCredential` support ESTS-R. First-party
applications can set environment variable `AZURE_REGIONAL_AUTHORITY_NAME` with a
region name.
([#15605](https://github.com/Azure/azure-sdk-for-go/issues/15605))
## 1.0.1 (2022-06-07)
### Other Changes
* Upgrade `microsoft-authentication-library-for-go` requirement to v0.5.1
([#18176](https://github.com/Azure/azure-sdk-for-go/issues/18176))
## 1.0.0 (2022-05-12)
### Features Added
* `DefaultAzureCredential` reads environment variable `AZURE_CLIENT_ID` for the
client ID of a user-assigned managed identity
([#17293](https://github.com/Azure/azure-sdk-for-go/pull/17293))
### Breaking Changes
* Removed `AuthorizationCodeCredential`. Use `InteractiveBrowserCredential` instead
to authenticate a user with the authorization code flow.
* Instances of `AuthenticationFailedError` are now returned by pointer.
* `GetToken()` returns `azcore.AccessToken` by value
### Bugs Fixed
* `AzureCLICredential` panics after receiving an unexpected error type
([#17490](https://github.com/Azure/azure-sdk-for-go/issues/17490))
### Other Changes
* `GetToken()` returns an error when the caller specifies no scope
* Updated to the latest versions of `golang.org/x/crypto`, `azcore` and `internal`
## 0.14.0 (2022-04-05)
### Breaking Changes
* This module now requires Go 1.18
* Removed `AuthorityHost`. Credentials are now configured for sovereign or private
clouds with the API in `azcore/cloud`, for example:
```go
// before
opts := azidentity.ClientSecretCredentialOptions{AuthorityHost: azidentity.AzureGovernment}
cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, &opts)
// after
import "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
opts := azidentity.ClientSecretCredentialOptions{}
opts.Cloud = cloud.AzureGovernment
cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, &opts)
```
## 0.13.2 (2022-03-08)
### Bugs Fixed
* Prevented a data race in `DefaultAzureCredential` and `ChainedTokenCredential`
([#17144](https://github.com/Azure/azure-sdk-for-go/issues/17144))
### Other Changes
* Upgraded App Service managed identity version from 2017-09-01 to 2019-08-01
([#17086](https://github.com/Azure/azure-sdk-for-go/pull/17086))
## 0.13.1 (2022-02-08)
### Features Added
* `EnvironmentCredential` supports certificate SNI authentication when
`AZURE_CLIENT_SEND_CERTIFICATE_CHAIN` is "true".
([#16851](https://github.com/Azure/azure-sdk-for-go/pull/16851))
### Bugs Fixed
* `ManagedIdentityCredential.GetToken()` now returns an error when configured for
a user assigned identity in Azure Cloud Shell (which doesn't support such identities)
([#16946](https://github.com/Azure/azure-sdk-for-go/pull/16946))
### Other Changes
* `NewDefaultAzureCredential()` logs non-fatal errors. These errors are also included in the
error returned by `DefaultAzureCredential.GetToken()` when it's unable to acquire a token
from any source. ([#15923](https://github.com/Azure/azure-sdk-for-go/issues/15923))
## 0.13.0 (2022-01-11)
### Breaking Changes
* Replaced `AuthenticationFailedError.RawResponse()` with a field having the same name
* Unexported `CredentialUnavailableError`
* Instances of `ChainedTokenCredential` will now skip looping through the list of source credentials and re-use the first successful credential on subsequent calls to `GetToken`.
* If `ChainedTokenCredentialOptions.RetrySources` is true, `ChainedTokenCredential` will continue to try all of the originally provided credentials each time the `GetToken` method is called.
* `ChainedTokenCredential.successfulCredential` will contain a reference to the last successful credential.
* `DefaultAzureCredenial` will also re-use the first successful credential on subsequent calls to `GetToken`.
* `DefaultAzureCredential.chain.successfulCredential` will also contain a reference to the last successful credential.
### Other Changes
* `ManagedIdentityCredential` no longer probes IMDS before requesting a token
from it. Also, an error response from IMDS no longer disables a credential
instance. Following an error, a credential instance will continue to send
requests to IMDS as necessary.
* Adopted MSAL for user and service principal authentication
* Updated `azcore` requirement to 0.21.0
## 0.12.0 (2021-11-02)
### Breaking Changes
* Raised minimum go version to 1.16
* Removed `NewAuthenticationPolicy()` from credentials. Clients should instead use azcore's
`runtime.NewBearerTokenPolicy()` to construct a bearer token authorization policy.
* The `AuthorityHost` field in credential options structs is now a custom type,
`AuthorityHost`, with underlying type `string`
* `NewChainedTokenCredential` has a new signature to accommodate a placeholder
options struct:
```go
// before
cred, err := NewChainedTokenCredential(credA, credB)
// after
cred, err := NewChainedTokenCredential([]azcore.TokenCredential{credA, credB}, nil)
```
* Removed `ExcludeAzureCLICredential`, `ExcludeEnvironmentCredential`, and `ExcludeMSICredential`
from `DefaultAzureCredentialOptions`
* `NewClientCertificateCredential` requires a `[]*x509.Certificate` and `crypto.PrivateKey` instead of
a path to a certificate file. Added `ParseCertificates` to simplify getting these in common cases:
```go
// before
cred, err := NewClientCertificateCredential("tenant", "client-id", "/cert.pem", nil)
// after
certData, err := os.ReadFile("/cert.pem")
certs, key, err := ParseCertificates(certData, password)
cred, err := NewClientCertificateCredential(tenantID, clientID, certs, key, nil)
```
* Removed `InteractiveBrowserCredentialOptions.ClientSecret` and `.Port`
* Removed `AADAuthenticationFailedError`
* Removed `id` parameter of `NewManagedIdentityCredential()`. User assigned identities are now
specified by `ManagedIdentityCredentialOptions.ID`:
```go
// before
cred, err := NewManagedIdentityCredential("client-id", nil)
// or, for a resource ID
opts := &ManagedIdentityCredentialOptions{ID: ResourceID}
cred, err := NewManagedIdentityCredential("/subscriptions/...", opts)
// after
clientID := ClientID("7cf7db0d-...")
opts := &ManagedIdentityCredentialOptions{ID: clientID}
// or, for a resource ID
resID: ResourceID("/subscriptions/...")
opts := &ManagedIdentityCredentialOptions{ID: resID}
cred, err := NewManagedIdentityCredential(opts)
```
* `DeviceCodeCredentialOptions.UserPrompt` has a new type: `func(context.Context, DeviceCodeMessage) error`
* Credential options structs now embed `azcore.ClientOptions`. In addition to changing literal initialization
syntax, this change renames `HTTPClient` fields to `Transport`.
* Renamed `LogCredential` to `EventCredential`
* `AzureCLICredential` no longer reads the environment variable `AZURE_CLI_PATH`
* `NewManagedIdentityCredential` no longer reads environment variables `AZURE_CLIENT_ID` and
`AZURE_RESOURCE_ID`. Use `ManagedIdentityCredentialOptions.ID` instead.
* Unexported `AuthenticationFailedError` and `CredentialUnavailableError` structs. In their place are two
interfaces having the same names.
### Bugs Fixed
* `AzureCLICredential.GetToken` no longer mutates its `opts.Scopes`
### Features Added
* Added connection configuration options to `DefaultAzureCredentialOptions`
* `AuthenticationFailedError.RawResponse()` returns the HTTP response motivating the error,
if available
### Other Changes
* `NewDefaultAzureCredential()` returns `*DefaultAzureCredential` instead of `*ChainedTokenCredential`
* Added `TenantID` field to `DefaultAzureCredentialOptions` and `AzureCLICredentialOptions`
## 0.11.0 (2021-09-08)
### Breaking Changes
* Unexported `AzureCLICredentialOptions.TokenProvider` and its type,
`AzureCLITokenProvider`
### Bug Fixes
* `ManagedIdentityCredential.GetToken` returns `CredentialUnavailableError`
when IMDS has no assigned identity, signaling `DefaultAzureCredential` to
try other credentials
## 0.10.0 (2021-08-30)
### Breaking Changes
* Update based on `azcore` refactor [#15383](https://github.com/Azure/azure-sdk-for-go/pull/15383)
## 0.9.3 (2021-08-20)
### Bugs Fixed
* `ManagedIdentityCredential.GetToken` no longer mutates its `opts.Scopes`
### Other Changes
* Bumps version of `azcore` to `v0.18.1`
## 0.9.2 (2021-07-23)
### Features Added
* Adding support for Service Fabric environment in `ManagedIdentityCredential`
* Adding an option for using a resource ID instead of client ID in `ManagedIdentityCredential`
## 0.9.1 (2021-05-24)
### Features Added
* Add LICENSE.txt and bump version information
## 0.9.0 (2021-05-21)
### Features Added
* Add support for authenticating in Azure Stack environments
* Enable user assigned identities for the IMDS scenario in `ManagedIdentityCredential`
* Add scope to resource conversion in `GetToken()` on `ManagedIdentityCredential`
## 0.8.0 (2021-01-20)
### Features Added
* Updating documentation
## 0.7.1 (2021-01-04)
### Features Added
* Adding port option to `InteractiveBrowserCredential`
## 0.7.0 (2020-12-11)
### Features Added
* Add `redirectURI` parameter back to authentication code flow
## 0.6.1 (2020-12-09)
### Features Added
* Updating query parameter in `ManagedIdentityCredential` and updating datetime string for parsing managed identity access tokens.
## 0.6.0 (2020-11-16)
### Features Added
* Remove `RedirectURL` parameter from auth code flow to align with the MSAL implementation which relies on the native client redirect URL.
## 0.5.0 (2020-10-30)
### Features Added
* Flattening credential options
## 0.4.3 (2020-10-21)
### Features Added
* Adding Azure Arc support in `ManagedIdentityCredential`
## 0.4.2 (2020-10-16)
### Features Added
* Typo fixes
## 0.4.1 (2020-10-16)
### Features Added
* Ensure authority hosts are only HTTPs
## 0.4.0 (2020-10-16)
### Features Added
* Adding options structs for credentials
## 0.3.0 (2020-10-09)
### Features Added
* Update `DeviceCodeCredential` callback
## 0.2.2 (2020-10-09)
### Features Added
* Add `AuthorizationCodeCredential`
## 0.2.1 (2020-10-06)
### Features Added
* Add `InteractiveBrowserCredential`
## 0.2.0 (2020-09-11)
### Features Added
* Refactor `azidentity` on top of `azcore` refactor
* Updated policies to conform to `policy.Policy` interface changes.
* Updated non-retriable errors to conform to `azcore.NonRetriableError`.
* Fixed calls to `Request.SetBody()` to include content type.
* Switched endpoints to string types and removed extra parsing code.
## 0.1.1 (2020-09-02)
### Features Added
* Add `AzureCLICredential` to `DefaultAzureCredential` chain
## 0.1.0 (2020-07-23)
### Features Added
* Initial Release. Azure Identity library that provides Azure Active Directory token authentication support for the SDK.

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

View file

@ -0,0 +1,307 @@
# Migrating from autorest/adal to azidentity
`azidentity` provides Azure Active Directory (Azure AD) authentication for the newest Azure SDK modules (`github.com/azure-sdk-for-go/sdk/...`). Older Azure SDK packages (`github.com/azure-sdk-for-go/services/...`) use types from `github.com/go-autorest/autorest/adal` instead.
This guide shows common authentication code using `autorest/adal` and its equivalent using `azidentity`.
## Table of contents
- [Acquire a token](#acquire-a-token)
- [Client certificate authentication](#client-certificate-authentication)
- [Client secret authentication](#client-secret-authentication)
- [Configuration](#configuration)
- [Device code authentication](#device-code-authentication)
- [Managed identity](#managed-identity)
- [Use azidentity credentials with older packages](#use-azidentity-credentials-with-older-packages)
## Configuration
### `autorest/adal`
Token providers require a token audience (resource identifier) and an instance of `adal.OAuthConfig`, which requires an Azure AD endpoint and tenant:
```go
import "github.com/Azure/go-autorest/autorest/adal"
oauthCfg, err := adal.NewOAuthConfig("https://login.chinacloudapi.cn", tenantID)
handle(err)
spt, err := adal.NewServicePrincipalTokenWithSecret(
*oauthCfg, clientID, "https://management.chinacloudapi.cn/", &adal.ServicePrincipalTokenSecret{ClientSecret: secret},
)
```
### `azidentity`
A credential instance can acquire tokens for any audience. The audience for each token is determined by the client requesting it. Credentials require endpoint configuration only for sovereign or private clouds. The `azcore/cloud` package has predefined configuration for sovereign clouds such as Azure China:
```go
import (
"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
clientOpts := azcore.ClientOptions{Cloud: cloud.AzureChina}
cred, err := azidentity.NewClientSecretCredential(
tenantID, clientID, secret, &azidentity.ClientSecretCredentialOptions{ClientOptions: clientOpts},
)
handle(err)
```
## Client secret authentication
### `autorest/adal`
```go
import (
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
)
oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID)
handle(err)
spt, err := adal.NewServicePrincipalTokenWithSecret(
*oauthCfg, clientID, "https://management.azure.com/", &adal.ServicePrincipalTokenSecret{ClientSecret: secret},
)
handle(err)
client := subscriptions.NewClient()
client.Authorizer = autorest.NewBearerAuthorizer(spt)
```
### `azidentity`
```go
import (
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions"
)
cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, nil)
handle(err)
client, err := armsubscriptions.NewClient(cred, nil)
handle(err)
```
## Client certificate authentication
### `autorest/adal`
```go
import (
"os"
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
)
certData, err := os.ReadFile("./example.pfx")
handle(err)
certificate, rsaPrivateKey, err := decodePkcs12(certData, "")
handle(err)
oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID)
handle(err)
spt, err := adal.NewServicePrincipalTokenFromCertificate(
*oauthConfig, clientID, certificate, rsaPrivateKey, "https://management.azure.com/",
)
client := subscriptions.NewClient()
client.Authorizer = autorest.NewBearerAuthorizer(spt)
```
### `azidentity`
```go
import (
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions"
)
certData, err := os.ReadFile("./example.pfx")
handle(err)
certs, key, err := azidentity.ParseCertificates(certData, nil)
handle(err)
cred, err = azidentity.NewClientCertificateCredential(tenantID, clientID, certs, key, nil)
handle(err)
client, err := armsubscriptions.NewClient(cred, nil)
handle(err)
```
## Managed identity
### `autorest/adal`
```go
import (
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
)
spt, err := adal.NewServicePrincipalTokenFromManagedIdentity("https://management.azure.com/", nil)
handle(err)
client := subscriptions.NewClient()
client.Authorizer = autorest.NewBearerAuthorizer(spt)
```
### `azidentity`
```go
import (
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions"
)
cred, err := azidentity.NewManagedIdentityCredential(nil)
handle(err)
client, err := armsubscriptions.NewClient(cred, nil)
handle(err)
```
### User-assigned identities
`autorest/adal`:
```go
import "github.com/Azure/go-autorest/autorest/adal"
opts := &adal.ManagedIdentityOptions{ClientID: "..."}
spt, err := adal.NewServicePrincipalTokenFromManagedIdentity("https://management.azure.com/")
handle(err)
```
`azidentity`:
```go
import "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
opts := azidentity.ManagedIdentityCredentialOptions{ID: azidentity.ClientID("...")}
cred, err := azidentity.NewManagedIdentityCredential(&opts)
handle(err)
```
## Device code authentication
### `autorest/adal`
```go
import (
"fmt"
"net/http"
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
)
oauthClient := &http.Client{}
oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID)
handle(err)
resource := "https://management.azure.com/"
deviceCode, err := adal.InitiateDeviceAuth(oauthClient, *oauthCfg, clientID, resource)
handle(err)
// display instructions, wait for the user to authenticate
fmt.Println(*deviceCode.Message)
token, err := adal.WaitForUserCompletion(oauthClient, deviceCode)
handle(err)
spt, err := adal.NewServicePrincipalTokenFromManualToken(*oauthCfg, clientID, resource, *token)
handle(err)
client := subscriptions.NewClient()
client.Authorizer = autorest.NewBearerAuthorizer(spt)
```
### `azidentity`
```go
import (
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions"
)
cred, err := azidentity.NewDeviceCodeCredential(nil)
handle(err)
client, err := armsubscriptions.NewSubscriptionsClient(cred, nil)
handle(err)
```
`azidentity.DeviceCodeCredential` will guide a user through authentication, printing instructions to the console by default. The user prompt is customizable. For more information, see the [package documentation](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DeviceCodeCredential).
## Acquire a token
### `autorest/adal`
```go
import "github.com/Azure/go-autorest/autorest/adal"
oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID)
handle(err)
spt, err := adal.NewServicePrincipalTokenWithSecret(
*oauthCfg, clientID, "https://vault.azure.net", &adal.ServicePrincipalTokenSecret{ClientSecret: secret},
)
err = spt.Refresh()
if err == nil {
token := spt.Token
}
```
### `azidentity`
In ordinary usage, application code doesn't need to request tokens from credentials directly. Azure SDK clients handle token acquisition and refreshing internally. However, applications may call `GetToken()` to do so. All credential types have this method.
```go
import (
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, nil)
handle(err)
tk, err := cred.GetToken(
context.TODO(), policy.TokenRequestOptions{Scopes: []string{"https://vault.azure.net/.default"}},
)
if err == nil {
token := tk.Token
}
```
Note that `azidentity` credentials use the Azure AD v2.0 endpoint, which requires OAuth 2 scopes instead of the resource identifiers `autorest/adal` expects. For more information, see [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent).
## Use azidentity credentials with older packages
The [azidext module](https://pkg.go.dev/github.com/jongio/azidext/go/azidext) provides an adapter for `azidentity` credential types. The adapter enables using the credential types with older Azure SDK clients. For example:
```go
import (
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions"
"github.com/jongio/azidext/go/azidext"
)
cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, nil)
handle(err)
client := subscriptions.NewClient()
client.Authorizer = azidext.NewTokenCredentialAdapter(cred, []string{"https://management.azure.com//.default"})
```
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-go%2Fsdk%2Fazidentity%2FMIGRATION.png)

View file

@ -0,0 +1,243 @@
# Azure Identity Client Module for Go
The Azure Identity module provides Azure Active Directory (Azure AD) token authentication support across the Azure SDK. It includes a set of `TokenCredential` implementations, which can be used with Azure SDK clients supporting token authentication.
[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/azidentity)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity)
| [Azure Active Directory documentation](https://docs.microsoft.com/azure/active-directory/)
| [Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/azidentity)
# Getting started
## Install the module
This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management.
Install the Azure Identity module:
```sh
go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity
```
## Prerequisites
- an [Azure subscription](https://azure.microsoft.com/free/)
- Go 1.18
### Authenticating during local development
When debugging and executing code locally, developers typically use their own accounts to authenticate calls to Azure services. The `azidentity` module supports authenticating through developer tools to simplify local development.
#### Authenticating via the Azure CLI
`DefaultAzureCredential` and `AzureCLICredential` can authenticate as the user
signed in to the [Azure CLI](https://docs.microsoft.com/cli/azure). To sign in to the Azure CLI, run `az login`. On a system with a default web browser, the Azure CLI will launch the browser to authenticate a user.
When no default browser is available, `az login` will use the device code
authentication flow. This can also be selected manually by running `az login --use-device-code`.
## Key concepts
### Credentials
A credential is a type which contains or can obtain the data needed for a
service client to authenticate requests. Service clients across the Azure SDK
accept a credential instance when they are constructed, and use that credential
to authenticate requests.
The `azidentity` module focuses on OAuth authentication with Azure Active
Directory (AAD). It offers a variety of credential types capable of acquiring
an Azure AD access token. See [Credential Types](#credential-types "Credential Types") for a list of this module's credential types.
### DefaultAzureCredential
`DefaultAzureCredential` is appropriate for most apps that will be deployed to Azure. It combines common production credentials with development credentials. It attempts to authenticate via the following mechanisms in this order, stopping when one succeeds:
![DefaultAzureCredential authentication flow](img/mermaidjs/DefaultAzureCredentialAuthFlow.svg)
1. **Environment** - `DefaultAzureCredential` will read account information specified via [environment variables](#environment-variables) and use it to authenticate.
1. **Workload Identity** - If the app is deployed on Kubernetes with environment variables set by the workload identity webhook, `DefaultAzureCredential` will authenticate the configured identity.
1. **Managed Identity** - If the app is deployed to an Azure host with managed identity enabled, `DefaultAzureCredential` will authenticate with it.
1. **Azure CLI** - If a user or service principal has authenticated via the Azure CLI `az login` command, `DefaultAzureCredential` will authenticate that identity.
> Note: `DefaultAzureCredential` is intended to simplify getting started with the SDK by handling common scenarios with reasonable default behaviors. Developers who want more control or whose scenario isn't served by the default settings should use other credential types.
## Managed Identity
`DefaultAzureCredential` and `ManagedIdentityCredential` support
[managed identity authentication](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview)
in any hosting environment which supports managed identities, such as (this list is not exhaustive):
* [Azure App Service](https://docs.microsoft.com/azure/app-service/overview-managed-identity)
* [Azure Arc](https://docs.microsoft.com/azure/azure-arc/servers/managed-identity-authentication)
* [Azure Cloud Shell](https://docs.microsoft.com/azure/cloud-shell/msi-authorization)
* [Azure Kubernetes Service](https://docs.microsoft.com/azure/aks/use-managed-identity)
* [Azure Service Fabric](https://docs.microsoft.com/azure/service-fabric/concepts-managed-identity)
* [Azure Virtual Machines](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token)
## Examples
- [Authenticate with DefaultAzureCredential](#authenticate-with-defaultazurecredential "Authenticate with DefaultAzureCredential")
- [Define a custom authentication flow with ChainedTokenCredential](#define-a-custom-authentication-flow-with-chainedtokencredential "Define a custom authentication flow with ChainedTokenCredential")
- [Specify a user-assigned managed identity for DefaultAzureCredential](#specify-a-user-assigned-managed-identity-for-defaultazurecredential)
### Authenticate with DefaultAzureCredential
This example demonstrates authenticating a client from the `armresources` module with `DefaultAzureCredential`.
```go
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
// handle error
}
client := armresources.NewResourceGroupsClient("subscription ID", cred, nil)
```
### Specify a user-assigned managed identity for DefaultAzureCredential
To configure `DefaultAzureCredential` to authenticate a user-assigned managed identity, set the environment variable `AZURE_CLIENT_ID` to the identity's client ID.
### Define a custom authentication flow with `ChainedTokenCredential`
`DefaultAzureCredential` is generally the quickest way to get started developing apps for Azure. For more advanced scenarios, `ChainedTokenCredential` links multiple credential instances to be tried sequentially when authenticating. It will try each chained credential in turn until one provides a token or fails to authenticate due to an error.
The following example demonstrates creating a credential, which will attempt to authenticate using managed identity. It will fall back to authenticating via the Azure CLI when a managed identity is unavailable.
```go
managed, err := azidentity.NewManagedIdentityCredential(nil)
if err != nil {
// handle error
}
azCLI, err := azidentity.NewAzureCLICredential(nil)
if err != nil {
// handle error
}
chain, err := azidentity.NewChainedTokenCredential([]azcore.TokenCredential{managed, azCLI}, nil)
if err != nil {
// handle error
}
client := armresources.NewResourceGroupsClient("subscription ID", chain, nil)
```
## Credential Types
### Authenticating Azure Hosted Applications
|Credential|Usage
|-|-
|[DefaultAzureCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DefaultAzureCredential)|Simplified authentication experience for getting started developing Azure apps
|[ChainedTokenCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ChainedTokenCredential)|Define custom authentication flows, composing multiple credentials
|[EnvironmentCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#EnvironmentCredential)|Authenticate a service principal or user configured by environment variables
|[ManagedIdentityCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ManagedIdentityCredential)|Authenticate the managed identity of an Azure resource
|[WorkloadIdentityCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#WorkloadIdentityCredential)|Authenticate a workload identity on Kubernetes
### Authenticating Service Principals
|Credential|Usage
|-|-
|[ClientAssertionCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ClientAssertionCredential)|Authenticate a service principal with a signed client assertion
|[ClientCertificateCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ClientCertificateCredential)|Authenticate a service principal with a certificate
|[ClientSecretCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ClientSecretCredential)|Authenticate a service principal with a secret
### Authenticating Users
|Credential|Usage
|-|-
|[InteractiveBrowserCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#InteractiveBrowserCredential)|Interactively authenticate a user with the default web browser
|[DeviceCodeCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DeviceCodeCredential)|Interactively authenticate a user on a device with limited UI
|[UsernamePasswordCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#UsernamePasswordCredential)|Authenticate a user with a username and password
### Authenticating via Development Tools
|Credential|Usage
|-|-
|[AzureCLICredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#AzureCLICredential)|Authenticate as the user signed in to the Azure CLI
## Environment Variables
`DefaultAzureCredential` and `EnvironmentCredential` can be configured with environment variables. Each type of authentication requires values for specific variables:
#### Service principal with secret
|variable name|value
|-|-
|`AZURE_CLIENT_ID`|ID of an Azure Active Directory application
|`AZURE_TENANT_ID`|ID of the application's Azure Active Directory tenant
|`AZURE_CLIENT_SECRET`|one of the application's client secrets
#### Service principal with certificate
|variable name|value
|-|-
|`AZURE_CLIENT_ID`|ID of an Azure Active Directory application
|`AZURE_TENANT_ID`|ID of the application's Azure Active Directory tenant
|`AZURE_CLIENT_CERTIFICATE_PATH`|path to a certificate file including private key
|`AZURE_CLIENT_CERTIFICATE_PASSWORD`|password of the certificate file, if any
#### Username and password
|variable name|value
|-|-
|`AZURE_CLIENT_ID`|ID of an Azure Active Directory application
|`AZURE_USERNAME`|a username (usually an email address)
|`AZURE_PASSWORD`|that user's password
Configuration is attempted in the above order. For example, if values for a
client secret and certificate are both present, the client secret will be used.
## Troubleshooting
### Error Handling
Credentials return an `error` when they fail to authenticate or lack data they require to authenticate. For guidance on resolving errors from specific credential types, see the [troubleshooting guide](https://aka.ms/azsdk/go/identity/troubleshoot).
For more details on handling specific Azure Active Directory errors please refer to the
Azure Active Directory
[error code documentation](https://docs.microsoft.com/azure/active-directory/develop/reference-aadsts-error-codes).
### Logging
This module uses the classification-based logging implementation in `azcore`. To enable console logging for all SDK modules, set `AZURE_SDK_GO_LOGGING` to `all`. Use the `azcore/log` package to control log event output or to enable logs for `azidentity` only. For example:
```go
import azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log"
// print log output to stdout
azlog.SetListener(func(event azlog.Event, s string) {
fmt.Println(s)
})
// include only azidentity credential logs
azlog.SetEvents(azidentity.EventAuthentication)
```
Credentials log basic information only, such as `GetToken` success or failure and errors. These log entries don't contain authentication secrets but may contain sensitive information.
## Next steps
Client and management modules listed on the [Azure SDK releases page](https://azure.github.io/azure-sdk/releases/latest/go.html) support authenticating with `azidentity` credential types. You can learn more about using these libraries in their documentation, which is linked from the release page.
## Provide Feedback
If you encounter bugs or have suggestions, please
[open an issue](https://github.com/Azure/azure-sdk-for-go/issues).
## Contributing
This project welcomes contributions and suggestions. Most contributions require
you to agree to a Contributor License Agreement (CLA) declaring that you have
the right to, and actually do, grant us the rights to use your contribution.
For details, visit [https://cla.microsoft.com](https://cla.microsoft.com).
When you submit a pull request, a CLA-bot will automatically determine whether
you need to provide a CLA and decorate the PR appropriately (e.g., label,
comment). Simply follow the instructions provided by the bot. You will only
need to do this once across all repos using our CLA.
This project has adopted the
[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information, see the
[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any
additional questions or comments.
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-go%2Fsdk%2Fazidentity%2FREADME.png)

View file

@ -0,0 +1,207 @@
# Troubleshoot Azure Identity authentication issues
This troubleshooting guide covers failure investigation techniques, common errors for the credential types in the `azidentity` module, and mitigation steps to resolve these errors.
## Table of contents
- [Handle azidentity errors](#handle-azidentity-errors)
- [Permission issues](#permission-issues)
- [Find relevant information in errors](#find-relevant-information-in-errors)
- [Enable and configure logging](#enable-and-configure-logging)
- [Troubleshoot AzureCliCredential authentication issues](#troubleshoot-azureclicredential-authentication-issues)
- [Troubleshoot ClientCertificateCredential authentication issues](#troubleshoot-clientcertificatecredential-authentication-issues)
- [Troubleshoot ClientSecretCredential authentication issues](#troubleshoot-clientsecretcredential-authentication-issues)
- [Troubleshoot DefaultAzureCredential authentication issues](#troubleshoot-defaultazurecredential-authentication-issues)
- [Troubleshoot EnvironmentCredential authentication issues](#troubleshoot-environmentcredential-authentication-issues)
- [Troubleshoot ManagedIdentityCredential authentication issues](#troubleshoot-managedidentitycredential-authentication-issues)
- [Azure App Service and Azure Functions managed identity](#azure-app-service-and-azure-functions-managed-identity)
- [Azure Kubernetes Service managed identity](#azure-kubernetes-service-managed-identity)
- [Azure Virtual Machine managed identity](#azure-virtual-machine-managed-identity)
- [Troubleshoot UsernamePasswordCredential authentication issues](#troubleshoot-usernamepasswordcredential-authentication-issues)
- [Troubleshoot WorkloadIdentityCredential authentication issues](#troubleshoot-workloadidentitycredential-authentication-issues)
- [Get additional help](#get-additional-help)
## Handle azidentity errors
Any service client method that makes a request to the service may return an error due to authentication failure. This is because the credential authenticates on the first call to the service and on any subsequent call that needs to refresh an access token. Authentication errors include a description of the failure and possibly an error message from Azure Active Directory (Azure AD). Depending on the application, these errors may or may not be recoverable.
### Permission issues
Service client errors with a status code of 401 or 403 often indicate that authentication succeeded but the caller doesn't have permission to access the specified API. Check the service documentation to determine which RBAC roles are needed for the request, and ensure the authenticated user or service principal has the appropriate role assignments.
## Find relevant information in errors
Authentication errors can include responses from Azure AD and often contain information helpful in diagnosis. Consider the following error message:
```
ClientSecretCredential authentication failed
POST https://login.microsoftonline.com/3c631bb7-a9f7-4343-a5ba-a615913/oauth2/v2.0/token
--------------------------------------------------------------------------------
RESPONSE 401 Unauthorized
--------------------------------------------------------------------------------
{
"error": "invalid_client",
"error_description": "AADSTS7000215: Invalid client secret provided. Ensure the secret being sent in the request is the client secret value, not the client secret ID, for a secret added to app '86be4c01-505b-45e9-bfc0-9b825fd84'.\r\nTrace ID: 03da4b8e-5ffe-48ca-9754-aff4276f0100\r\nCorrelation ID: 7b12f9bb-2eef-42e3-ad75-eee69ec9088d\r\nTimestamp: 2022-03-02 18:25:26Z",
"error_codes": [
7000215
],
"timestamp": "2022-03-02 18:25:26Z",
"trace_id": "03da4b8e-5ffe-48ca-9754-aff4276f0100",
"correlation_id": "7b12f9bb-2eef-42e3-ad75-eee69ec9088d",
"error_uri": "https://login.microsoftonline.com/error?code=7000215"
}
--------------------------------------------------------------------------------
```
This error contains several pieces of information:
- __Failing Credential Type__: The type of credential that failed to authenticate. This can be helpful when diagnosing issues with chained credential types such as `DefaultAzureCredential` or `ChainedTokenCredential`.
- __Azure AD Error Code and Message__: The error code and message returned by Azure AD. This can give insight into the specific reason the request failed. For instance, in this case authentication failed because the provided client secret is incorrect. [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/reference-aadsts-error-codes#aadsts-error-codes) has more information on AADSTS error codes.
- __Correlation ID and Timestamp__: The correlation ID and timestamp identify the request in server-side logs. This information can be useful to support engineers diagnosing unexpected Azure AD failures.
### Enable and configure logging
`azidentity` provides the same logging capabilities as the rest of the Azure SDK. The simplest way to see the logs to help debug authentication issues is to print credential logs to the console.
```go
import azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log"
// print log output to stdout
azlog.SetListener(func(event azlog.Event, s string) {
fmt.Println(s)
})
// include only azidentity credential logs
azlog.SetEvents(azidentity.EventAuthentication)
```
<a id="dac"></a>
## Troubleshoot DefaultAzureCredential authentication issues
| Error |Description| Mitigation |
|---|---|---|
|"DefaultAzureCredential failed to acquire a token"|No credential in the `DefaultAzureCredential` chain provided a token|<ul><li>[Enable logging](#enable-and-configure-logging) to get further diagnostic information.</li><li>Consult the troubleshooting guide for underlying credential types for more information.</li><ul><li>[EnvironmentCredential](#troubleshoot-environmentcredential-authentication-issues)</li><li>[ManagedIdentityCredential](#troubleshoot-managedidentitycredential-authentication-issues)</li><li>[AzureCLICredential](#troubleshoot-azureclicredential-authentication-issues)</li></ul>|
|Error from the client with a status code of 401 or 403|Authentication succeeded but the authorizing Azure service responded with a 401 (Unauthorized), or 403 (Forbidden) status code|<ul><li>[Enable logging](#enable-and-configure-logging) to determine which credential in the chain returned the authenticating token.</li><li>If an unexpected credential is returning a token, check application configuration such as environment variables.</li><li>Ensure the correct role is assigned to the authenticated identity. For example, a service specific role rather than the subscription Owner role.</li></ul>|
|"managed identity timed out"|`DefaultAzureCredential` sets a short timeout on its first managed identity authentication attempt to prevent very long timeouts during local development when no managed identity is available. That timeout causes this error in production when an application requests a token before the hosting environment is ready to provide one.|Use [ManagedIdentityCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ManagedIdentityCredential) directly, at least in production. It doesn't set a timeout on its authentication attempts.|
## Troubleshoot EnvironmentCredential authentication issues
| Error Message |Description| Mitigation |
|---|---|---|
|Missing or incomplete environment variable configuration|A valid combination of environment variables wasn't set|Ensure the appropriate environment variables are set for the intended authentication method as described in the [module documentation](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#EnvironmentCredential)|
<a id="client-secret"></a>
## Troubleshoot ClientSecretCredential authentication issues
| Error Code | Issue | Mitigation |
|---|---|---|
|AADSTS7000215|An invalid client secret was provided.|Ensure the secret provided to the credential constructor is valid. If unsure, create a new client secret using the Azure portal. Details on creating a new client secret are in [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-2-create-a-new-application-secret).|
|AADSTS7000222|An expired client secret was provided.|Create a new client secret using the Azure portal. Details on creating a new client secret are in [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-2-create-a-new-application-secret).|
|AADSTS700016|The specified application wasn't found in the specified tenant.|Ensure the client and tenant IDs provided to the credential constructor are correct for your application registration. For multi-tenant apps, ensure the application has been added to the desired tenant by a tenant admin. To add a new application in the desired tenant, follow the [Azure AD instructions](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal).|
<a id="client-cert"></a>
## Troubleshoot ClientCertificateCredential authentication issues
| Error Code | Description | Mitigation |
|---|---|---|
|AADSTS700027|Client assertion contains an invalid signature.|Ensure the specified certificate has been uploaded to the application registration as described in [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-1-upload-a-certificate).|
|AADSTS700016|The specified application wasn't found in the specified tenant.|Ensure the client and tenant IDs provided to the credential constructor are correct for your application registration. For multi-tenant apps, ensure the application has been added to the desired tenant by a tenant admin. To add a new application in the desired tenant, follow the [Azure AD instructions](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal).|
<a id="username-password"></a>
## Troubleshoot UsernamePasswordCredential authentication issues
| Error Code | Issue | Mitigation |
|---|---|---|
|AADSTS50126|The provided username or password is invalid.|Ensure the username and password provided to the credential constructor are valid.|
<a id="managed-id"></a>
## Troubleshoot ManagedIdentityCredential authentication issues
`ManagedIdentityCredential` is designed to work on a variety of Azure hosts support managed identity. Configuration and troubleshooting vary from host to host. The below table lists the Azure hosts that can be assigned a managed identity and are supported by `ManagedIdentityCredential`.
|Host Environment| | |
|---|---|---|
|Azure Virtual Machines and Scale Sets|[Configuration](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/qs-configure-portal-windows-vm)|[Troubleshooting](#azure-virtual-machine-managed-identity)|
|Azure App Service and Azure Functions|[Configuration](https://docs.microsoft.com/azure/app-service/overview-managed-identity)|[Troubleshooting](#azure-app-service-and-azure-functions-managed-identity)|
|Azure Kubernetes Service|[Configuration](https://azure.github.io/aad-pod-identity/docs/)|[Troubleshooting](#azure-kubernetes-service-managed-identity)|
|Azure Arc|[Configuration](https://docs.microsoft.com/azure/azure-arc/servers/managed-identity-authentication)||
|Azure Service Fabric|[Configuration](https://docs.microsoft.com/azure/service-fabric/concepts-managed-identity)||
### Azure Virtual Machine managed identity
| Error Message |Description| Mitigation |
|---|---|---|
|The requested identity hasnt been assigned to this resource.|The IMDS endpoint responded with a status code of 400, indicating the requested identity isnt assigned to the VM.|If using a user assigned identity, ensure the specified ID is correct.<p/><p/>If using a system assigned identity, make sure it has been enabled as described in [managed identity documentation](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/qs-configure-portal-windows-vm#enable-system-assigned-managed-identity-on-an-existing-vm).|
|The request failed due to a gateway error.|The request to the IMDS endpoint failed due to a gateway error, 502 or 504 status code.|IMDS doesn't support requests via proxy or gateway. Disable proxies or gateways running on the VM for requests to the IMDS endpoint `http://169.254.169.254`|
|No response received from the managed identity endpoint.|No response was received for the request to IMDS or the request timed out.|<ul><li>Ensure the VM is configured for managed identity as described in [managed identity documentation](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/qs-configure-portal-windows-vm).</li><li>Verify the IMDS endpoint is reachable on the VM. See [below](#verify-imds-is-available-on-the-vm) for instructions.</li></ul>|
|Multiple attempts failed to obtain a token from the managed identity endpoint.|The credential has exhausted its retries for a token request.|<ul><li>Refer to the error message for more details on specific failures.<li>Ensure the VM is configured for managed identity as described in [managed identity documentation](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/qs-configure-portal-windows-vm).</li><li>Verify the IMDS endpoint is reachable on the VM. See [below](#verify-imds-is-available-on-the-vm) for instructions.</li></ul>|
#### Verify IMDS is available on the VM
If you have access to the VM, you can use `curl` to verify the managed identity endpoint is available.
```sh
curl 'http://169.254.169.254/metadata/identity/oauth2/token?resource=https://management.core.windows.net&api-version=2018-02-01' -H "Metadata: true"
```
> This command's output will contain an access token and SHOULD NOT BE SHARED, to avoid compromising account security.
### Azure App Service and Azure Functions managed identity
| Error Message |Description| Mitigation |
|---|---|---|
|Get "`http://169.254.169.254/...`" i/o timeout|The App Service host hasn't set environment variables for managed identity configuration.|<ul><li>Ensure the App Service is configured for managed identity as described in [App Service documentation](https://docs.microsoft.com/azure/app-service/overview-managed-identity).</li><li>Verify the App Service environment is properly configured and the managed identity endpoint is available. See [below](#verify-the-app-service-managed-identity-endpoint-is-available) for instructions.</li></ul>|
#### Verify the App Service managed identity endpoint is available
If you can SSH into the App Service, you can verify managed identity is available in the environment. First ensure the environment variables `IDENTITY_ENDPOINT` and `IDENTITY_SECRET` are set. Then you can verify the managed identity endpoint is available using `curl`.
```sh
curl "$IDENTITY_ENDPOINT?resource=https://management.core.windows.net&api-version=2019-08-01" -H "X-IDENTITY-HEADER: $IDENTITY_HEADER"
```
> This command's output will contain an access token and SHOULD NOT BE SHARED, to avoid compromising account security.
### Azure Kubernetes Service managed identity
#### Pod Identity
| Error Message |Description| Mitigation |
|---|---|---|
|"no azure identity found for request clientID"|The application attempted to authenticate before an identity was assigned to its pod|Verify the pod is labeled correctly. This also occurs when a correctly labeled pod authenticates before the identity is ready. To prevent initialization races, configure NMI to set the Retry-After header in its responses as described in [Pod Identity documentation](https://azure.github.io/aad-pod-identity/docs/configure/feature_flags/#set-retry-after-header-in-nmi-response).
<a id="azure-cli"></a>
## Troubleshoot AzureCliCredential authentication issues
| Error Message |Description| Mitigation |
|---|---|---|
|Azure CLI not found on path|The Azure CLI isnt installed or isn't on the application's path.|<ul><li>Ensure the Azure CLI is installed as described in [Azure CLI documentation](https://docs.microsoft.com/cli/azure/install-azure-cli).</li><li>Validate the installation location is in the application's `PATH` environment variable.</li></ul>|
|Please run 'az login' to set up account|No account is currently logged into the Azure CLI, or the login has expired.|<ul><li>Run `az login` to log into the Azure CLI. More information about Azure CLI authentication is available in the [Azure CLI documentation](https://docs.microsoft.com/cli/azure/authenticate-azure-cli).</li><li>Verify that the Azure CLI can obtain tokens. See [below](#verify-the-azure-cli-can-obtain-tokens) for instructions.</li></ul>|
#### Verify the Azure CLI can obtain tokens
You can manually verify that the Azure CLI can authenticate and obtain tokens. First, use the `account` command to verify the logged in account.
```azurecli
az account show
```
Once you've verified the Azure CLI is using the correct account, you can validate that it's able to obtain tokens for that account.
```azurecli
az account get-access-token --output json --resource https://management.core.windows.net
```
> This command's output will contain an access token and SHOULD NOT BE SHARED, to avoid compromising account security.
<a id="workload"></a>
## Troubleshoot `WorkloadIdentityCredential` authentication issues
| Error Message |Description| Mitigation |
|---|---|---|
|no client ID/tenant ID/token file specified|Incomplete configuration|In most cases these values are provided via environment variables set by Azure Workload Identity.<ul><li>If your application runs on Azure Kubernetes Servide (AKS) or a cluster that has deployed the Azure Workload Identity admission webhook, check pod labels and service account configuration. See the [AKS documentation](https://learn.microsoft.com/azure/aks/workload-identity-deploy-cluster#disable-workload-identity) and [Azure Workload Identity troubleshooting guide](https://azure.github.io/azure-workload-identity/docs/troubleshooting.html) for more details.<li>If your application isn't running on AKS or your cluster hasn't deployed the Workload Identity admission webhook, set these values in `WorkloadIdentityCredentialOptions`
## Get additional help
Additional information on ways to reach out for support can be found in [SUPPORT.md](https://github.com/Azure/azure-sdk-for-go/blob/main/SUPPORT.md).

View file

@ -0,0 +1,6 @@
{
"AssetsRepo": "Azure/azure-sdk-assets",
"AssetsRepoPrefixPath": "go",
"TagPrefix": "go/azidentity",
"Tag": "go/azidentity_6225ab0470"
}

View file

@ -0,0 +1,178 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"regexp"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/public"
)
const (
azureAdditionallyAllowedTenants = "AZURE_ADDITIONALLY_ALLOWED_TENANTS"
azureAuthorityHost = "AZURE_AUTHORITY_HOST"
azureClientCertificatePassword = "AZURE_CLIENT_CERTIFICATE_PASSWORD"
azureClientCertificatePath = "AZURE_CLIENT_CERTIFICATE_PATH"
azureClientID = "AZURE_CLIENT_ID"
azureClientSecret = "AZURE_CLIENT_SECRET"
azureFederatedTokenFile = "AZURE_FEDERATED_TOKEN_FILE"
azurePassword = "AZURE_PASSWORD"
azureRegionalAuthorityName = "AZURE_REGIONAL_AUTHORITY_NAME"
azureTenantID = "AZURE_TENANT_ID"
azureUsername = "AZURE_USERNAME"
organizationsTenantID = "organizations"
developerSignOnClientID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46"
defaultSuffix = "/.default"
)
var (
// capability CP1 indicates the client application is capable of handling CAE claims challenges
cp1 = []string{"CP1"}
errInvalidTenantID = errors.New("invalid tenantID. You can locate your tenantID by following the instructions listed here: https://learn.microsoft.com/partner-center/find-ids-and-domain-names")
)
// setAuthorityHost initializes the authority host for credentials. Precedence is:
// 1. cloud.Configuration.ActiveDirectoryAuthorityHost value set by user
// 2. value of AZURE_AUTHORITY_HOST
// 3. default: Azure Public Cloud
func setAuthorityHost(cc cloud.Configuration) (string, error) {
host := cc.ActiveDirectoryAuthorityHost
if host == "" {
if len(cc.Services) > 0 {
return "", errors.New("missing ActiveDirectoryAuthorityHost for specified cloud")
}
host = cloud.AzurePublic.ActiveDirectoryAuthorityHost
if envAuthorityHost := os.Getenv(azureAuthorityHost); envAuthorityHost != "" {
host = envAuthorityHost
}
}
u, err := url.Parse(host)
if err != nil {
return "", err
}
if u.Scheme != "https" {
return "", errors.New("cannot use an authority host without https")
}
return host, nil
}
// resolveAdditionalTenants returns a copy of tenants, simplified when tenants contains a wildcard
func resolveAdditionalTenants(tenants []string) []string {
if len(tenants) == 0 {
return nil
}
for _, t := range tenants {
// a wildcard makes all other values redundant
if t == "*" {
return []string{"*"}
}
}
cp := make([]string, len(tenants))
copy(cp, tenants)
return cp
}
// resolveTenant returns the correct tenant for a token request
func resolveTenant(defaultTenant, specified, credName string, additionalTenants []string) (string, error) {
if specified == "" || specified == defaultTenant {
return defaultTenant, nil
}
if defaultTenant == "adfs" {
return "", errors.New("ADFS doesn't support tenants")
}
if !validTenantID(specified) {
return "", errInvalidTenantID
}
for _, t := range additionalTenants {
if t == "*" || t == specified {
return specified, nil
}
}
return "", fmt.Errorf(`%s isn't configured to acquire tokens for tenant %q. To enable acquiring tokens for this tenant add it to the AdditionallyAllowedTenants on the credential options, or add "*" to allow acquiring tokens for any tenant`, credName, specified)
}
// validTenantID return true is it receives a valid tenantID, returns false otherwise
func validTenantID(tenantID string) bool {
match, err := regexp.MatchString("^[0-9a-zA-Z-.]+$", tenantID)
if err != nil {
return false
}
return match
}
func newPipelineAdapter(opts *azcore.ClientOptions) pipelineAdapter {
pl := runtime.NewPipeline(component, version, runtime.PipelineOptions{}, opts)
return pipelineAdapter{pl: pl}
}
type pipelineAdapter struct {
pl runtime.Pipeline
}
func (p pipelineAdapter) CloseIdleConnections() {
// do nothing
}
func (p pipelineAdapter) Do(r *http.Request) (*http.Response, error) {
req, err := runtime.NewRequest(r.Context(), r.Method, r.URL.String())
if err != nil {
return nil, err
}
if r.Body != nil && r.Body != http.NoBody {
// create a rewindable body from the existing body as required
var body io.ReadSeekCloser
if rsc, ok := r.Body.(io.ReadSeekCloser); ok {
body = rsc
} else {
b, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
body = streaming.NopCloser(bytes.NewReader(b))
}
err = req.SetBody(body, r.Header.Get("Content-Type"))
if err != nil {
return nil, err
}
}
resp, err := p.pl.Do(req)
if err != nil {
return nil, err
}
return resp, err
}
// enables fakes for test scenarios
type msalConfidentialClient interface {
AcquireTokenSilent(ctx context.Context, scopes []string, options ...confidential.AcquireSilentOption) (confidential.AuthResult, error)
AcquireTokenByAuthCode(ctx context.Context, code string, redirectURI string, scopes []string, options ...confidential.AcquireByAuthCodeOption) (confidential.AuthResult, error)
AcquireTokenByCredential(ctx context.Context, scopes []string, options ...confidential.AcquireByCredentialOption) (confidential.AuthResult, error)
AcquireTokenOnBehalfOf(ctx context.Context, userAssertion string, scopes []string, options ...confidential.AcquireOnBehalfOfOption) (confidential.AuthResult, error)
}
// enables fakes for test scenarios
type msalPublicClient interface {
AcquireTokenSilent(ctx context.Context, scopes []string, options ...public.AcquireSilentOption) (public.AuthResult, error)
AcquireTokenByUsernamePassword(ctx context.Context, scopes []string, username string, password string, options ...public.AcquireByUsernamePasswordOption) (public.AuthResult, error)
AcquireTokenByDeviceCode(ctx context.Context, scopes []string, options ...public.AcquireByDeviceCodeOption) (public.DeviceCode, error)
AcquireTokenByAuthCode(ctx context.Context, code string, redirectURI string, scopes []string, options ...public.AcquireByAuthCodeOption) (public.AuthResult, error)
AcquireTokenInteractive(ctx context.Context, scopes []string, options ...public.AcquireInteractiveOption) (public.AuthResult, error)
}

View file

@ -0,0 +1,183 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"regexp"
"runtime"
"strings"
"sync"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/internal/log"
)
const (
credNameAzureCLI = "AzureCLICredential"
timeoutCLIRequest = 10 * time.Second
)
// used by tests to fake invoking the CLI
type azureCLITokenProvider func(ctx context.Context, resource string, tenantID string) ([]byte, error)
// AzureCLICredentialOptions contains optional parameters for AzureCLICredential.
type AzureCLICredentialOptions struct {
// AdditionallyAllowedTenants specifies tenants for which the credential may acquire tokens, in addition
// to TenantID. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the
// logged in account can access.
AdditionallyAllowedTenants []string
// TenantID identifies the tenant the credential should authenticate in.
// Defaults to the CLI's default tenant, which is typically the home tenant of the logged in user.
TenantID string
tokenProvider azureCLITokenProvider
}
// init returns an instance of AzureCLICredentialOptions initialized with default values.
func (o *AzureCLICredentialOptions) init() {
if o.tokenProvider == nil {
o.tokenProvider = defaultTokenProvider
}
}
// AzureCLICredential authenticates as the identity logged in to the Azure CLI.
type AzureCLICredential struct {
mu *sync.Mutex
opts AzureCLICredentialOptions
}
// NewAzureCLICredential constructs an AzureCLICredential. Pass nil to accept default options.
func NewAzureCLICredential(options *AzureCLICredentialOptions) (*AzureCLICredential, error) {
cp := AzureCLICredentialOptions{}
if options != nil {
cp = *options
}
cp.init()
cp.AdditionallyAllowedTenants = resolveAdditionalTenants(cp.AdditionallyAllowedTenants)
return &AzureCLICredential{mu: &sync.Mutex{}, opts: cp}, nil
}
// GetToken requests a token from the Azure CLI. This credential doesn't cache tokens, so every call invokes the CLI.
// This method is called automatically by Azure SDK clients.
func (c *AzureCLICredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
if len(opts.Scopes) != 1 {
return azcore.AccessToken{}, errors.New(credNameAzureCLI + ": GetToken() requires exactly one scope")
}
tenant, err := resolveTenant(c.opts.TenantID, opts.TenantID, credNameAzureCLI, c.opts.AdditionallyAllowedTenants)
if err != nil {
return azcore.AccessToken{}, err
}
// pass the CLI an AAD v1 resource because we don't know which CLI version is installed and older ones don't support v2 scopes
opts.Scopes = []string{strings.TrimSuffix(opts.Scopes[0], defaultSuffix)}
c.mu.Lock()
defer c.mu.Unlock()
b, err := c.opts.tokenProvider(ctx, opts.Scopes[0], tenant)
if err != nil {
return azcore.AccessToken{}, err
}
at, err := c.createAccessToken(b)
if err != nil {
return azcore.AccessToken{}, err
}
msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", credNameAzureCLI, strings.Join(opts.Scopes, ", "))
log.Write(EventAuthentication, msg)
return at, nil
}
var defaultTokenProvider azureCLITokenProvider = func(ctx context.Context, resource string, tenantID string) ([]byte, error) {
match, err := regexp.MatchString("^[0-9a-zA-Z-.:/]+$", resource)
if err != nil {
return nil, err
}
if !match {
return nil, fmt.Errorf(`%s: unexpected scope "%s". Only alphanumeric characters and ".", ";", "-", and "/" are allowed`, credNameAzureCLI, resource)
}
// set a default timeout for this authentication iff the application hasn't done so already
var cancel context.CancelFunc
if _, hasDeadline := ctx.Deadline(); !hasDeadline {
ctx, cancel = context.WithTimeout(ctx, timeoutCLIRequest)
defer cancel()
}
commandLine := "az account get-access-token -o json --resource " + resource
if tenantID != "" {
commandLine += " --tenant " + tenantID
}
var cliCmd *exec.Cmd
if runtime.GOOS == "windows" {
dir := os.Getenv("SYSTEMROOT")
if dir == "" {
return nil, newCredentialUnavailableError(credNameAzureCLI, "environment variable 'SYSTEMROOT' has no value")
}
cliCmd = exec.CommandContext(ctx, "cmd.exe", "/c", commandLine)
cliCmd.Dir = dir
} else {
cliCmd = exec.CommandContext(ctx, "/bin/sh", "-c", commandLine)
cliCmd.Dir = "/bin"
}
cliCmd.Env = os.Environ()
var stderr bytes.Buffer
cliCmd.Stderr = &stderr
output, err := cliCmd.Output()
if err != nil {
msg := stderr.String()
var exErr *exec.ExitError
if errors.As(err, &exErr) && exErr.ExitCode() == 127 || strings.HasPrefix(msg, "'az' is not recognized") {
msg = "Azure CLI not found on path"
}
if msg == "" {
msg = err.Error()
}
return nil, newCredentialUnavailableError(credNameAzureCLI, msg)
}
return output, nil
}
func (c *AzureCLICredential) createAccessToken(tk []byte) (azcore.AccessToken, error) {
t := struct {
AccessToken string `json:"accessToken"`
Authority string `json:"_authority"`
ClientID string `json:"_clientId"`
ExpiresOn string `json:"expiresOn"`
IdentityProvider string `json:"identityProvider"`
IsMRRT bool `json:"isMRRT"`
RefreshToken string `json:"refreshToken"`
Resource string `json:"resource"`
TokenType string `json:"tokenType"`
UserID string `json:"userId"`
}{}
err := json.Unmarshal(tk, &t)
if err != nil {
return azcore.AccessToken{}, err
}
// the Azure CLI's "expiresOn" is local time
exp, err := time.ParseInLocation("2006-01-02 15:04:05.999999", t.ExpiresOn, time.Local)
if err != nil {
return azcore.AccessToken{}, fmt.Errorf("Error parsing token expiration time %q: %v", t.ExpiresOn, err)
}
converted := azcore.AccessToken{
Token: t.AccessToken,
ExpiresOn: exp.UTC(),
}
return converted, nil
}
var _ azcore.TokenCredential = (*AzureCLICredential)(nil)

View file

@ -0,0 +1,138 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/internal/log"
)
// ChainedTokenCredentialOptions contains optional parameters for ChainedTokenCredential.
type ChainedTokenCredentialOptions struct {
// RetrySources configures how the credential uses its sources. When true, the credential always attempts to
// authenticate through each source in turn, stopping when one succeeds. When false, the credential authenticates
// only through this first successful source--it never again tries the sources which failed.
RetrySources bool
}
// ChainedTokenCredential links together multiple credentials and tries them sequentially when authenticating. By default,
// it tries all the credentials until one authenticates, after which it always uses that credential.
type ChainedTokenCredential struct {
cond *sync.Cond
iterating bool
name string
retrySources bool
sources []azcore.TokenCredential
successfulCredential azcore.TokenCredential
}
// NewChainedTokenCredential creates a ChainedTokenCredential. Pass nil for options to accept defaults.
func NewChainedTokenCredential(sources []azcore.TokenCredential, options *ChainedTokenCredentialOptions) (*ChainedTokenCredential, error) {
if len(sources) == 0 {
return nil, errors.New("sources must contain at least one TokenCredential")
}
for _, source := range sources {
if source == nil { // cannot have a nil credential in the chain or else the application will panic when GetToken() is called on nil
return nil, errors.New("sources cannot contain nil")
}
}
cp := make([]azcore.TokenCredential, len(sources))
copy(cp, sources)
if options == nil {
options = &ChainedTokenCredentialOptions{}
}
return &ChainedTokenCredential{
cond: sync.NewCond(&sync.Mutex{}),
name: "ChainedTokenCredential",
retrySources: options.RetrySources,
sources: cp,
}, nil
}
// GetToken calls GetToken on the chained credentials in turn, stopping when one returns a token.
// This method is called automatically by Azure SDK clients.
func (c *ChainedTokenCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
if !c.retrySources {
// ensure only one goroutine at a time iterates the sources and perhaps sets c.successfulCredential
c.cond.L.Lock()
for {
if c.successfulCredential != nil {
c.cond.L.Unlock()
return c.successfulCredential.GetToken(ctx, opts)
}
if !c.iterating {
c.iterating = true
// allow other goroutines to wait while this one iterates
c.cond.L.Unlock()
break
}
c.cond.Wait()
}
}
var (
err error
errs []error
successfulCredential azcore.TokenCredential
token azcore.AccessToken
unavailableErr *credentialUnavailableError
)
for _, cred := range c.sources {
token, err = cred.GetToken(ctx, opts)
if err == nil {
log.Writef(EventAuthentication, "%s authenticated with %s", c.name, extractCredentialName(cred))
successfulCredential = cred
break
}
errs = append(errs, err)
// continue to the next source iff this one returned credentialUnavailableError
if !errors.As(err, &unavailableErr) {
break
}
}
if c.iterating {
c.cond.L.Lock()
// this is nil when all credentials returned an error
c.successfulCredential = successfulCredential
c.iterating = false
c.cond.L.Unlock()
c.cond.Broadcast()
}
// err is the error returned by the last GetToken call. It will be nil when that call succeeds
if err != nil {
// return credentialUnavailableError iff all sources did so; return AuthenticationFailedError otherwise
msg := createChainedErrorMessage(errs)
if errors.As(err, &unavailableErr) {
err = newCredentialUnavailableError(c.name, msg)
} else {
res := getResponseFromError(err)
err = newAuthenticationFailedError(c.name, msg, res, err)
}
}
return token, err
}
func createChainedErrorMessage(errs []error) string {
msg := "failed to acquire a token.\nAttempted credentials:"
for _, err := range errs {
msg += fmt.Sprintf("\n\t%s", err.Error())
}
return msg
}
func extractCredentialName(credential azcore.TokenCredential) string {
return strings.TrimPrefix(fmt.Sprintf("%T", credential), "*azidentity.")
}
var _ azcore.TokenCredential = (*ChainedTokenCredential)(nil)

View file

@ -0,0 +1,34 @@
# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file.
trigger:
branches:
include:
- main
- feature/*
- hotfix/*
- release/*
paths:
include:
- sdk/azidentity/
pr:
branches:
include:
- main
- feature/*
- hotfix/*
- release/*
paths:
include:
- sdk/azidentity/
stages:
- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml
parameters:
RunLiveTests: true
ServiceDirectory: 'azidentity'
CloudConfig:
Public:
SubscriptionConfigurations:
- $(sub-config-azure-cloud-test-resources)
# Contains alternate tenant, AAD app and cert info for testing
- $(sub-config-identity-test-resources)

View file

@ -0,0 +1,75 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
)
const credNameAssertion = "ClientAssertionCredential"
// ClientAssertionCredential authenticates an application with assertions provided by a callback function.
// This credential is for advanced scenarios. [ClientCertificateCredential] has a more convenient API for
// the most common assertion scenario, authenticating a service principal with a certificate. See
// [Azure AD documentation] for details of the assertion format.
//
// [Azure AD documentation]: https://docs.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials#assertion-format
type ClientAssertionCredential struct {
client *confidentialClient
}
// ClientAssertionCredentialOptions contains optional parameters for ClientAssertionCredential.
type ClientAssertionCredentialOptions struct {
azcore.ClientOptions
// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens.
// Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the
// application is registered.
AdditionallyAllowedTenants []string
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
// the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool
}
// NewClientAssertionCredential constructs a ClientAssertionCredential. The getAssertion function must be thread safe. Pass nil for options to accept defaults.
func NewClientAssertionCredential(tenantID, clientID string, getAssertion func(context.Context) (string, error), options *ClientAssertionCredentialOptions) (*ClientAssertionCredential, error) {
if getAssertion == nil {
return nil, errors.New("getAssertion must be a function that returns assertions")
}
if options == nil {
options = &ClientAssertionCredentialOptions{}
}
cred := confidential.NewCredFromAssertionCallback(
func(ctx context.Context, _ confidential.AssertionRequestOptions) (string, error) {
return getAssertion(ctx)
},
)
msalOpts := confidentialClientOptions{
AdditionallyAllowedTenants: options.AdditionallyAllowedTenants,
ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery,
}
c, err := newConfidentialClient(tenantID, clientID, credNameAssertion, cred, msalOpts)
if err != nil {
return nil, err
}
return &ClientAssertionCredential{client: c}, nil
}
// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.
func (c *ClientAssertionCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
return c.client.GetToken(ctx, opts)
}
var _ azcore.TokenCredential = (*ClientAssertionCredential)(nil)

View file

@ -0,0 +1,160 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"crypto"
"crypto/x509"
"encoding/pem"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
"golang.org/x/crypto/pkcs12"
)
const credNameCert = "ClientCertificateCredential"
// ClientCertificateCredentialOptions contains optional parameters for ClientCertificateCredential.
type ClientCertificateCredentialOptions struct {
azcore.ClientOptions
// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens.
// Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the
// application is registered.
AdditionallyAllowedTenants []string
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
// the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool
// SendCertificateChain controls whether the credential sends the public certificate chain in the x5c
// header of each token request's JWT. This is required for Subject Name/Issuer (SNI) authentication.
// Defaults to False.
SendCertificateChain bool
}
// ClientCertificateCredential authenticates a service principal with a certificate.
type ClientCertificateCredential struct {
client *confidentialClient
}
// NewClientCertificateCredential constructs a ClientCertificateCredential. Pass nil for options to accept defaults.
func NewClientCertificateCredential(tenantID string, clientID string, certs []*x509.Certificate, key crypto.PrivateKey, options *ClientCertificateCredentialOptions) (*ClientCertificateCredential, error) {
if len(certs) == 0 {
return nil, errors.New("at least one certificate is required")
}
if options == nil {
options = &ClientCertificateCredentialOptions{}
}
cred, err := confidential.NewCredFromCert(certs, key)
if err != nil {
return nil, err
}
msalOpts := confidentialClientOptions{
AdditionallyAllowedTenants: options.AdditionallyAllowedTenants,
ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery,
SendX5C: options.SendCertificateChain,
}
c, err := newConfidentialClient(tenantID, clientID, credNameCert, cred, msalOpts)
if err != nil {
return nil, err
}
return &ClientCertificateCredential{client: c}, nil
}
// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.
func (c *ClientCertificateCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
return c.client.GetToken(ctx, opts)
}
// ParseCertificates loads certificates and a private key, in PEM or PKCS12 format, for use with NewClientCertificateCredential.
// Pass nil for password if the private key isn't encrypted. This function can't decrypt keys in PEM format.
func ParseCertificates(certData []byte, password []byte) ([]*x509.Certificate, crypto.PrivateKey, error) {
var blocks []*pem.Block
var err error
if len(password) == 0 {
blocks, err = loadPEMCert(certData)
}
if len(blocks) == 0 || err != nil {
blocks, err = loadPKCS12Cert(certData, string(password))
}
if err != nil {
return nil, nil, err
}
var certs []*x509.Certificate
var pk crypto.PrivateKey
for _, block := range blocks {
switch block.Type {
case "CERTIFICATE":
c, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, nil, err
}
certs = append(certs, c)
case "PRIVATE KEY":
if pk != nil {
return nil, nil, errors.New("certData contains multiple private keys")
}
pk, err = x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
pk, err = x509.ParsePKCS1PrivateKey(block.Bytes)
}
if err != nil {
return nil, nil, err
}
case "RSA PRIVATE KEY":
if pk != nil {
return nil, nil, errors.New("certData contains multiple private keys")
}
pk, err = x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, nil, err
}
}
}
if len(certs) == 0 {
return nil, nil, errors.New("found no certificate")
}
if pk == nil {
return nil, nil, errors.New("found no private key")
}
return certs, pk, nil
}
func loadPEMCert(certData []byte) ([]*pem.Block, error) {
blocks := []*pem.Block{}
for {
var block *pem.Block
block, certData = pem.Decode(certData)
if block == nil {
break
}
blocks = append(blocks, block)
}
if len(blocks) == 0 {
return nil, errors.New("didn't find any PEM blocks")
}
return blocks, nil
}
func loadPKCS12Cert(certData []byte, password string) ([]*pem.Block, error) {
blocks, err := pkcs12.ToPEM(certData, password)
if err != nil {
return nil, err
}
if len(blocks) == 0 {
// not mentioning PKCS12 in this message because we end up here when certData is garbage
return nil, errors.New("didn't find any certificate content")
}
return blocks, err
}
var _ azcore.TokenCredential = (*ClientCertificateCredential)(nil)

View file

@ -0,0 +1,65 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
)
const credNameSecret = "ClientSecretCredential"
// ClientSecretCredentialOptions contains optional parameters for ClientSecretCredential.
type ClientSecretCredentialOptions struct {
azcore.ClientOptions
// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens.
// Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the
// application is registered.
AdditionallyAllowedTenants []string
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
// the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool
}
// ClientSecretCredential authenticates an application with a client secret.
type ClientSecretCredential struct {
client *confidentialClient
}
// NewClientSecretCredential constructs a ClientSecretCredential. Pass nil for options to accept defaults.
func NewClientSecretCredential(tenantID string, clientID string, clientSecret string, options *ClientSecretCredentialOptions) (*ClientSecretCredential, error) {
if options == nil {
options = &ClientSecretCredentialOptions{}
}
cred, err := confidential.NewCredFromSecret(clientSecret)
if err != nil {
return nil, err
}
msalOpts := confidentialClientOptions{
AdditionallyAllowedTenants: options.AdditionallyAllowedTenants,
ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery,
}
c, err := newConfidentialClient(tenantID, clientID, credNameSecret, cred, msalOpts)
if err != nil {
return nil, err
}
return &ClientSecretCredential{c}, nil
}
// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.
func (c *ClientSecretCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
return c.client.GetToken(ctx, opts)
}
var _ azcore.TokenCredential = (*ClientSecretCredential)(nil)

View file

@ -0,0 +1,156 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"errors"
"fmt"
"os"
"strings"
"sync"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/log"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
)
type confidentialClientOptions struct {
azcore.ClientOptions
AdditionallyAllowedTenants []string
// Assertion for on-behalf-of authentication
Assertion string
DisableInstanceDiscovery, SendX5C bool
}
// confidentialClient wraps the MSAL confidential client
type confidentialClient struct {
cae, noCAE msalConfidentialClient
caeMu, noCAEMu, clientMu *sync.Mutex
clientID, tenantID string
cred confidential.Credential
host string
name string
opts confidentialClientOptions
region string
}
func newConfidentialClient(tenantID, clientID, name string, cred confidential.Credential, opts confidentialClientOptions) (*confidentialClient, error) {
if !validTenantID(tenantID) {
return nil, errInvalidTenantID
}
host, err := setAuthorityHost(opts.Cloud)
if err != nil {
return nil, err
}
opts.AdditionallyAllowedTenants = resolveAdditionalTenants(opts.AdditionallyAllowedTenants)
return &confidentialClient{
caeMu: &sync.Mutex{},
clientID: clientID,
clientMu: &sync.Mutex{},
cred: cred,
host: host,
name: name,
noCAEMu: &sync.Mutex{},
opts: opts,
region: os.Getenv(azureRegionalAuthorityName),
tenantID: tenantID,
}, nil
}
// GetToken requests an access token from MSAL, checking the cache first.
func (c *confidentialClient) GetToken(ctx context.Context, tro policy.TokenRequestOptions) (azcore.AccessToken, error) {
if len(tro.Scopes) < 1 {
return azcore.AccessToken{}, fmt.Errorf("%s.GetToken() requires at least one scope", c.name)
}
// we don't resolve the tenant for managed identities because they acquire tokens only from their home tenants
if c.name != credNameManagedIdentity {
tenant, err := c.resolveTenant(tro.TenantID)
if err != nil {
return azcore.AccessToken{}, err
}
tro.TenantID = tenant
}
client, mu, err := c.client(ctx, tro)
if err != nil {
return azcore.AccessToken{}, err
}
mu.Lock()
defer mu.Unlock()
var ar confidential.AuthResult
if c.opts.Assertion != "" {
ar, err = client.AcquireTokenOnBehalfOf(ctx, c.opts.Assertion, tro.Scopes, confidential.WithClaims(tro.Claims), confidential.WithTenantID(tro.TenantID))
} else {
ar, err = client.AcquireTokenSilent(ctx, tro.Scopes, confidential.WithClaims(tro.Claims), confidential.WithTenantID(tro.TenantID))
if err != nil {
ar, err = client.AcquireTokenByCredential(ctx, tro.Scopes, confidential.WithClaims(tro.Claims), confidential.WithTenantID(tro.TenantID))
}
}
if err != nil {
// We could get a credentialUnavailableError from managed identity authentication because in that case the error comes from our code.
// We return it directly because it affects the behavior of credential chains. Otherwise, we return AuthenticationFailedError.
var unavailableErr *credentialUnavailableError
if !errors.As(err, &unavailableErr) {
res := getResponseFromError(err)
err = newAuthenticationFailedError(c.name, err.Error(), res, err)
}
} else {
msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", c.name, strings.Join(ar.GrantedScopes, ", "))
log.Write(EventAuthentication, msg)
}
return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err
}
func (c *confidentialClient) client(ctx context.Context, tro policy.TokenRequestOptions) (msalConfidentialClient, *sync.Mutex, error) {
c.clientMu.Lock()
defer c.clientMu.Unlock()
if tro.EnableCAE {
if c.cae == nil {
client, err := c.newMSALClient(true)
if err != nil {
return nil, nil, err
}
c.cae = client
}
return c.cae, c.caeMu, nil
}
if c.noCAE == nil {
client, err := c.newMSALClient(false)
if err != nil {
return nil, nil, err
}
c.noCAE = client
}
return c.noCAE, c.noCAEMu, nil
}
func (c *confidentialClient) newMSALClient(enableCAE bool) (msalConfidentialClient, error) {
authority := runtime.JoinPaths(c.host, c.tenantID)
o := []confidential.Option{
confidential.WithAzureRegion(c.region),
confidential.WithHTTPClient(newPipelineAdapter(&c.opts.ClientOptions)),
}
if enableCAE {
o = append(o, confidential.WithClientCapabilities(cp1))
}
if c.opts.SendX5C {
o = append(o, confidential.WithX5C())
}
if c.opts.DisableInstanceDiscovery || strings.ToLower(c.tenantID) == "adfs" {
o = append(o, confidential.WithInstanceDiscovery(false))
}
return confidential.New(authority, c.clientID, c.cred, o...)
}
// resolveTenant returns the correct tenant for a token request given the client's
// configuration, or an error when that configuration doesn't allow the specified tenant
func (c *confidentialClient) resolveTenant(specified string) (string, error) {
return resolveTenant(c.tenantID, specified, c.name, c.opts.AdditionallyAllowedTenants)
}

View file

@ -0,0 +1,196 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"errors"
"os"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/internal/log"
)
// DefaultAzureCredentialOptions contains optional parameters for DefaultAzureCredential.
// These options may not apply to all credentials in the chain.
type DefaultAzureCredentialOptions struct {
// ClientOptions has additional options for credentials that use an Azure SDK HTTP pipeline. These options don't apply
// to credential types that authenticate via external tools such as the Azure CLI.
azcore.ClientOptions
// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens. Add
// the wildcard value "*" to allow the credential to acquire tokens for any tenant. This value can also be
// set as a semicolon delimited list of tenants in the environment variable AZURE_ADDITIONALLY_ALLOWED_TENANTS.
AdditionallyAllowedTenants []string
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
// the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool
// TenantID sets the default tenant for authentication via the Azure CLI and workload identity.
TenantID string
}
// DefaultAzureCredential is a default credential chain for applications that will deploy to Azure.
// It combines credentials suitable for deployment with credentials suitable for local development.
// It attempts to authenticate with each of these credential types, in the following order, stopping
// when one provides a token:
//
// - [EnvironmentCredential]
// - [WorkloadIdentityCredential], if environment variable configuration is set by the Azure workload
// identity webhook. Use [WorkloadIdentityCredential] directly when not using the webhook or needing
// more control over its configuration.
// - [ManagedIdentityCredential]
// - [AzureCLICredential]
//
// Consult the documentation for these credential types for more information on how they authenticate.
// Once a credential has successfully authenticated, DefaultAzureCredential will use that credential for
// every subsequent authentication.
type DefaultAzureCredential struct {
chain *ChainedTokenCredential
}
// NewDefaultAzureCredential creates a DefaultAzureCredential. Pass nil for options to accept defaults.
func NewDefaultAzureCredential(options *DefaultAzureCredentialOptions) (*DefaultAzureCredential, error) {
var creds []azcore.TokenCredential
var errorMessages []string
if options == nil {
options = &DefaultAzureCredentialOptions{}
}
additionalTenants := options.AdditionallyAllowedTenants
if len(additionalTenants) == 0 {
if tenants := os.Getenv(azureAdditionallyAllowedTenants); tenants != "" {
additionalTenants = strings.Split(tenants, ";")
}
}
envCred, err := NewEnvironmentCredential(&EnvironmentCredentialOptions{
ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery,
additionallyAllowedTenants: additionalTenants,
})
if err == nil {
creds = append(creds, envCred)
} else {
errorMessages = append(errorMessages, "EnvironmentCredential: "+err.Error())
creds = append(creds, &defaultCredentialErrorReporter{credType: "EnvironmentCredential", err: err})
}
wic, err := NewWorkloadIdentityCredential(&WorkloadIdentityCredentialOptions{
AdditionallyAllowedTenants: additionalTenants,
ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery,
TenantID: options.TenantID,
})
if err == nil {
creds = append(creds, wic)
} else {
errorMessages = append(errorMessages, credNameWorkloadIdentity+": "+err.Error())
creds = append(creds, &defaultCredentialErrorReporter{credType: credNameWorkloadIdentity, err: err})
}
o := &ManagedIdentityCredentialOptions{ClientOptions: options.ClientOptions}
if ID, ok := os.LookupEnv(azureClientID); ok {
o.ID = ClientID(ID)
}
miCred, err := NewManagedIdentityCredential(o)
if err == nil {
creds = append(creds, &timeoutWrapper{mic: miCred, timeout: time.Second})
} else {
errorMessages = append(errorMessages, credNameManagedIdentity+": "+err.Error())
creds = append(creds, &defaultCredentialErrorReporter{credType: credNameManagedIdentity, err: err})
}
cliCred, err := NewAzureCLICredential(&AzureCLICredentialOptions{AdditionallyAllowedTenants: additionalTenants, TenantID: options.TenantID})
if err == nil {
creds = append(creds, cliCred)
} else {
errorMessages = append(errorMessages, credNameAzureCLI+": "+err.Error())
creds = append(creds, &defaultCredentialErrorReporter{credType: credNameAzureCLI, err: err})
}
if len(errorMessages) > 0 {
log.Writef(EventAuthentication, "NewDefaultAzureCredential failed to initialize some credentials:\n\t%s", strings.Join(errorMessages, "\n\t"))
}
chain, err := NewChainedTokenCredential(creds, nil)
if err != nil {
return nil, err
}
chain.name = "DefaultAzureCredential"
return &DefaultAzureCredential{chain: chain}, nil
}
// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.
func (c *DefaultAzureCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
return c.chain.GetToken(ctx, opts)
}
var _ azcore.TokenCredential = (*DefaultAzureCredential)(nil)
// defaultCredentialErrorReporter is a substitute for credentials that couldn't be constructed.
// Its GetToken method always returns a credentialUnavailableError having the same message as
// the error that prevented constructing the credential. This ensures the message is present
// in the error returned by ChainedTokenCredential.GetToken()
type defaultCredentialErrorReporter struct {
credType string
err error
}
func (d *defaultCredentialErrorReporter) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
if _, ok := d.err.(*credentialUnavailableError); ok {
return azcore.AccessToken{}, d.err
}
return azcore.AccessToken{}, newCredentialUnavailableError(d.credType, d.err.Error())
}
var _ azcore.TokenCredential = (*defaultCredentialErrorReporter)(nil)
// timeoutWrapper prevents a potentially very long timeout when managed identity isn't available
type timeoutWrapper struct {
mic *ManagedIdentityCredential
// timeout applies to all auth attempts until one doesn't time out
timeout time.Duration
}
// GetToken wraps DefaultAzureCredential's initial managed identity auth attempt with a short timeout
// because managed identity may not be available and connecting to IMDS can take several minutes to time out.
func (w *timeoutWrapper) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
var tk azcore.AccessToken
var err error
// no need to synchronize around this value because it's written only within ChainedTokenCredential's critical section
if w.timeout > 0 {
c, cancel := context.WithTimeout(ctx, w.timeout)
defer cancel()
tk, err = w.mic.GetToken(c, opts)
if isAuthFailedDueToContext(err) {
err = newCredentialUnavailableError(credNameManagedIdentity, "managed identity timed out. See https://aka.ms/azsdk/go/identity/troubleshoot#dac for more information")
} else {
// some managed identity implementation is available, so don't apply the timeout to future calls
w.timeout = 0
}
} else {
tk, err = w.mic.GetToken(ctx, opts)
}
return tk, err
}
// unwraps nested AuthenticationFailedErrors to get the root error
func isAuthFailedDueToContext(err error) bool {
for {
var authFailedErr *AuthenticationFailedError
if !errors.As(err, &authFailedErr) {
break
}
err = authFailedErr.err
}
return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
}

View file

@ -0,0 +1,106 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
)
const credNameDeviceCode = "DeviceCodeCredential"
// DeviceCodeCredentialOptions contains optional parameters for DeviceCodeCredential.
type DeviceCodeCredentialOptions struct {
azcore.ClientOptions
// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire
// tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant.
AdditionallyAllowedTenants []string
// ClientID is the ID of the application users will authenticate to.
// Defaults to the ID of an Azure development application.
ClientID string
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
// the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool
// TenantID is the Azure Active Directory tenant the credential authenticates in. Defaults to the
// "organizations" tenant, which can authenticate work and school accounts. Required for single-tenant
// applications.
TenantID string
// UserPrompt controls how the credential presents authentication instructions. The credential calls
// this function with authentication details when it receives a device code. By default, the credential
// prints these details to stdout.
UserPrompt func(context.Context, DeviceCodeMessage) error
}
func (o *DeviceCodeCredentialOptions) init() {
if o.TenantID == "" {
o.TenantID = organizationsTenantID
}
if o.ClientID == "" {
o.ClientID = developerSignOnClientID
}
if o.UserPrompt == nil {
o.UserPrompt = func(ctx context.Context, dc DeviceCodeMessage) error {
fmt.Println(dc.Message)
return nil
}
}
}
// DeviceCodeMessage contains the information a user needs to complete authentication.
type DeviceCodeMessage struct {
// UserCode is the user code returned by the service.
UserCode string `json:"user_code"`
// VerificationURL is the URL at which the user must authenticate.
VerificationURL string `json:"verification_uri"`
// Message is user instruction from Azure Active Directory.
Message string `json:"message"`
}
// DeviceCodeCredential acquires tokens for a user via the device code flow, which has the
// user browse to an Azure Active Directory URL, enter a code, and authenticate. It's useful
// for authenticating a user in an environment without a web browser, such as an SSH session.
// If a web browser is available, InteractiveBrowserCredential is more convenient because it
// automatically opens a browser to the login page.
type DeviceCodeCredential struct {
client *publicClient
}
// NewDeviceCodeCredential creates a DeviceCodeCredential. Pass nil to accept default options.
func NewDeviceCodeCredential(options *DeviceCodeCredentialOptions) (*DeviceCodeCredential, error) {
cp := DeviceCodeCredentialOptions{}
if options != nil {
cp = *options
}
cp.init()
msalOpts := publicClientOptions{
AdditionallyAllowedTenants: cp.AdditionallyAllowedTenants,
ClientOptions: cp.ClientOptions,
DeviceCodePrompt: cp.UserPrompt,
DisableInstanceDiscovery: cp.DisableInstanceDiscovery,
}
c, err := newPublicClient(cp.TenantID, cp.ClientID, credNameDeviceCode, msalOpts)
if err != nil {
return nil, err
}
c.name = credNameDeviceCode
return &DeviceCodeCredential{client: c}, nil
}
// GetToken requests an access token from Azure Active Directory. It will begin the device code flow and poll until the user completes authentication.
// This method is called automatically by Azure SDK clients.
func (c *DeviceCodeCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
return c.client.GetToken(ctx, opts)
}
var _ azcore.TokenCredential = (*DeviceCodeCredential)(nil)

View file

@ -0,0 +1,164 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"errors"
"fmt"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/internal/log"
)
const envVarSendCertChain = "AZURE_CLIENT_SEND_CERTIFICATE_CHAIN"
// EnvironmentCredentialOptions contains optional parameters for EnvironmentCredential
type EnvironmentCredentialOptions struct {
azcore.ClientOptions
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
// the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool
// additionallyAllowedTenants is used only by NewDefaultAzureCredential() to enable that constructor's explicit
// option to override the value of AZURE_ADDITIONALLY_ALLOWED_TENANTS. Applications using EnvironmentCredential
// directly should set that variable instead. This field should remain unexported to preserve this credential's
// unambiguous "all configuration from environment variables" design.
additionallyAllowedTenants []string
}
// EnvironmentCredential authenticates a service principal with a secret or certificate, or a user with a password, depending
// on environment variable configuration. It reads configuration from these variables, in the following order:
//
// # Service principal with client secret
//
// AZURE_TENANT_ID: ID of the service principal's tenant. Also called its "directory" ID.
//
// AZURE_CLIENT_ID: the service principal's client ID
//
// AZURE_CLIENT_SECRET: one of the service principal's client secrets
//
// # Service principal with certificate
//
// AZURE_TENANT_ID: ID of the service principal's tenant. Also called its "directory" ID.
//
// AZURE_CLIENT_ID: the service principal's client ID
//
// AZURE_CLIENT_CERTIFICATE_PATH: path to a PEM or PKCS12 certificate file including the private key.
//
// AZURE_CLIENT_CERTIFICATE_PASSWORD: (optional) password for the certificate file.
//
// # User with username and password
//
// AZURE_TENANT_ID: (optional) tenant to authenticate in. Defaults to "organizations".
//
// AZURE_CLIENT_ID: client ID of the application the user will authenticate to
//
// AZURE_USERNAME: a username (usually an email address)
//
// AZURE_PASSWORD: the user's password
//
// # Configuration for multitenant applications
//
// To enable multitenant authentication, set AZURE_ADDITIONALLY_ALLOWED_TENANTS with a semicolon delimited list of tenants
// the credential may request tokens from in addition to the tenant specified by AZURE_TENANT_ID. Set
// AZURE_ADDITIONALLY_ALLOWED_TENANTS to "*" to enable the credential to request a token from any tenant.
type EnvironmentCredential struct {
cred azcore.TokenCredential
}
// NewEnvironmentCredential creates an EnvironmentCredential. Pass nil to accept default options.
func NewEnvironmentCredential(options *EnvironmentCredentialOptions) (*EnvironmentCredential, error) {
if options == nil {
options = &EnvironmentCredentialOptions{}
}
tenantID := os.Getenv(azureTenantID)
if tenantID == "" {
return nil, errors.New("missing environment variable AZURE_TENANT_ID")
}
clientID := os.Getenv(azureClientID)
if clientID == "" {
return nil, errors.New("missing environment variable " + azureClientID)
}
// tenants set by NewDefaultAzureCredential() override the value of AZURE_ADDITIONALLY_ALLOWED_TENANTS
additionalTenants := options.additionallyAllowedTenants
if len(additionalTenants) == 0 {
if tenants := os.Getenv(azureAdditionallyAllowedTenants); tenants != "" {
additionalTenants = strings.Split(tenants, ";")
}
}
if clientSecret := os.Getenv(azureClientSecret); clientSecret != "" {
log.Write(EventAuthentication, "EnvironmentCredential will authenticate with ClientSecretCredential")
o := &ClientSecretCredentialOptions{
AdditionallyAllowedTenants: additionalTenants,
ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery,
}
cred, err := NewClientSecretCredential(tenantID, clientID, clientSecret, o)
if err != nil {
return nil, err
}
return &EnvironmentCredential{cred: cred}, nil
}
if certPath := os.Getenv(azureClientCertificatePath); certPath != "" {
log.Write(EventAuthentication, "EnvironmentCredential will authenticate with ClientCertificateCredential")
certData, err := os.ReadFile(certPath)
if err != nil {
return nil, fmt.Errorf(`failed to read certificate file "%s": %v`, certPath, err)
}
var password []byte
if v := os.Getenv(azureClientCertificatePassword); v != "" {
password = []byte(v)
}
certs, key, err := ParseCertificates(certData, password)
if err != nil {
return nil, fmt.Errorf(`failed to load certificate from "%s": %v`, certPath, err)
}
o := &ClientCertificateCredentialOptions{
AdditionallyAllowedTenants: additionalTenants,
ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery,
}
if v, ok := os.LookupEnv(envVarSendCertChain); ok {
o.SendCertificateChain = v == "1" || strings.ToLower(v) == "true"
}
cred, err := NewClientCertificateCredential(tenantID, clientID, certs, key, o)
if err != nil {
return nil, err
}
return &EnvironmentCredential{cred: cred}, nil
}
if username := os.Getenv(azureUsername); username != "" {
if password := os.Getenv(azurePassword); password != "" {
log.Write(EventAuthentication, "EnvironmentCredential will authenticate with UsernamePasswordCredential")
o := &UsernamePasswordCredentialOptions{
AdditionallyAllowedTenants: additionalTenants,
ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery,
}
cred, err := NewUsernamePasswordCredential(tenantID, clientID, username, password, o)
if err != nil {
return nil, err
}
return &EnvironmentCredential{cred: cred}, nil
}
return nil, errors.New("no value for AZURE_PASSWORD")
}
return nil, errors.New("incomplete environment variable configuration. Only AZURE_TENANT_ID and AZURE_CLIENT_ID are set")
}
// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.
func (c *EnvironmentCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
return c.cred.GetToken(ctx, opts)
}
var _ azcore.TokenCredential = (*EnvironmentCredential)(nil)

View file

@ -0,0 +1,128 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo"
msal "github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors"
)
// getResponseFromError retrieves the response carried by
// an AuthenticationFailedError or MSAL CallErr, if any
func getResponseFromError(err error) *http.Response {
var a *AuthenticationFailedError
var c msal.CallErr
var res *http.Response
if errors.As(err, &c) {
res = c.Resp
} else if errors.As(err, &a) {
res = a.RawResponse
}
return res
}
// AuthenticationFailedError indicates an authentication request has failed.
type AuthenticationFailedError struct {
// RawResponse is the HTTP response motivating the error, if available.
RawResponse *http.Response
credType string
message string
err error
}
func newAuthenticationFailedError(credType string, message string, resp *http.Response, err error) error {
return &AuthenticationFailedError{credType: credType, message: message, RawResponse: resp, err: err}
}
// Error implements the error interface. Note that the message contents are not contractual and can change over time.
func (e *AuthenticationFailedError) Error() string {
if e.RawResponse == nil {
return e.credType + ": " + e.message
}
msg := &bytes.Buffer{}
fmt.Fprintf(msg, e.credType+" authentication failed\n")
fmt.Fprintf(msg, "%s %s://%s%s\n", e.RawResponse.Request.Method, e.RawResponse.Request.URL.Scheme, e.RawResponse.Request.URL.Host, e.RawResponse.Request.URL.Path)
fmt.Fprintln(msg, "--------------------------------------------------------------------------------")
fmt.Fprintf(msg, "RESPONSE %s\n", e.RawResponse.Status)
fmt.Fprintln(msg, "--------------------------------------------------------------------------------")
body, err := runtime.Payload(e.RawResponse)
switch {
case err != nil:
fmt.Fprintf(msg, "Error reading response body: %v", err)
case len(body) > 0:
if err := json.Indent(msg, body, "", " "); err != nil {
// failed to pretty-print so just dump it verbatim
fmt.Fprint(msg, string(body))
}
default:
fmt.Fprint(msg, "Response contained no body")
}
fmt.Fprintln(msg, "\n--------------------------------------------------------------------------------")
var anchor string
switch e.credType {
case credNameAzureCLI:
anchor = "azure-cli"
case credNameCert:
anchor = "client-cert"
case credNameSecret:
anchor = "client-secret"
case credNameManagedIdentity:
anchor = "managed-id"
case credNameUserPassword:
anchor = "username-password"
case credNameWorkloadIdentity:
anchor = "workload"
}
if anchor != "" {
fmt.Fprintf(msg, "To troubleshoot, visit https://aka.ms/azsdk/go/identity/troubleshoot#%s", anchor)
}
return msg.String()
}
// NonRetriable indicates the request which provoked this error shouldn't be retried.
func (*AuthenticationFailedError) NonRetriable() {
// marker method
}
var _ errorinfo.NonRetriable = (*AuthenticationFailedError)(nil)
// credentialUnavailableError indicates a credential can't attempt authentication because it lacks required
// data or state
type credentialUnavailableError struct {
message string
}
// newCredentialUnavailableError is an internal helper that ensures consistent error message formatting
func newCredentialUnavailableError(credType, message string) error {
msg := fmt.Sprintf("%s: %s", credType, message)
return &credentialUnavailableError{msg}
}
// NewCredentialUnavailableError constructs an error indicating a credential can't attempt authentication
// because it lacks required data or state. When [ChainedTokenCredential] receives this error it will try
// its next credential, if any.
func NewCredentialUnavailableError(message string) error {
return &credentialUnavailableError{message}
}
// Error implements the error interface. Note that the message contents are not contractual and can change over time.
func (e *credentialUnavailableError) Error() string {
return e.message
}
// NonRetriable is a marker method indicating this error should not be retried. It has no implementation.
func (e *credentialUnavailableError) NonRetriable() {}
var _ errorinfo.NonRetriable = (*credentialUnavailableError)(nil)

View file

@ -0,0 +1,86 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
)
const credNameBrowser = "InteractiveBrowserCredential"
// InteractiveBrowserCredentialOptions contains optional parameters for InteractiveBrowserCredential.
type InteractiveBrowserCredentialOptions struct {
azcore.ClientOptions
// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire
// tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant.
AdditionallyAllowedTenants []string
// ClientID is the ID of the application users will authenticate to.
// Defaults to the ID of an Azure development application.
ClientID string
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
// the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool
// LoginHint pre-populates the account prompt with a username. Users may choose to authenticate a different account.
LoginHint string
// RedirectURL is the URL Azure Active Directory will redirect to with the access token. This is required
// only when setting ClientID, and must match a redirect URI in the application's registration.
// Applications which have registered "http://localhost" as a redirect URI need not set this option.
RedirectURL string
// TenantID is the Azure Active Directory tenant the credential authenticates in. Defaults to the
// "organizations" tenant, which can authenticate work and school accounts.
TenantID string
}
func (o *InteractiveBrowserCredentialOptions) init() {
if o.TenantID == "" {
o.TenantID = organizationsTenantID
}
if o.ClientID == "" {
o.ClientID = developerSignOnClientID
}
}
// InteractiveBrowserCredential opens a browser to interactively authenticate a user.
type InteractiveBrowserCredential struct {
client *publicClient
}
// NewInteractiveBrowserCredential constructs a new InteractiveBrowserCredential. Pass nil to accept default options.
func NewInteractiveBrowserCredential(options *InteractiveBrowserCredentialOptions) (*InteractiveBrowserCredential, error) {
cp := InteractiveBrowserCredentialOptions{}
if options != nil {
cp = *options
}
cp.init()
msalOpts := publicClientOptions{
ClientOptions: cp.ClientOptions,
DisableInstanceDiscovery: cp.DisableInstanceDiscovery,
LoginHint: cp.LoginHint,
RedirectURL: cp.RedirectURL,
}
c, err := newPublicClient(cp.TenantID, cp.ClientID, credNameBrowser, msalOpts)
if err != nil {
return nil, err
}
return &InteractiveBrowserCredential{client: c}, nil
}
// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.
func (c *InteractiveBrowserCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
return c.client.GetToken(ctx, opts)
}
var _ azcore.TokenCredential = (*InteractiveBrowserCredential)(nil)

View file

@ -0,0 +1,14 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import "github.com/Azure/azure-sdk-for-go/sdk/internal/log"
// EventAuthentication entries contain information about authentication.
// This includes information like the names of environment variables
// used when obtaining credentials and the type of credential used.
const EventAuthentication log.Event = "Authentication"

View file

@ -0,0 +1,404 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/internal/log"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
)
const (
arcIMDSEndpoint = "IMDS_ENDPOINT"
identityEndpoint = "IDENTITY_ENDPOINT"
identityHeader = "IDENTITY_HEADER"
identityServerThumbprint = "IDENTITY_SERVER_THUMBPRINT"
headerMetadata = "Metadata"
imdsEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token"
msiEndpoint = "MSI_ENDPOINT"
imdsAPIVersion = "2018-02-01"
azureArcAPIVersion = "2019-08-15"
serviceFabricAPIVersion = "2019-07-01-preview"
qpClientID = "client_id"
qpResID = "mi_res_id"
)
type msiType int
const (
msiTypeAppService msiType = iota
msiTypeAzureArc
msiTypeCloudShell
msiTypeIMDS
msiTypeServiceFabric
)
// managedIdentityClient provides the base for authenticating in managed identity environments
// This type includes an runtime.Pipeline and TokenCredentialOptions.
type managedIdentityClient struct {
pipeline runtime.Pipeline
msiType msiType
endpoint string
id ManagedIDKind
}
type wrappedNumber json.Number
func (n *wrappedNumber) UnmarshalJSON(b []byte) error {
c := string(b)
if c == "\"\"" {
return nil
}
return json.Unmarshal(b, (*json.Number)(n))
}
// setIMDSRetryOptionDefaults sets zero-valued fields to default values appropriate for IMDS
func setIMDSRetryOptionDefaults(o *policy.RetryOptions) {
if o.MaxRetries == 0 {
o.MaxRetries = 5
}
if o.MaxRetryDelay == 0 {
o.MaxRetryDelay = 1 * time.Minute
}
if o.RetryDelay == 0 {
o.RetryDelay = 2 * time.Second
}
if o.StatusCodes == nil {
o.StatusCodes = []int{
// IMDS docs recommend retrying 404, 410, 429 and 5xx
// https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#error-handling
http.StatusNotFound, // 404
http.StatusGone, // 410
http.StatusTooManyRequests, // 429
http.StatusInternalServerError, // 500
http.StatusNotImplemented, // 501
http.StatusBadGateway, // 502
http.StatusServiceUnavailable, // 503
http.StatusGatewayTimeout, // 504
http.StatusHTTPVersionNotSupported, // 505
http.StatusVariantAlsoNegotiates, // 506
http.StatusInsufficientStorage, // 507
http.StatusLoopDetected, // 508
http.StatusNotExtended, // 510
http.StatusNetworkAuthenticationRequired, // 511
}
}
if o.TryTimeout == 0 {
o.TryTimeout = 1 * time.Minute
}
}
// newManagedIdentityClient creates a new instance of the ManagedIdentityClient with the ManagedIdentityCredentialOptions
// that are passed into it along with a default pipeline.
// options: ManagedIdentityCredentialOptions configure policies for the pipeline and the authority host that
// will be used to retrieve tokens and authenticate
func newManagedIdentityClient(options *ManagedIdentityCredentialOptions) (*managedIdentityClient, error) {
if options == nil {
options = &ManagedIdentityCredentialOptions{}
}
cp := options.ClientOptions
c := managedIdentityClient{id: options.ID, endpoint: imdsEndpoint, msiType: msiTypeIMDS}
env := "IMDS"
if endpoint, ok := os.LookupEnv(identityEndpoint); ok {
if _, ok := os.LookupEnv(identityHeader); ok {
if _, ok := os.LookupEnv(identityServerThumbprint); ok {
env = "Service Fabric"
c.endpoint = endpoint
c.msiType = msiTypeServiceFabric
} else {
env = "App Service"
c.endpoint = endpoint
c.msiType = msiTypeAppService
}
} else if _, ok := os.LookupEnv(arcIMDSEndpoint); ok {
env = "Azure Arc"
c.endpoint = endpoint
c.msiType = msiTypeAzureArc
}
} else if endpoint, ok := os.LookupEnv(msiEndpoint); ok {
env = "Cloud Shell"
c.endpoint = endpoint
c.msiType = msiTypeCloudShell
} else {
setIMDSRetryOptionDefaults(&cp.Retry)
}
c.pipeline = runtime.NewPipeline(component, version, runtime.PipelineOptions{}, &cp)
if log.Should(EventAuthentication) {
log.Writef(EventAuthentication, "Managed Identity Credential will use %s managed identity", env)
}
return &c, nil
}
// provideToken acquires a token for MSAL's confidential.Client, which caches the token
func (c *managedIdentityClient) provideToken(ctx context.Context, params confidential.TokenProviderParameters) (confidential.TokenProviderResult, error) {
result := confidential.TokenProviderResult{}
tk, err := c.authenticate(ctx, c.id, params.Scopes)
if err == nil {
result.AccessToken = tk.Token
result.ExpiresInSeconds = int(time.Until(tk.ExpiresOn).Seconds())
}
return result, err
}
// authenticate acquires an access token
func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKind, scopes []string) (azcore.AccessToken, error) {
msg, err := c.createAuthRequest(ctx, id, scopes)
if err != nil {
return azcore.AccessToken{}, err
}
resp, err := c.pipeline.Do(msg)
if err != nil {
return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, err.Error(), nil, err)
}
if runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) {
return c.createAccessToken(resp)
}
if c.msiType == msiTypeIMDS {
switch resp.StatusCode {
case http.StatusBadRequest:
if id != nil {
return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "the requested identity isn't assigned to this resource", resp, nil)
}
msg := "failed to authenticate a system assigned identity"
if body, err := runtime.Payload(resp); err == nil && len(body) > 0 {
msg += fmt.Sprintf(". The endpoint responded with %s", body)
}
return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, msg)
case http.StatusForbidden:
// Docker Desktop runs a proxy that responds 403 to IMDS token requests. If we get that response,
// we return credentialUnavailableError so credential chains continue to their next credential
body, err := runtime.Payload(resp)
if err == nil && strings.Contains(string(body), "A socket operation was attempted to an unreachable network") {
return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, fmt.Sprintf("unexpected response %q", string(body)))
}
}
}
return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "authentication failed", resp, nil)
}
func (c *managedIdentityClient) createAccessToken(res *http.Response) (azcore.AccessToken, error) {
value := struct {
// these are the only fields that we use
Token string `json:"access_token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
ExpiresIn wrappedNumber `json:"expires_in,omitempty"` // this field should always return the number of seconds for which a token is valid
ExpiresOn interface{} `json:"expires_on,omitempty"` // the value returned in this field varies between a number and a date string
}{}
if err := runtime.UnmarshalAsJSON(res, &value); err != nil {
return azcore.AccessToken{}, fmt.Errorf("internal AccessToken: %v", err)
}
if value.ExpiresIn != "" {
expiresIn, err := json.Number(value.ExpiresIn).Int64()
if err != nil {
return azcore.AccessToken{}, err
}
return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Now().Add(time.Second * time.Duration(expiresIn)).UTC()}, nil
}
switch v := value.ExpiresOn.(type) {
case float64:
return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Unix(int64(v), 0).UTC()}, nil
case string:
if expiresOn, err := strconv.Atoi(v); err == nil {
return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Unix(int64(expiresOn), 0).UTC()}, nil
}
return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "unexpected expires_on value: "+v, res, nil)
default:
msg := fmt.Sprintf("unsupported type received in expires_on: %T, %v", v, v)
return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, msg, res, nil)
}
}
func (c *managedIdentityClient) createAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) {
switch c.msiType {
case msiTypeIMDS:
return c.createIMDSAuthRequest(ctx, id, scopes)
case msiTypeAppService:
return c.createAppServiceAuthRequest(ctx, id, scopes)
case msiTypeAzureArc:
// need to perform preliminary request to retreive the secret key challenge provided by the HIMDS service
key, err := c.getAzureArcSecretKey(ctx, scopes)
if err != nil {
msg := fmt.Sprintf("failed to retreive secret key from the identity endpoint: %v", err)
return nil, newAuthenticationFailedError(credNameManagedIdentity, msg, nil, err)
}
return c.createAzureArcAuthRequest(ctx, id, scopes, key)
case msiTypeServiceFabric:
return c.createServiceFabricAuthRequest(ctx, id, scopes)
case msiTypeCloudShell:
return c.createCloudShellAuthRequest(ctx, id, scopes)
default:
return nil, newCredentialUnavailableError(credNameManagedIdentity, "managed identity isn't supported in this environment")
}
}
func (c *managedIdentityClient) createIMDSAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) {
request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint)
if err != nil {
return nil, err
}
request.Raw().Header.Set(headerMetadata, "true")
q := request.Raw().URL.Query()
q.Add("api-version", imdsAPIVersion)
q.Add("resource", strings.Join(scopes, " "))
if id != nil {
if id.idKind() == miResourceID {
q.Add(qpResID, id.String())
} else {
q.Add(qpClientID, id.String())
}
}
request.Raw().URL.RawQuery = q.Encode()
return request, nil
}
func (c *managedIdentityClient) createAppServiceAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) {
request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint)
if err != nil {
return nil, err
}
request.Raw().Header.Set("X-IDENTITY-HEADER", os.Getenv(identityHeader))
q := request.Raw().URL.Query()
q.Add("api-version", "2019-08-01")
q.Add("resource", scopes[0])
if id != nil {
if id.idKind() == miResourceID {
q.Add(qpResID, id.String())
} else {
q.Add(qpClientID, id.String())
}
}
request.Raw().URL.RawQuery = q.Encode()
return request, nil
}
func (c *managedIdentityClient) createServiceFabricAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) {
request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint)
if err != nil {
return nil, err
}
q := request.Raw().URL.Query()
request.Raw().Header.Set("Accept", "application/json")
request.Raw().Header.Set("Secret", os.Getenv(identityHeader))
q.Add("api-version", serviceFabricAPIVersion)
q.Add("resource", strings.Join(scopes, " "))
if id != nil {
log.Write(EventAuthentication, "WARNING: Service Fabric doesn't support selecting a user-assigned identity at runtime")
if id.idKind() == miResourceID {
q.Add(qpResID, id.String())
} else {
q.Add(qpClientID, id.String())
}
}
request.Raw().URL.RawQuery = q.Encode()
return request, nil
}
func (c *managedIdentityClient) getAzureArcSecretKey(ctx context.Context, resources []string) (string, error) {
// create the request to retreive the secret key challenge provided by the HIMDS service
request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint)
if err != nil {
return "", err
}
request.Raw().Header.Set(headerMetadata, "true")
q := request.Raw().URL.Query()
q.Add("api-version", azureArcAPIVersion)
q.Add("resource", strings.Join(resources, " "))
request.Raw().URL.RawQuery = q.Encode()
// send the initial request to get the short-lived secret key
response, err := c.pipeline.Do(request)
if err != nil {
return "", err
}
// the endpoint is expected to return a 401 with the WWW-Authenticate header set to the location
// of the secret key file. Any other status code indicates an error in the request.
if response.StatusCode != 401 {
msg := fmt.Sprintf("expected a 401 response, received %d", response.StatusCode)
return "", newAuthenticationFailedError(credNameManagedIdentity, msg, response, nil)
}
header := response.Header.Get("WWW-Authenticate")
if len(header) == 0 {
return "", errors.New("did not receive a value from WWW-Authenticate header")
}
// the WWW-Authenticate header is expected in the following format: Basic realm=/some/file/path.key
pos := strings.LastIndex(header, "=")
if pos == -1 {
return "", fmt.Errorf("did not receive a correct value from WWW-Authenticate header: %s", header)
}
key, err := os.ReadFile(header[pos+1:])
if err != nil {
return "", fmt.Errorf("could not read file (%s) contents: %v", header[pos+1:], err)
}
return string(key), nil
}
func (c *managedIdentityClient) createAzureArcAuthRequest(ctx context.Context, id ManagedIDKind, resources []string, key string) (*policy.Request, error) {
request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint)
if err != nil {
return nil, err
}
request.Raw().Header.Set(headerMetadata, "true")
request.Raw().Header.Set("Authorization", fmt.Sprintf("Basic %s", key))
q := request.Raw().URL.Query()
q.Add("api-version", azureArcAPIVersion)
q.Add("resource", strings.Join(resources, " "))
if id != nil {
log.Write(EventAuthentication, "WARNING: Azure Arc doesn't support user-assigned managed identities")
if id.idKind() == miResourceID {
q.Add(qpResID, id.String())
} else {
q.Add(qpClientID, id.String())
}
}
request.Raw().URL.RawQuery = q.Encode()
return request, nil
}
func (c *managedIdentityClient) createCloudShellAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) {
request, err := runtime.NewRequest(ctx, http.MethodPost, c.endpoint)
if err != nil {
return nil, err
}
request.Raw().Header.Set(headerMetadata, "true")
data := url.Values{}
data.Set("resource", strings.Join(scopes, " "))
dataEncoded := data.Encode()
body := streaming.NopCloser(strings.NewReader(dataEncoded))
if err := request.SetBody(body, "application/x-www-form-urlencoded"); err != nil {
return nil, err
}
if id != nil {
log.Write(EventAuthentication, "WARNING: Cloud Shell doesn't support user-assigned managed identities")
q := request.Raw().URL.Query()
if id.idKind() == miResourceID {
q.Add(qpResID, id.String())
} else {
q.Add(qpClientID, id.String())
}
}
return request, nil
}

View file

@ -0,0 +1,113 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"fmt"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
)
const credNameManagedIdentity = "ManagedIdentityCredential"
type managedIdentityIDKind int
const (
miClientID managedIdentityIDKind = 0
miResourceID managedIdentityIDKind = 1
)
// ManagedIDKind identifies the ID of a managed identity as either a client or resource ID
type ManagedIDKind interface {
fmt.Stringer
idKind() managedIdentityIDKind
}
// ClientID is the client ID of a user-assigned managed identity.
type ClientID string
func (ClientID) idKind() managedIdentityIDKind {
return miClientID
}
// String returns the string value of the ID.
func (c ClientID) String() string {
return string(c)
}
// ResourceID is the resource ID of a user-assigned managed identity.
type ResourceID string
func (ResourceID) idKind() managedIdentityIDKind {
return miResourceID
}
// String returns the string value of the ID.
func (r ResourceID) String() string {
return string(r)
}
// ManagedIdentityCredentialOptions contains optional parameters for ManagedIdentityCredential.
type ManagedIdentityCredentialOptions struct {
azcore.ClientOptions
// ID is the ID of a managed identity the credential should authenticate. Set this field to use a specific identity
// instead of the hosting environment's default. The value may be the identity's client ID or resource ID, but note that
// some platforms don't accept resource IDs.
ID ManagedIDKind
}
// ManagedIdentityCredential authenticates an Azure managed identity in any hosting environment supporting managed identities.
// This credential authenticates a system-assigned identity by default. Use ManagedIdentityCredentialOptions.ID to specify a
// user-assigned identity. See Azure Active Directory documentation for more information about managed identities:
// https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview
type ManagedIdentityCredential struct {
client *confidentialClient
mic *managedIdentityClient
}
// NewManagedIdentityCredential creates a ManagedIdentityCredential. Pass nil to accept default options.
func NewManagedIdentityCredential(options *ManagedIdentityCredentialOptions) (*ManagedIdentityCredential, error) {
if options == nil {
options = &ManagedIdentityCredentialOptions{}
}
mic, err := newManagedIdentityClient(options)
if err != nil {
return nil, err
}
cred := confidential.NewCredFromTokenProvider(mic.provideToken)
// It's okay to give MSAL an invalid client ID because MSAL will use it only as part of a cache key.
// ManagedIdentityClient handles all the details of authentication and won't receive this value from MSAL.
clientID := "SYSTEM-ASSIGNED-MANAGED-IDENTITY"
if options.ID != nil {
clientID = options.ID.String()
}
// similarly, it's okay to give MSAL an incorrect tenant because MSAL won't use the value
c, err := newConfidentialClient("common", clientID, credNameManagedIdentity, cred, confidentialClientOptions{})
if err != nil {
return nil, err
}
return &ManagedIdentityCredential{client: c, mic: mic}, nil
}
// GetToken requests an access token from the hosting environment. This method is called automatically by Azure SDK clients.
func (c *ManagedIdentityCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
if len(opts.Scopes) != 1 {
err := fmt.Errorf("%s.GetToken() requires exactly one scope", credNameManagedIdentity)
return azcore.AccessToken{}, err
}
// managed identity endpoints require an AADv1 resource (i.e. token audience), not a v2 scope, so we remove "/.default" here
opts.Scopes = []string{strings.TrimSuffix(opts.Scopes[0], defaultSuffix)}
return c.client.GetToken(ctx, opts)
}
var _ azcore.TokenCredential = (*ManagedIdentityCredential)(nil)

View file

@ -0,0 +1,92 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"crypto"
"crypto/x509"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
)
const credNameOBO = "OnBehalfOfCredential"
// OnBehalfOfCredential authenticates a service principal via the on-behalf-of flow. This is typically used by
// middle-tier services that authorize requests to other services with a delegated user identity. Because this
// is not an interactive authentication flow, an application using it must have admin consent for any delegated
// permissions before requesting tokens for them. See [Azure Active Directory documentation] for more details.
//
// [Azure Active Directory documentation]: https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow
type OnBehalfOfCredential struct {
client *confidentialClient
}
// OnBehalfOfCredentialOptions contains optional parameters for OnBehalfOfCredential
type OnBehalfOfCredentialOptions struct {
azcore.ClientOptions
// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens.
// Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the
// application is registered.
AdditionallyAllowedTenants []string
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
// the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool
// SendCertificateChain applies only when the credential is configured to authenticate with a certificate.
// This setting controls whether the credential sends the public certificate chain in the x5c header of each
// token request's JWT. This is required for, and only used in, Subject Name/Issuer (SNI) authentication.
SendCertificateChain bool
}
// NewOnBehalfOfCredentialWithCertificate constructs an OnBehalfOfCredential that authenticates with a certificate.
// See [ParseCertificates] for help loading a certificate.
func NewOnBehalfOfCredentialWithCertificate(tenantID, clientID, userAssertion string, certs []*x509.Certificate, key crypto.PrivateKey, options *OnBehalfOfCredentialOptions) (*OnBehalfOfCredential, error) {
cred, err := confidential.NewCredFromCert(certs, key)
if err != nil {
return nil, err
}
return newOnBehalfOfCredential(tenantID, clientID, userAssertion, cred, options)
}
// NewOnBehalfOfCredentialWithSecret constructs an OnBehalfOfCredential that authenticates with a client secret.
func NewOnBehalfOfCredentialWithSecret(tenantID, clientID, userAssertion, clientSecret string, options *OnBehalfOfCredentialOptions) (*OnBehalfOfCredential, error) {
cred, err := confidential.NewCredFromSecret(clientSecret)
if err != nil {
return nil, err
}
return newOnBehalfOfCredential(tenantID, clientID, userAssertion, cred, options)
}
func newOnBehalfOfCredential(tenantID, clientID, userAssertion string, cred confidential.Credential, options *OnBehalfOfCredentialOptions) (*OnBehalfOfCredential, error) {
if options == nil {
options = &OnBehalfOfCredentialOptions{}
}
opts := confidentialClientOptions{
AdditionallyAllowedTenants: options.AdditionallyAllowedTenants,
Assertion: userAssertion,
ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery,
SendX5C: options.SendCertificateChain,
}
c, err := newConfidentialClient(tenantID, clientID, credNameOBO, cred, opts)
if err != nil {
return nil, err
}
return &OnBehalfOfCredential{c}, nil
}
// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.
func (o *OnBehalfOfCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
return o.client.GetToken(ctx, opts)
}
var _ azcore.TokenCredential = (*OnBehalfOfCredential)(nil)

View file

@ -0,0 +1,178 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"fmt"
"strings"
"sync"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/log"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/public"
)
type publicClientOptions struct {
azcore.ClientOptions
AdditionallyAllowedTenants []string
DeviceCodePrompt func(context.Context, DeviceCodeMessage) error
DisableInstanceDiscovery bool
LoginHint, RedirectURL string
Username, Password string
}
// publicClient wraps the MSAL public client
type publicClient struct {
account public.Account
cae, noCAE msalPublicClient
caeMu, noCAEMu, clientMu *sync.Mutex
clientID, tenantID string
host string
name string
opts publicClientOptions
}
func newPublicClient(tenantID, clientID, name string, o publicClientOptions) (*publicClient, error) {
if !validTenantID(tenantID) {
return nil, errInvalidTenantID
}
host, err := setAuthorityHost(o.Cloud)
if err != nil {
return nil, err
}
o.AdditionallyAllowedTenants = resolveAdditionalTenants(o.AdditionallyAllowedTenants)
return &publicClient{
caeMu: &sync.Mutex{},
clientID: clientID,
clientMu: &sync.Mutex{},
host: host,
name: name,
noCAEMu: &sync.Mutex{},
opts: o,
tenantID: tenantID,
}, nil
}
// GetToken requests an access token from MSAL, checking the cache first.
func (p *publicClient) GetToken(ctx context.Context, tro policy.TokenRequestOptions) (azcore.AccessToken, error) {
if len(tro.Scopes) < 1 {
return azcore.AccessToken{}, fmt.Errorf("%s.GetToken() requires at least one scope", p.name)
}
tenant, err := p.resolveTenant(tro.TenantID)
if err != nil {
return azcore.AccessToken{}, err
}
client, mu, err := p.client(tro)
if err != nil {
return azcore.AccessToken{}, err
}
mu.Lock()
defer mu.Unlock()
ar, err := client.AcquireTokenSilent(ctx, tro.Scopes, public.WithSilentAccount(p.account), public.WithClaims(tro.Claims), public.WithTenantID(tenant))
if err == nil {
return p.token(ar, err)
}
at, err := p.reqToken(ctx, client, tro)
if err == nil {
msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", p.name, strings.Join(ar.GrantedScopes, ", "))
log.Write(EventAuthentication, msg)
}
return at, err
}
// reqToken requests a token from the MSAL public client. It's separate from GetToken() to enable Authenticate() to bypass the cache.
func (p *publicClient) reqToken(ctx context.Context, c msalPublicClient, tro policy.TokenRequestOptions) (azcore.AccessToken, error) {
tenant, err := p.resolveTenant(tro.TenantID)
if err != nil {
return azcore.AccessToken{}, err
}
var ar public.AuthResult
switch p.name {
case credNameBrowser:
ar, err = c.AcquireTokenInteractive(ctx, tro.Scopes,
public.WithClaims(tro.Claims),
public.WithLoginHint(p.opts.LoginHint),
public.WithRedirectURI(p.opts.RedirectURL),
public.WithTenantID(tenant),
)
case credNameDeviceCode:
dc, e := c.AcquireTokenByDeviceCode(ctx, tro.Scopes, public.WithClaims(tro.Claims), public.WithTenantID(tenant))
if e != nil {
return azcore.AccessToken{}, e
}
err = p.opts.DeviceCodePrompt(ctx, DeviceCodeMessage{
Message: dc.Result.Message,
UserCode: dc.Result.UserCode,
VerificationURL: dc.Result.VerificationURL,
})
if err == nil {
ar, err = dc.AuthenticationResult(ctx)
}
case credNameUserPassword:
ar, err = c.AcquireTokenByUsernamePassword(ctx, tro.Scopes, p.opts.Username, p.opts.Password, public.WithClaims(tro.Claims), public.WithTenantID(tenant))
default:
return azcore.AccessToken{}, fmt.Errorf("unknown credential %q", p.name)
}
return p.token(ar, err)
}
func (p *publicClient) client(tro policy.TokenRequestOptions) (msalPublicClient, *sync.Mutex, error) {
p.clientMu.Lock()
defer p.clientMu.Unlock()
if tro.EnableCAE {
if p.cae == nil {
client, err := p.newMSALClient(true)
if err != nil {
return nil, nil, err
}
p.cae = client
}
return p.cae, p.caeMu, nil
}
if p.noCAE == nil {
client, err := p.newMSALClient(false)
if err != nil {
return nil, nil, err
}
p.noCAE = client
}
return p.noCAE, p.noCAEMu, nil
}
func (p *publicClient) newMSALClient(enableCAE bool) (msalPublicClient, error) {
o := []public.Option{
public.WithAuthority(runtime.JoinPaths(p.host, p.tenantID)),
public.WithHTTPClient(newPipelineAdapter(&p.opts.ClientOptions)),
}
if enableCAE {
o = append(o, public.WithClientCapabilities(cp1))
}
if p.opts.DisableInstanceDiscovery || strings.ToLower(p.tenantID) == "adfs" {
o = append(o, public.WithInstanceDiscovery(false))
}
return public.New(p.clientID, o...)
}
func (p *publicClient) token(ar public.AuthResult, err error) (azcore.AccessToken, error) {
if err == nil {
p.account = ar.Account
} else {
res := getResponseFromError(err)
err = newAuthenticationFailedError(p.name, err.Error(), res, err)
}
return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err
}
// resolveTenant returns the correct tenant for a token request given the client's
// configuration, or an error when that configuration doesn't allow the specified tenant
func (p *publicClient) resolveTenant(specified string) (string, error) {
return resolveTenant(p.tenantID, specified, p.name, p.opts.AdditionallyAllowedTenants)
}

View file

@ -0,0 +1,36 @@
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
param (
# Captures any arguments from eng/New-TestResources.ps1 not declared here (no parameter errors).
[Parameter(ValueFromRemainingArguments = $true)]
$RemainingArguments
)
if (!$CI) {
# TODO: Remove this once auto-cloud config downloads are supported locally
Write-Host "Skipping cert setup in local testing mode"
return
}
if ($EnvironmentVariables -eq $null -or $EnvironmentVariables.Count -eq 0) {
throw "EnvironmentVariables must be set in the calling script New-TestResources.ps1"
}
$tmp = $env:TEMP ? $env:TEMP : [System.IO.Path]::GetTempPath()
$pfxPath = Join-Path $tmp "test.pfx"
$pemPath = Join-Path $tmp "test.pem"
$sniPath = Join-Path $tmp "testsni.pfx"
Write-Host "Creating identity test files: $pfxPath $pemPath $sniPath"
[System.Convert]::FromBase64String($EnvironmentVariables['PFX_CONTENTS']) | Set-Content -Path $pfxPath -AsByteStream
Set-Content -Path $pemPath -Value $EnvironmentVariables['PEM_CONTENTS']
[System.Convert]::FromBase64String($EnvironmentVariables['SNI_CONTENTS']) | Set-Content -Path $sniPath -AsByteStream
# Set for pipeline
Write-Host "##vso[task.setvariable variable=IDENTITY_SP_CERT_PFX;]$pfxPath"
Write-Host "##vso[task.setvariable variable=IDENTITY_SP_CERT_PEM;]$pemPath"
Write-Host "##vso[task.setvariable variable=IDENTITY_SP_CERT_SNI;]$sniPath"
# Set for local
$env:IDENTITY_SP_CERT_PFX = $pfxPath
$env:IDENTITY_SP_CERT_PEM = $pemPath
$env:IDENTITY_SP_CERT_SNI = $sniPath

View file

@ -0,0 +1 @@
param baseName string

View file

@ -0,0 +1,66 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
)
const credNameUserPassword = "UsernamePasswordCredential"
// UsernamePasswordCredentialOptions contains optional parameters for UsernamePasswordCredential.
type UsernamePasswordCredentialOptions struct {
azcore.ClientOptions
// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens.
// Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the
// application is registered.
AdditionallyAllowedTenants []string
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
// the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool
}
// UsernamePasswordCredential authenticates a user with a password. Microsoft doesn't recommend this kind of authentication,
// because it's less secure than other authentication flows. This credential is not interactive, so it isn't compatible
// with any form of multi-factor authentication, and the application must already have user or admin consent.
// This credential can only authenticate work and school accounts; it can't authenticate Microsoft accounts.
type UsernamePasswordCredential struct {
client *publicClient
}
// NewUsernamePasswordCredential creates a UsernamePasswordCredential. clientID is the ID of the application the user
// will authenticate to. Pass nil for options to accept defaults.
func NewUsernamePasswordCredential(tenantID string, clientID string, username string, password string, options *UsernamePasswordCredentialOptions) (*UsernamePasswordCredential, error) {
if options == nil {
options = &UsernamePasswordCredentialOptions{}
}
opts := publicClientOptions{
AdditionallyAllowedTenants: options.AdditionallyAllowedTenants,
ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery,
Password: password,
Username: username,
}
c, err := newPublicClient(tenantID, clientID, credNameUserPassword, opts)
if err != nil {
return nil, err
}
return &UsernamePasswordCredential{client: c}, err
}
// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients.
func (c *UsernamePasswordCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
return c.client.GetToken(ctx, opts)
}
var _ azcore.TokenCredential = (*UsernamePasswordCredential)(nil)

View file

@ -0,0 +1,15 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
const (
// UserAgent is the string to be used in the user agent string when making requests.
component = "azidentity"
// Version is the semantic version (see http://semver.org) of this module.
version = "v1.4.0"
)

View file

@ -0,0 +1,126 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity
import (
"context"
"errors"
"os"
"sync"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
)
const credNameWorkloadIdentity = "WorkloadIdentityCredential"
// WorkloadIdentityCredential supports Azure workload identity on Kubernetes.
// See [Azure Kubernetes Service documentation] for more information.
//
// [Azure Kubernetes Service documentation]: https://learn.microsoft.com/azure/aks/workload-identity-overview
type WorkloadIdentityCredential struct {
assertion, file string
cred *ClientAssertionCredential
expires time.Time
mtx *sync.RWMutex
}
// WorkloadIdentityCredentialOptions contains optional parameters for WorkloadIdentityCredential.
type WorkloadIdentityCredentialOptions struct {
azcore.ClientOptions
// AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens.
// Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the
// application is registered.
AdditionallyAllowedTenants []string
// ClientID of the service principal. Defaults to the value of the environment variable AZURE_CLIENT_ID.
ClientID string
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
// the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool
// TenantID of the service principal. Defaults to the value of the environment variable AZURE_TENANT_ID.
TenantID string
// TokenFilePath is the path of a file containing a Kubernetes service account token. Defaults to the value of the
// environment variable AZURE_FEDERATED_TOKEN_FILE.
TokenFilePath string
}
// NewWorkloadIdentityCredential constructs a WorkloadIdentityCredential. Service principal configuration is read
// from environment variables as set by the Azure workload identity webhook. Set options to override those values.
func NewWorkloadIdentityCredential(options *WorkloadIdentityCredentialOptions) (*WorkloadIdentityCredential, error) {
if options == nil {
options = &WorkloadIdentityCredentialOptions{}
}
ok := false
clientID := options.ClientID
if clientID == "" {
if clientID, ok = os.LookupEnv(azureClientID); !ok {
return nil, errors.New("no client ID specified. Check pod configuration or set ClientID in the options")
}
}
file := options.TokenFilePath
if file == "" {
if file, ok = os.LookupEnv(azureFederatedTokenFile); !ok {
return nil, errors.New("no token file specified. Check pod configuration or set TokenFilePath in the options")
}
}
tenantID := options.TenantID
if tenantID == "" {
if tenantID, ok = os.LookupEnv(azureTenantID); !ok {
return nil, errors.New("no tenant ID specified. Check pod configuration or set TenantID in the options")
}
}
w := WorkloadIdentityCredential{file: file, mtx: &sync.RWMutex{}}
caco := ClientAssertionCredentialOptions{
AdditionallyAllowedTenants: options.AdditionallyAllowedTenants,
ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery,
}
cred, err := NewClientAssertionCredential(tenantID, clientID, w.getAssertion, &caco)
if err != nil {
return nil, err
}
// we want "WorkloadIdentityCredential" in log messages, not "ClientAssertionCredential"
cred.client.name = credNameWorkloadIdentity
w.cred = cred
return &w, nil
}
// GetToken requests an access token from Azure Active Directory. Azure SDK clients call this method automatically.
func (w *WorkloadIdentityCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
return w.cred.GetToken(ctx, opts)
}
// getAssertion returns the specified file's content, which is expected to be a Kubernetes service account token.
// Kubernetes is responsible for updating the file as service account tokens expire.
func (w *WorkloadIdentityCredential) getAssertion(context.Context) (string, error) {
w.mtx.RLock()
if w.expires.Before(time.Now()) {
// ensure only one goroutine at a time updates the assertion
w.mtx.RUnlock()
w.mtx.Lock()
defer w.mtx.Unlock()
// double check because another goroutine may have acquired the write lock first and done the update
if now := time.Now(); w.expires.Before(now) {
content, err := os.ReadFile(w.file)
if err != nil {
return "", err
}
w.assertion = string(content)
// Kubernetes rotates service account tokens when they reach 80% of their total TTL. The shortest TTL
// is 1 hour. That implies the token we just read is valid for at least 12 minutes (20% of 1 hour),
// but we add some margin for safety.
w.expires = now.Add(10 * time.Minute)
}
} else {
defer w.mtx.RUnlock()
}
return w.assertion, nil
}

View file

@ -0,0 +1,327 @@
# Release History
## 5.3.0 (2023-11-24)
### Features Added
- Support for test fakes and OpenTelemetry trace spans.
## 5.3.0-beta.2 (2023-10-30)
### Other Changes
- Updated with latest code generator to fix a few issues in fakes.
## 5.3.0-beta.1 (2023-10-09)
### Features Added
- Support for test fakes and OpenTelemetry trace spans.
## 5.2.0 (2023-09-22)
### Features Added
- New value `DiskCreateOptionCopyFromSanSnapshot` added to enum type `DiskCreateOption`
- New enum type `DomainNameLabelScopeTypes` with values `DomainNameLabelScopeTypesNoReuse`, `DomainNameLabelScopeTypesResourceGroupReuse`, `DomainNameLabelScopeTypesSubscriptionReuse`, `DomainNameLabelScopeTypesTenantReuse`
- New enum type `NetworkInterfaceAuxiliaryMode` with values `NetworkInterfaceAuxiliaryModeAcceleratedConnections`, `NetworkInterfaceAuxiliaryModeFloating`, `NetworkInterfaceAuxiliaryModeNone`
- New enum type `NetworkInterfaceAuxiliarySKU` with values `NetworkInterfaceAuxiliarySKUA1`, `NetworkInterfaceAuxiliarySKUA2`, `NetworkInterfaceAuxiliarySKUA4`, `NetworkInterfaceAuxiliarySKUA8`, `NetworkInterfaceAuxiliarySKUNone`
- New field `ElasticSanResourceID` in struct `CreationData`
- New field `LastOwnershipUpdateTime` in struct `DiskProperties`
- New field `AuxiliaryMode`, `AuxiliarySKU` in struct `VirtualMachineNetworkInterfaceConfigurationProperties`
- New field `DomainNameLabelScope` in struct `VirtualMachinePublicIPAddressDNSSettingsConfiguration`
- New field `AuxiliaryMode`, `AuxiliarySKU` in struct `VirtualMachineScaleSetNetworkConfigurationProperties`
- New field `DomainNameLabelScope` in struct `VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings`
- New field `AuxiliaryMode`, `AuxiliarySKU` in struct `VirtualMachineScaleSetUpdateNetworkConfigurationProperties`
- New field `TimeCreated` in struct `VirtualMachineScaleSetVMProperties`
## 5.1.0 (2023-07-28)
### Features Added
- New enum type `FileFormat` with values `FileFormatVHD`, `FileFormatVHDX`
- New field `FileFormat` in struct `GrantAccessData`
## 5.0.0 (2023-05-26)
### Breaking Changes
- Type of `CommunityGalleryImageProperties.Identifier` has been changed from `*GalleryImageIdentifier` to `*CommunityGalleryImageIdentifier`
- Type of `GalleryTargetExtendedLocation.StorageAccountType` has been changed from `*StorageAccountType` to `*EdgeZoneStorageAccountType`
- Type of `RestorePointSourceVMDataDisk.DiskRestorePoint` has been changed from `*APIEntityReference` to `*DiskRestorePointAttributes`
- Type of `RestorePointSourceVMOSDisk.DiskRestorePoint` has been changed from `*APIEntityReference` to `*DiskRestorePointAttributes`
- `StorageAccountTypeStandardSSDLRS` from enum `StorageAccountType` has been removed
- Field `ID` of struct `VirtualMachineScaleSetIPConfiguration` has been removed
- Field `ID` of struct `VirtualMachineScaleSetNetworkConfiguration` has been removed
- Field `ID` of struct `VirtualMachineScaleSetUpdateIPConfiguration` has been removed
- Field `ID` of struct `VirtualMachineScaleSetUpdateNetworkConfiguration` has been removed
### Features Added
- New enum type `EdgeZoneStorageAccountType` with values `EdgeZoneStorageAccountTypePremiumLRS`, `EdgeZoneStorageAccountTypeStandardLRS`, `EdgeZoneStorageAccountTypeStandardSSDLRS`, `EdgeZoneStorageAccountTypeStandardZRS`
- New enum type `ExpandTypeForListVMs` with values `ExpandTypeForListVMsInstanceView`
- New enum type `ExpandTypesForListVMs` with values `ExpandTypesForListVMsInstanceView`
- New enum type `RestorePointEncryptionType` with values `RestorePointEncryptionTypeEncryptionAtRestWithCustomerKey`, `RestorePointEncryptionTypeEncryptionAtRestWithPlatformAndCustomerKeys`, `RestorePointEncryptionTypeEncryptionAtRestWithPlatformKey`
- New function `*DedicatedHostsClient.NewListAvailableSizesPager(string, string, string, *DedicatedHostsClientListAvailableSizesOptions) *runtime.Pager[DedicatedHostsClientListAvailableSizesResponse]`
- New function `*VirtualMachineScaleSetsClient.BeginReapply(context.Context, string, string, *VirtualMachineScaleSetsClientBeginReapplyOptions) (*runtime.Poller[VirtualMachineScaleSetsClientReapplyResponse], error)`
- New struct `CommunityGalleryImageIdentifier`
- New struct `DedicatedHostSizeListResult`
- New struct `DiskRestorePointAttributes`
- New struct `RestorePointEncryption`
- New struct `RunCommandManagedIdentity`
- New struct `SecurityPostureReference`
- New field `SKU` in struct `DedicatedHostUpdate`
- New field `BypassPlatformSafetyChecksOnUserSchedule` in struct `LinuxVMGuestPatchAutomaticByPlatformSettings`
- New field `HyperVGeneration` in struct `RestorePointSourceMetadata`
- New field `WriteAcceleratorEnabled` in struct `RestorePointSourceVMDataDisk`
- New field `WriteAcceleratorEnabled` in struct `RestorePointSourceVMOSDisk`
- New field `ProvisionAfterExtensions` in struct `VirtualMachineExtensionProperties`
- New field `ErrorBlobManagedIdentity`, `OutputBlobManagedIdentity`, `TreatFailureAsDeploymentFailure` in struct `VirtualMachineRunCommandProperties`
- New field `ScriptURIManagedIdentity` in struct `VirtualMachineRunCommandScriptSource`
- New field `PriorityMixPolicy`, `SpotRestorePolicy` in struct `VirtualMachineScaleSetUpdateProperties`
- New field `Location` in struct `VirtualMachineScaleSetVMExtension`
- New field `SecurityPostureReference` in struct `VirtualMachineScaleSetVMProfile`
- New field `Hibernate` in struct `VirtualMachineScaleSetsClientBeginDeallocateOptions`
- New field `Expand` in struct `VirtualMachinesClientListAllOptions`
- New field `Expand` in struct `VirtualMachinesClientListOptions`
- New field `BypassPlatformSafetyChecksOnUserSchedule` in struct `WindowsVMGuestPatchAutomaticByPlatformSettings`
## 4.2.1 (2023-04-14)
### Bug Fixes
- Fix serialization bug of empty value of `any` type.
## 4.2.0 (2023-03-27)
### Features Added
- New struct `ClientFactory` which is a client factory used to create any client in this module
- New value `StorageAccountTypeStandardSSDLRS` added to enum type `StorageAccountType`
- New field `ComputerName` in struct `VirtualMachineScaleSetVMInstanceView`
- New field `HyperVGeneration` in struct `VirtualMachineScaleSetVMInstanceView`
- New field `OSName` in struct `VirtualMachineScaleSetVMInstanceView`
- New field `OSVersion` in struct `VirtualMachineScaleSetVMInstanceView`
## 4.1.0 (2023-01-27)
### Features Added
- New type alias `AlternativeType` with values `AlternativeTypeNone`, `AlternativeTypeOffer`, `AlternativeTypePlan`
- New type alias `ImageState` with values `ImageStateActive`, `ImageStateDeprecated`, `ImageStateScheduledForDeprecation`
- New struct `AlternativeOption`
- New struct `ImageDeprecationStatus`
- New struct `OSImageNotificationProfile`
- New struct `OSProfileProvisioningData`
- New struct `ServiceArtifactReference`
- New field `Zones` in struct `CloudService`
- New field `UserData` in struct `RestorePointSourceMetadata`
- New field `MaxSurge` in struct `RollingUpgradePolicy`
- New field `RollbackFailedInstancesOnPolicyBreach` in struct `RollingUpgradePolicy`
- New field `OSImageNotificationProfile` in struct `ScheduledEventsProfile`
- New field `ImageDeprecationStatus` in struct `VirtualMachineImageProperties`
- New field `ExactVersion` in struct `VirtualMachineReimageParameters`
- New field `OSProfile` in struct `VirtualMachineReimageParameters`
- New field `RequireGuestProvisionSignal` in struct `VirtualMachineScaleSetOSProfile`
- New field `ConstrainedMaximumCapacity` in struct `VirtualMachineScaleSetProperties`
- New field `ExactVersion` in struct `VirtualMachineScaleSetReimageParameters`
- New field `OSProfile` in struct `VirtualMachineScaleSetReimageParameters`
- New field `ServiceArtifactReference` in struct `VirtualMachineScaleSetVMProfile`
- New field `ExactVersion` in struct `VirtualMachineScaleSetVMReimageParameters`
- New field `OSProfile` in struct `VirtualMachineScaleSetVMReimageParameters`
## 4.0.0 (2022-10-04)
### Breaking Changes
- Type of `GalleryImageVersionStorageProfile.Source` has been changed from `*GalleryArtifactVersionSource` to `*GalleryArtifactVersionFullSource`
- Type of `SharingProfile.CommunityGalleryInfo` has been changed from `interface{}` to `*CommunityGalleryInfo`
- Type of `VirtualMachineExtensionUpdateProperties.ProtectedSettingsFromKeyVault` has been changed from `interface{}` to `*KeyVaultSecretReference`
- Type of `GalleryOSDiskImage.Source` has been changed from `*GalleryArtifactVersionSource` to `*GalleryDiskImageSource`
- Type of `GalleryDiskImage.Source` has been changed from `*GalleryArtifactVersionSource` to `*GalleryDiskImageSource`
- Type of `GalleryDataDiskImage.Source` has been changed from `*GalleryArtifactVersionSource` to `*GalleryDiskImageSource`
- Type of `VirtualMachineScaleSetExtensionProperties.ProtectedSettingsFromKeyVault` has been changed from `interface{}` to `*KeyVaultSecretReference`
- Type of `VirtualMachineExtensionProperties.ProtectedSettingsFromKeyVault` has been changed from `interface{}` to `*KeyVaultSecretReference`
- Field `URI` of struct `GalleryArtifactVersionSource` has been removed
### Features Added
- New const `DiskControllerTypesSCSI`
- New const `PolicyViolationCategoryImageFlaggedUnsafe`
- New const `GalleryApplicationCustomActionParameterTypeConfigurationDataBlob`
- New const `PolicyViolationCategoryIPTheft`
- New const `PolicyViolationCategoryCopyrightValidation`
- New const `PolicyViolationCategoryOther`
- New const `GalleryApplicationCustomActionParameterTypeString`
- New const `DiskControllerTypesNVMe`
- New const `GalleryApplicationCustomActionParameterTypeLogOutputBlob`
- New type alias `DiskControllerTypes`
- New type alias `PolicyViolationCategory`
- New type alias `GalleryApplicationCustomActionParameterType`
- New function `PossiblePolicyViolationCategoryValues() []PolicyViolationCategory`
- New function `PossibleGalleryApplicationCustomActionParameterTypeValues() []GalleryApplicationCustomActionParameterType`
- New function `PossibleDiskControllerTypesValues() []DiskControllerTypes`
- New struct `GalleryApplicationCustomAction`
- New struct `GalleryApplicationCustomActionParameter`
- New struct `GalleryApplicationVersionSafetyProfile`
- New struct `GalleryArtifactSafetyProfileBase`
- New struct `GalleryArtifactVersionFullSource`
- New struct `GalleryDiskImageSource`
- New struct `GalleryImageVersionSafetyProfile`
- New struct `LatestGalleryImageVersion`
- New struct `PolicyViolation`
- New struct `PriorityMixPolicy`
- New field `DiskControllerType` in struct `VirtualMachineScaleSetUpdateStorageProfile`
- New field `HardwareProfile` in struct `VirtualMachineScaleSetUpdateVMProfile`
- New field `CustomActions` in struct `GalleryApplicationProperties`
- New field `DisableTCPStateTracking` in struct `VirtualMachineScaleSetNetworkConfigurationProperties`
- New field `DiskControllerType` in struct `StorageProfile`
- New field `OptimizedForFrequentAttach` in struct `DiskProperties`
- New field `BurstingEnabledTime` in struct `DiskProperties`
- New field `DiskControllerTypes` in struct `SupportedCapabilities`
- New field `DisableTCPStateTracking` in struct `VirtualMachineNetworkInterfaceConfigurationProperties`
- New field `EnableVMAgentPlatformUpdates` in struct `WindowsConfiguration`
- New field `PerformancePlus` in struct `CreationData`
- New field `IncrementalSnapshotFamilyID` in struct `SnapshotProperties`
- New field `OptimizedForFrequentAttach` in struct `DiskUpdateProperties`
- New field `DisableTCPStateTracking` in struct `VirtualMachineScaleSetUpdateNetworkConfigurationProperties`
- New field `ExcludeFromLatest` in struct `TargetRegion`
- New field `PrivacyStatementURI` in struct `SharedGalleryImageProperties`
- New field `Eula` in struct `SharedGalleryImageProperties`
- New field `SafetyProfile` in struct `GalleryApplicationVersionProperties`
- New field `SafetyProfile` in struct `GalleryImageVersionProperties`
- New field `EnableVMAgentPlatformUpdates` in struct `LinuxConfiguration`
- New field `CurrentCapacity` in struct `CapacityReservationUtilization`
- New field `PriorityMixPolicy` in struct `VirtualMachineScaleSetProperties`
- New field `CustomActions` in struct `GalleryApplicationVersionPublishingProfile`
- New field `PlatformFaultDomainCount` in struct `CapacityReservationProperties`
- New field `DiskControllerType` in struct `VirtualMachineScaleSetStorageProfile`
## 3.0.1 (2022-07-29)
### Other Changes
- Fix wrong module import for live test
## 3.0.0 (2022-06-24)
### Breaking Changes
- Function `*CloudServicesClient.BeginCreateOrUpdate` parameter(s) have been changed from `(context.Context, string, string, *CloudServicesClientBeginCreateOrUpdateOptions)` to `(context.Context, string, string, CloudService, *CloudServicesClientBeginCreateOrUpdateOptions)`
- Function `*CloudServicesClient.BeginUpdate` parameter(s) have been changed from `(context.Context, string, string, *CloudServicesClientBeginUpdateOptions)` to `(context.Context, string, string, CloudServiceUpdate, *CloudServicesClientBeginUpdateOptions)`
- Function `*CloudServicesUpdateDomainClient.BeginWalkUpdateDomain` parameter(s) have been changed from `(context.Context, string, string, int32, *CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions)` to `(context.Context, string, string, int32, UpdateDomain, *CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions)`
- Type of `CloudServiceExtensionProperties.Settings` has been changed from `*string` to `interface{}`
- Type of `CloudServiceExtensionProperties.ProtectedSettings` has been changed from `*string` to `interface{}`
- Field `Parameters` of struct `CloudServicesClientBeginUpdateOptions` has been removed
- Field `Parameters` of struct `CloudServicesClientBeginCreateOrUpdateOptions` has been removed
- Field `Parameters` of struct `CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions` has been removed
### Features Added
- New const `CloudServiceSlotTypeProduction`
- New const `CloudServiceSlotTypeStaging`
- New function `*VirtualMachineImagesClient.ListByEdgeZone(context.Context, string, string, *VirtualMachineImagesClientListByEdgeZoneOptions) (VirtualMachineImagesClientListByEdgeZoneResponse, error)`
- New function `PossibleCloudServiceSlotTypeValues() []CloudServiceSlotType`
- New struct `SystemData`
- New struct `VMImagesInEdgeZoneListResult`
- New struct `VirtualMachineImagesClientListByEdgeZoneOptions`
- New struct `VirtualMachineImagesClientListByEdgeZoneResponse`
- New field `SystemData` in struct `CloudService`
- New field `SlotType` in struct `CloudServiceNetworkProfile`
## 2.0.0 (2022-06-02)
### Breaking Changes
- Type of `GalleryProperties.ProvisioningState` has been changed from `*GalleryPropertiesProvisioningState` to `*GalleryProvisioningState`
- Type of `GalleryImageVersionProperties.ProvisioningState` has been changed from `*GalleryImageVersionPropertiesProvisioningState` to `*GalleryProvisioningState`
- Type of `GalleryImageProperties.ProvisioningState` has been changed from `*GalleryImagePropertiesProvisioningState` to `*GalleryProvisioningState`
- Type of `GalleryApplicationVersionProperties.ProvisioningState` has been changed from `*GalleryApplicationVersionPropertiesProvisioningState` to `*GalleryProvisioningState`
- Type of `VirtualMachineScaleSetIdentity.UserAssignedIdentities` has been changed from `map[string]*VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue` to `map[string]*UserAssignedIdentitiesValue`
- Const `GalleryImagePropertiesProvisioningStateFailed` has been removed
- Const `GalleryImagePropertiesProvisioningStateMigrating` has been removed
- Const `GalleryImageVersionPropertiesProvisioningStateCreating` has been removed
- Const `GalleryImageVersionPropertiesProvisioningStateMigrating` has been removed
- Const `GalleryApplicationVersionPropertiesProvisioningStateFailed` has been removed
- Const `GalleryPropertiesProvisioningStateMigrating` has been removed
- Const `GalleryApplicationVersionPropertiesProvisioningStateDeleting` has been removed
- Const `GalleryPropertiesProvisioningStateDeleting` has been removed
- Const `GalleryApplicationVersionPropertiesProvisioningStateCreating` has been removed
- Const `GalleryImageVersionPropertiesProvisioningStateSucceeded` has been removed
- Const `GalleryImagePropertiesProvisioningStateCreating` has been removed
- Const `GalleryImagePropertiesProvisioningStateUpdating` has been removed
- Const `GalleryImageVersionPropertiesProvisioningStateDeleting` has been removed
- Const `GalleryPropertiesProvisioningStateFailed` has been removed
- Const `SharingProfileGroupTypesCommunity` has been removed
- Const `GalleryApplicationVersionPropertiesProvisioningStateSucceeded` has been removed
- Const `GalleryApplicationVersionPropertiesProvisioningStateMigrating` has been removed
- Const `GalleryPropertiesProvisioningStateUpdating` has been removed
- Const `GalleryImageVersionPropertiesProvisioningStateFailed` has been removed
- Const `GalleryImagePropertiesProvisioningStateDeleting` has been removed
- Const `GalleryImageVersionPropertiesProvisioningStateUpdating` has been removed
- Const `GalleryPropertiesProvisioningStateCreating` has been removed
- Const `GalleryApplicationVersionPropertiesProvisioningStateUpdating` has been removed
- Const `GalleryImagePropertiesProvisioningStateSucceeded` has been removed
- Const `GalleryPropertiesProvisioningStateSucceeded` has been removed
- Function `PossibleGalleryPropertiesProvisioningStateValues` has been removed
- Function `PossibleGalleryImageVersionPropertiesProvisioningStateValues` has been removed
- Function `PossibleGalleryImagePropertiesProvisioningStateValues` has been removed
- Function `PossibleGalleryApplicationVersionPropertiesProvisioningStateValues` has been removed
- Struct `VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue` has been removed
### Features Added
- New const `GallerySharingPermissionTypesCommunity`
- New const `GalleryProvisioningStateUpdating`
- New const `SharedGalleryHostCachingReadOnly`
- New const `SharedGalleryHostCachingNone`
- New const `GalleryProvisioningStateSucceeded`
- New const `GalleryProvisioningStateFailed`
- New const `SharedGalleryHostCachingReadWrite`
- New const `GalleryProvisioningStateCreating`
- New const `DiskEncryptionSetIdentityTypeUserAssigned`
- New const `GalleryProvisioningStateMigrating`
- New const `DiskEncryptionSetIdentityTypeSystemAssignedUserAssigned`
- New const `CopyCompletionErrorReasonCopySourceNotFound`
- New const `GalleryProvisioningStateDeleting`
- New const `DiskStorageAccountTypesPremiumV2LRS`
- New function `PossibleCopyCompletionErrorReasonValues() []CopyCompletionErrorReason`
- New function `PossibleSharedGalleryHostCachingValues() []SharedGalleryHostCaching`
- New function `PossibleGalleryProvisioningStateValues() []GalleryProvisioningState`
- New function `EncryptionSetIdentity.MarshalJSON() ([]byte, error)`
- New function `*CommunityGalleryImagesClient.NewListPager(string, string, *CommunityGalleryImagesClientListOptions) *runtime.Pager[CommunityGalleryImagesClientListResponse]`
- New function `*CommunityGalleryImageVersionsClient.NewListPager(string, string, string, *CommunityGalleryImageVersionsClientListOptions) *runtime.Pager[CommunityGalleryImageVersionsClientListResponse]`
- New struct `CommunityGalleryImageList`
- New struct `CommunityGalleryImageVersionList`
- New struct `CommunityGalleryImageVersionsClientListOptions`
- New struct `CommunityGalleryImageVersionsClientListResponse`
- New struct `CommunityGalleryImagesClientListOptions`
- New struct `CommunityGalleryImagesClientListResponse`
- New struct `CopyCompletionError`
- New struct `SharedGalleryDataDiskImage`
- New struct `SharedGalleryDiskImage`
- New struct `SharedGalleryImageVersionStorageProfile`
- New struct `SharedGalleryOSDiskImage`
- New struct `UserArtifactSettings`
- New field `SharedGalleryImageID` in struct `ImageDiskReference`
- New field `CommunityGalleryImageID` in struct `ImageDiskReference`
- New field `AdvancedSettings` in struct `GalleryApplicationVersionPublishingProfile`
- New field `Settings` in struct `GalleryApplicationVersionPublishingProfile`
- New field `CopyCompletionError` in struct `SnapshotProperties`
- New field `ExcludeFromLatest` in struct `SharedGalleryImageVersionProperties`
- New field `StorageProfile` in struct `SharedGalleryImageVersionProperties`
- New field `ExcludeFromLatest` in struct `CommunityGalleryImageVersionProperties`
- New field `StorageProfile` in struct `CommunityGalleryImageVersionProperties`
- New field `Architecture` in struct `SharedGalleryImageProperties`
- New field `UserAssignedIdentities` in struct `EncryptionSetIdentity`
- New field `Eula` in struct `CommunityGalleryImageProperties`
- New field `PrivacyStatementURI` in struct `CommunityGalleryImageProperties`
- New field `Architecture` in struct `CommunityGalleryImageProperties`
- New field `FederatedClientID` in struct `DiskEncryptionSetUpdateProperties`
- New field `FederatedClientID` in struct `EncryptionSetProperties`
- New field `SecurityProfile` in struct `DiskRestorePointProperties`
## 1.0.0 (2022-05-16)
The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute` is using our [next generation design principles](https://azure.github.io/azure-sdk/general_introduction.html) since version 1.0.0, which contains breaking changes.
To migrate the existing applications to the latest version, please refer to [Migration Guide](https://aka.ms/azsdk/go/mgmt/migration).
To learn more, please refer to our documentation [Quick Start](https://aka.ms/azsdk/go/mgmt).

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,113 @@
# Azure Compute Module for Go
[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v4)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v4)
The `armcompute` module provides operations for working with Azure Compute.
[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/compute/armcompute)
# Getting started
## Prerequisites
- an [Azure subscription](https://azure.microsoft.com/free/)
- Go 1.18 or above (You could download and install the latest version of Go from [here](https://go.dev/doc/install). It will replace the existing Go on your machine. If you want to install multiple Go versions on the same machine, you could refer this [doc](https://go.dev/doc/manage-install).)
## Install the package
This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management.
Install the Azure Compute module:
```sh
go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v4
```
## Authorization
When creating a client, you will need to provide a credential for authenticating with Azure Compute. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more.
```go
cred, err := azidentity.NewDefaultAzureCredential(nil)
```
For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity).
## Client Factory
Azure Compute module consists of one or more clients. We provide a client factory which could be used to create any client in this module.
```go
clientFactory, err := armcompute.NewClientFactory(<subscription ID>, cred, nil)
```
You can use `ClientOptions` in package `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` to set endpoint to connect with public and sovereign clouds as well as Azure Stack. For more information, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore).
```go
options := arm.ClientOptions {
ClientOptions: azcore.ClientOptions {
Cloud: cloud.AzureChina,
},
}
clientFactory, err := armcompute.NewClientFactory(<subscription ID>, cred, &options)
```
## Clients
A client groups a set of related APIs, providing access to its functionality. Create one or more clients to access the APIs you require using client factory.
```go
client := clientFactory.NewLogAnalyticsClient()
```
## Fakes
The fake package contains types used for constructing in-memory fake servers used in unit tests.
This allows writing tests to cover various success/error conditions without the need for connecting to a live service.
Please see https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/samples/fakes for details and examples on how to use fakes.
## More sample code
- [Availability Set](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/availabilityset)
- [Creating a Fake](https://github.com/Azure/azure-sdk-for-go/blob/main/sdk/resourcemanager/compute/armcompute/fake_example_test.go)
- [Virtual Machine](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/create_vm)
- [Dedicated Host](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/dedicated_host)
- [Disk](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/disk)
- [Gallery](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/gallery)
- [Proximity Placement Group](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/proximity)
- [Snapshot](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/snapshot)
- [Virtual Machine Scale Set](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/vmscaleset)
## Major Version Upgrade
Go uses [semantic import versioning](https://github.com/golang/go/wiki/Modules#semantic-import-versioning) to ensure a good backward compatibility for modules. For Azure Go management SDK, we usually upgrade module version according to cooresponding service's API version. Regarding it could be a complicated experience for major version upgrade, we will try our best to keep the SDK API stable and release new version in backward compatible way. However, if any unavoidable breaking changes and a new major version releases for SDK modules, you could use these commands under your module folder to upgrade:
```sh
go install github.com/icholy/gomajor@latest
gomajor get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute@latest
```
## Provide Feedback
If you encounter bugs or have suggestions, please
[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Compute` label.
# Contributing
This project welcomes contributions and suggestions. Most contributions require
you to agree to a Contributor License Agreement (CLA) declaring that you have
the right to, and actually do, grant us the rights to use your contribution.
For details, visit [https://cla.microsoft.com](https://cla.microsoft.com).
When you submit a pull request, a CLA-bot will automatically determine whether
you need to provide a CLA and decorate the PR appropriately (e.g., label,
comment). Simply follow the instructions provided by the bot. You will only
need to do this once across all repos using our CLA.
This project has adopted the
[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information, see the
[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any
additional questions or comments.

View file

@ -0,0 +1,6 @@
{
"AssetsRepo": "Azure/azure-sdk-assets",
"AssetsRepoPrefixPath": "go",
"TagPrefix": "go/resourcemanager/compute/armcompute",
"Tag": "go/resourcemanager/compute/armcompute_367222fc88"
}

View file

@ -0,0 +1,13 @@
### AutoRest Configuration
> see https://aka.ms/autorest
``` yaml
azure-arm: true
require:
- https://github.com/Azure/azure-rest-api-specs/blob/c78b5d8bd3aff2d82a5f034d9164b1a9ac030e09/specification/compute/resource-manager/readme.md
- https://github.com/Azure/azure-rest-api-specs/blob/c78b5d8bd3aff2d82a5f034d9164b1a9ac030e09/specification/compute/resource-manager/readme.go.md
license-header: MICROSOFT_MIT_NO_VERSION
module-version: 5.3.0
tag: package-2023-07-01
```

View file

@ -0,0 +1,485 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// AvailabilitySetsClient contains the methods for the AvailabilitySets group.
// Don't use this type directly, use NewAvailabilitySetsClient() instead.
type AvailabilitySetsClient struct {
internal *arm.Client
subscriptionID string
}
// NewAvailabilitySetsClient creates a new instance of AvailabilitySetsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewAvailabilitySetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AvailabilitySetsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &AvailabilitySetsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// CreateOrUpdate - Create or update an availability set.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - availabilitySetName - The name of the availability set.
// - parameters - Parameters supplied to the Create Availability Set operation.
// - options - AvailabilitySetsClientCreateOrUpdateOptions contains the optional parameters for the AvailabilitySetsClient.CreateOrUpdate
// method.
func (client *AvailabilitySetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, availabilitySetName string, parameters AvailabilitySet, options *AvailabilitySetsClientCreateOrUpdateOptions) (AvailabilitySetsClientCreateOrUpdateResponse, error) {
var err error
const operationName = "AvailabilitySetsClient.CreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, availabilitySetName, parameters, options)
if err != nil {
return AvailabilitySetsClientCreateOrUpdateResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return AvailabilitySetsClientCreateOrUpdateResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return AvailabilitySetsClientCreateOrUpdateResponse{}, err
}
resp, err := client.createOrUpdateHandleResponse(httpResp)
return resp, err
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *AvailabilitySetsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, availabilitySetName string, parameters AvailabilitySet, options *AvailabilitySetsClientCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if availabilitySetName == "" {
return nil, errors.New("parameter availabilitySetName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{availabilitySetName}", url.PathEscape(availabilitySetName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// createOrUpdateHandleResponse handles the CreateOrUpdate response.
func (client *AvailabilitySetsClient) createOrUpdateHandleResponse(resp *http.Response) (AvailabilitySetsClientCreateOrUpdateResponse, error) {
result := AvailabilitySetsClientCreateOrUpdateResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilitySet); err != nil {
return AvailabilitySetsClientCreateOrUpdateResponse{}, err
}
return result, nil
}
// Delete - Delete an availability set.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - availabilitySetName - The name of the availability set.
// - options - AvailabilitySetsClientDeleteOptions contains the optional parameters for the AvailabilitySetsClient.Delete method.
func (client *AvailabilitySetsClient) Delete(ctx context.Context, resourceGroupName string, availabilitySetName string, options *AvailabilitySetsClientDeleteOptions) (AvailabilitySetsClientDeleteResponse, error) {
var err error
const operationName = "AvailabilitySetsClient.Delete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, availabilitySetName, options)
if err != nil {
return AvailabilitySetsClientDeleteResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return AvailabilitySetsClientDeleteResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return AvailabilitySetsClientDeleteResponse{}, err
}
return AvailabilitySetsClientDeleteResponse{}, nil
}
// deleteCreateRequest creates the Delete request.
func (client *AvailabilitySetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, availabilitySetName string, options *AvailabilitySetsClientDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if availabilitySetName == "" {
return nil, errors.New("parameter availabilitySetName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{availabilitySetName}", url.PathEscape(availabilitySetName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - Retrieves information about an availability set.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - availabilitySetName - The name of the availability set.
// - options - AvailabilitySetsClientGetOptions contains the optional parameters for the AvailabilitySetsClient.Get method.
func (client *AvailabilitySetsClient) Get(ctx context.Context, resourceGroupName string, availabilitySetName string, options *AvailabilitySetsClientGetOptions) (AvailabilitySetsClientGetResponse, error) {
var err error
const operationName = "AvailabilitySetsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, availabilitySetName, options)
if err != nil {
return AvailabilitySetsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return AvailabilitySetsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return AvailabilitySetsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *AvailabilitySetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, availabilitySetName string, options *AvailabilitySetsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if availabilitySetName == "" {
return nil, errors.New("parameter availabilitySetName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{availabilitySetName}", url.PathEscape(availabilitySetName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *AvailabilitySetsClient) getHandleResponse(resp *http.Response) (AvailabilitySetsClientGetResponse, error) {
result := AvailabilitySetsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilitySet); err != nil {
return AvailabilitySetsClientGetResponse{}, err
}
return result, nil
}
// NewListPager - Lists all availability sets in a resource group.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - options - AvailabilitySetsClientListOptions contains the optional parameters for the AvailabilitySetsClient.NewListPager
// method.
func (client *AvailabilitySetsClient) NewListPager(resourceGroupName string, options *AvailabilitySetsClientListOptions) *runtime.Pager[AvailabilitySetsClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[AvailabilitySetsClientListResponse]{
More: func(page AvailabilitySetsClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *AvailabilitySetsClientListResponse) (AvailabilitySetsClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AvailabilitySetsClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, resourceGroupName, options)
}, nil)
if err != nil {
return AvailabilitySetsClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *AvailabilitySetsClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *AvailabilitySetsClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *AvailabilitySetsClient) listHandleResponse(resp *http.Response) (AvailabilitySetsClientListResponse, error) {
result := AvailabilitySetsClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilitySetListResult); err != nil {
return AvailabilitySetsClientListResponse{}, err
}
return result, nil
}
// NewListAvailableSizesPager - Lists all available virtual machine sizes that can be used to create a new virtual machine
// in an existing availability set.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - availabilitySetName - The name of the availability set.
// - options - AvailabilitySetsClientListAvailableSizesOptions contains the optional parameters for the AvailabilitySetsClient.NewListAvailableSizesPager
// method.
func (client *AvailabilitySetsClient) NewListAvailableSizesPager(resourceGroupName string, availabilitySetName string, options *AvailabilitySetsClientListAvailableSizesOptions) *runtime.Pager[AvailabilitySetsClientListAvailableSizesResponse] {
return runtime.NewPager(runtime.PagingHandler[AvailabilitySetsClientListAvailableSizesResponse]{
More: func(page AvailabilitySetsClientListAvailableSizesResponse) bool {
return false
},
Fetcher: func(ctx context.Context, page *AvailabilitySetsClientListAvailableSizesResponse) (AvailabilitySetsClientListAvailableSizesResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AvailabilitySetsClient.NewListAvailableSizesPager")
req, err := client.listAvailableSizesCreateRequest(ctx, resourceGroupName, availabilitySetName, options)
if err != nil {
return AvailabilitySetsClientListAvailableSizesResponse{}, err
}
resp, err := client.internal.Pipeline().Do(req)
if err != nil {
return AvailabilitySetsClientListAvailableSizesResponse{}, err
}
if !runtime.HasStatusCode(resp, http.StatusOK) {
return AvailabilitySetsClientListAvailableSizesResponse{}, runtime.NewResponseError(resp)
}
return client.listAvailableSizesHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listAvailableSizesCreateRequest creates the ListAvailableSizes request.
func (client *AvailabilitySetsClient) listAvailableSizesCreateRequest(ctx context.Context, resourceGroupName string, availabilitySetName string, options *AvailabilitySetsClientListAvailableSizesOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}/vmSizes"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if availabilitySetName == "" {
return nil, errors.New("parameter availabilitySetName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{availabilitySetName}", url.PathEscape(availabilitySetName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listAvailableSizesHandleResponse handles the ListAvailableSizes response.
func (client *AvailabilitySetsClient) listAvailableSizesHandleResponse(resp *http.Response) (AvailabilitySetsClientListAvailableSizesResponse, error) {
result := AvailabilitySetsClientListAvailableSizesResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineSizeListResult); err != nil {
return AvailabilitySetsClientListAvailableSizesResponse{}, err
}
return result, nil
}
// NewListBySubscriptionPager - Lists all availability sets in a subscription.
//
// Generated from API version 2023-07-01
// - options - AvailabilitySetsClientListBySubscriptionOptions contains the optional parameters for the AvailabilitySetsClient.NewListBySubscriptionPager
// method.
func (client *AvailabilitySetsClient) NewListBySubscriptionPager(options *AvailabilitySetsClientListBySubscriptionOptions) *runtime.Pager[AvailabilitySetsClientListBySubscriptionResponse] {
return runtime.NewPager(runtime.PagingHandler[AvailabilitySetsClientListBySubscriptionResponse]{
More: func(page AvailabilitySetsClientListBySubscriptionResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *AvailabilitySetsClientListBySubscriptionResponse) (AvailabilitySetsClientListBySubscriptionResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AvailabilitySetsClient.NewListBySubscriptionPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listBySubscriptionCreateRequest(ctx, options)
}, nil)
if err != nil {
return AvailabilitySetsClientListBySubscriptionResponse{}, err
}
return client.listBySubscriptionHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listBySubscriptionCreateRequest creates the ListBySubscription request.
func (client *AvailabilitySetsClient) listBySubscriptionCreateRequest(ctx context.Context, options *AvailabilitySetsClientListBySubscriptionOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/availabilitySets"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
if options != nil && options.Expand != nil {
reqQP.Set("$expand", *options.Expand)
}
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listBySubscriptionHandleResponse handles the ListBySubscription response.
func (client *AvailabilitySetsClient) listBySubscriptionHandleResponse(resp *http.Response) (AvailabilitySetsClientListBySubscriptionResponse, error) {
result := AvailabilitySetsClientListBySubscriptionResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilitySetListResult); err != nil {
return AvailabilitySetsClientListBySubscriptionResponse{}, err
}
return result, nil
}
// Update - Update an availability set.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - availabilitySetName - The name of the availability set.
// - parameters - Parameters supplied to the Update Availability Set operation.
// - options - AvailabilitySetsClientUpdateOptions contains the optional parameters for the AvailabilitySetsClient.Update method.
func (client *AvailabilitySetsClient) Update(ctx context.Context, resourceGroupName string, availabilitySetName string, parameters AvailabilitySetUpdate, options *AvailabilitySetsClientUpdateOptions) (AvailabilitySetsClientUpdateResponse, error) {
var err error
const operationName = "AvailabilitySetsClient.Update"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, availabilitySetName, parameters, options)
if err != nil {
return AvailabilitySetsClientUpdateResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return AvailabilitySetsClientUpdateResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return AvailabilitySetsClientUpdateResponse{}, err
}
resp, err := client.updateHandleResponse(httpResp)
return resp, err
}
// updateCreateRequest creates the Update request.
func (client *AvailabilitySetsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, availabilitySetName string, parameters AvailabilitySetUpdate, options *AvailabilitySetsClientUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if availabilitySetName == "" {
return nil, errors.New("parameter availabilitySetName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{availabilitySetName}", url.PathEscape(availabilitySetName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// updateHandleResponse handles the Update response.
func (client *AvailabilitySetsClient) updateHandleResponse(resp *http.Response) (AvailabilitySetsClientUpdateResponse, error) {
result := AvailabilitySetsClientUpdateResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilitySet); err != nil {
return AvailabilitySetsClientUpdateResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// This file enables 'go generate' to regenerate this specific SDK
//go:generate pwsh ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate -alwaysSetBodyParamRequired resourcemanager/compute/armcompute
package armcompute

View file

@ -0,0 +1,434 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// CapacityReservationGroupsClient contains the methods for the CapacityReservationGroups group.
// Don't use this type directly, use NewCapacityReservationGroupsClient() instead.
type CapacityReservationGroupsClient struct {
internal *arm.Client
subscriptionID string
}
// NewCapacityReservationGroupsClient creates a new instance of CapacityReservationGroupsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewCapacityReservationGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CapacityReservationGroupsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &CapacityReservationGroupsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// CreateOrUpdate - The operation to create or update a capacity reservation group. When updating a capacity reservation group,
// only tags may be modified. Please refer to https://aka.ms/CapacityReservation for more
// details.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - capacityReservationGroupName - The name of the capacity reservation group.
// - parameters - Parameters supplied to the Create capacity reservation Group.
// - options - CapacityReservationGroupsClientCreateOrUpdateOptions contains the optional parameters for the CapacityReservationGroupsClient.CreateOrUpdate
// method.
func (client *CapacityReservationGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, parameters CapacityReservationGroup, options *CapacityReservationGroupsClientCreateOrUpdateOptions) (CapacityReservationGroupsClientCreateOrUpdateResponse, error) {
var err error
const operationName = "CapacityReservationGroupsClient.CreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, capacityReservationGroupName, parameters, options)
if err != nil {
return CapacityReservationGroupsClientCreateOrUpdateResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CapacityReservationGroupsClientCreateOrUpdateResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
err = runtime.NewResponseError(httpResp)
return CapacityReservationGroupsClientCreateOrUpdateResponse{}, err
}
resp, err := client.createOrUpdateHandleResponse(httpResp)
return resp, err
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *CapacityReservationGroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, parameters CapacityReservationGroup, options *CapacityReservationGroupsClientCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if capacityReservationGroupName == "" {
return nil, errors.New("parameter capacityReservationGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// createOrUpdateHandleResponse handles the CreateOrUpdate response.
func (client *CapacityReservationGroupsClient) createOrUpdateHandleResponse(resp *http.Response) (CapacityReservationGroupsClientCreateOrUpdateResponse, error) {
result := CapacityReservationGroupsClientCreateOrUpdateResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservationGroup); err != nil {
return CapacityReservationGroupsClientCreateOrUpdateResponse{}, err
}
return result, nil
}
// Delete - The operation to delete a capacity reservation group. This operation is allowed only if all the associated resources
// are disassociated from the reservation group and all capacity reservations under
// the reservation group have also been deleted. Please refer to https://aka.ms/CapacityReservation for more details.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - capacityReservationGroupName - The name of the capacity reservation group.
// - options - CapacityReservationGroupsClientDeleteOptions contains the optional parameters for the CapacityReservationGroupsClient.Delete
// method.
func (client *CapacityReservationGroupsClient) Delete(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, options *CapacityReservationGroupsClientDeleteOptions) (CapacityReservationGroupsClientDeleteResponse, error) {
var err error
const operationName = "CapacityReservationGroupsClient.Delete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, capacityReservationGroupName, options)
if err != nil {
return CapacityReservationGroupsClientDeleteResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CapacityReservationGroupsClientDeleteResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return CapacityReservationGroupsClientDeleteResponse{}, err
}
return CapacityReservationGroupsClientDeleteResponse{}, nil
}
// deleteCreateRequest creates the Delete request.
func (client *CapacityReservationGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, options *CapacityReservationGroupsClientDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if capacityReservationGroupName == "" {
return nil, errors.New("parameter capacityReservationGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - The operation that retrieves information about a capacity reservation group.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - capacityReservationGroupName - The name of the capacity reservation group.
// - options - CapacityReservationGroupsClientGetOptions contains the optional parameters for the CapacityReservationGroupsClient.Get
// method.
func (client *CapacityReservationGroupsClient) Get(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, options *CapacityReservationGroupsClientGetOptions) (CapacityReservationGroupsClientGetResponse, error) {
var err error
const operationName = "CapacityReservationGroupsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, capacityReservationGroupName, options)
if err != nil {
return CapacityReservationGroupsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CapacityReservationGroupsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return CapacityReservationGroupsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *CapacityReservationGroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, options *CapacityReservationGroupsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if capacityReservationGroupName == "" {
return nil, errors.New("parameter capacityReservationGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
if options != nil && options.Expand != nil {
reqQP.Set("$expand", string(*options.Expand))
}
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *CapacityReservationGroupsClient) getHandleResponse(resp *http.Response) (CapacityReservationGroupsClientGetResponse, error) {
result := CapacityReservationGroupsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservationGroup); err != nil {
return CapacityReservationGroupsClientGetResponse{}, err
}
return result, nil
}
// NewListByResourceGroupPager - Lists all of the capacity reservation groups in the specified resource group. Use the nextLink
// property in the response to get the next page of capacity reservation groups.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - options - CapacityReservationGroupsClientListByResourceGroupOptions contains the optional parameters for the CapacityReservationGroupsClient.NewListByResourceGroupPager
// method.
func (client *CapacityReservationGroupsClient) NewListByResourceGroupPager(resourceGroupName string, options *CapacityReservationGroupsClientListByResourceGroupOptions) *runtime.Pager[CapacityReservationGroupsClientListByResourceGroupResponse] {
return runtime.NewPager(runtime.PagingHandler[CapacityReservationGroupsClientListByResourceGroupResponse]{
More: func(page CapacityReservationGroupsClientListByResourceGroupResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *CapacityReservationGroupsClientListByResourceGroupResponse) (CapacityReservationGroupsClientListByResourceGroupResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CapacityReservationGroupsClient.NewListByResourceGroupPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options)
}, nil)
if err != nil {
return CapacityReservationGroupsClientListByResourceGroupResponse{}, err
}
return client.listByResourceGroupHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *CapacityReservationGroupsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *CapacityReservationGroupsClientListByResourceGroupOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
if options != nil && options.Expand != nil {
reqQP.Set("$expand", string(*options.Expand))
}
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *CapacityReservationGroupsClient) listByResourceGroupHandleResponse(resp *http.Response) (CapacityReservationGroupsClientListByResourceGroupResponse, error) {
result := CapacityReservationGroupsClientListByResourceGroupResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservationGroupListResult); err != nil {
return CapacityReservationGroupsClientListByResourceGroupResponse{}, err
}
return result, nil
}
// NewListBySubscriptionPager - Lists all of the capacity reservation groups in the subscription. Use the nextLink property
// in the response to get the next page of capacity reservation groups.
//
// Generated from API version 2023-07-01
// - options - CapacityReservationGroupsClientListBySubscriptionOptions contains the optional parameters for the CapacityReservationGroupsClient.NewListBySubscriptionPager
// method.
func (client *CapacityReservationGroupsClient) NewListBySubscriptionPager(options *CapacityReservationGroupsClientListBySubscriptionOptions) *runtime.Pager[CapacityReservationGroupsClientListBySubscriptionResponse] {
return runtime.NewPager(runtime.PagingHandler[CapacityReservationGroupsClientListBySubscriptionResponse]{
More: func(page CapacityReservationGroupsClientListBySubscriptionResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *CapacityReservationGroupsClientListBySubscriptionResponse) (CapacityReservationGroupsClientListBySubscriptionResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CapacityReservationGroupsClient.NewListBySubscriptionPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listBySubscriptionCreateRequest(ctx, options)
}, nil)
if err != nil {
return CapacityReservationGroupsClientListBySubscriptionResponse{}, err
}
return client.listBySubscriptionHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listBySubscriptionCreateRequest creates the ListBySubscription request.
func (client *CapacityReservationGroupsClient) listBySubscriptionCreateRequest(ctx context.Context, options *CapacityReservationGroupsClientListBySubscriptionOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/capacityReservationGroups"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
if options != nil && options.Expand != nil {
reqQP.Set("$expand", string(*options.Expand))
}
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listBySubscriptionHandleResponse handles the ListBySubscription response.
func (client *CapacityReservationGroupsClient) listBySubscriptionHandleResponse(resp *http.Response) (CapacityReservationGroupsClientListBySubscriptionResponse, error) {
result := CapacityReservationGroupsClientListBySubscriptionResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservationGroupListResult); err != nil {
return CapacityReservationGroupsClientListBySubscriptionResponse{}, err
}
return result, nil
}
// Update - The operation to update a capacity reservation group. When updating a capacity reservation group, only tags may
// be modified.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - capacityReservationGroupName - The name of the capacity reservation group.
// - parameters - Parameters supplied to the Update capacity reservation Group operation.
// - options - CapacityReservationGroupsClientUpdateOptions contains the optional parameters for the CapacityReservationGroupsClient.Update
// method.
func (client *CapacityReservationGroupsClient) Update(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, parameters CapacityReservationGroupUpdate, options *CapacityReservationGroupsClientUpdateOptions) (CapacityReservationGroupsClientUpdateResponse, error) {
var err error
const operationName = "CapacityReservationGroupsClient.Update"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, capacityReservationGroupName, parameters, options)
if err != nil {
return CapacityReservationGroupsClientUpdateResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CapacityReservationGroupsClientUpdateResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return CapacityReservationGroupsClientUpdateResponse{}, err
}
resp, err := client.updateHandleResponse(httpResp)
return resp, err
}
// updateCreateRequest creates the Update request.
func (client *CapacityReservationGroupsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, parameters CapacityReservationGroupUpdate, options *CapacityReservationGroupsClientUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if capacityReservationGroupName == "" {
return nil, errors.New("parameter capacityReservationGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// updateHandleResponse handles the Update response.
func (client *CapacityReservationGroupsClient) updateHandleResponse(resp *http.Response) (CapacityReservationGroupsClientUpdateResponse, error) {
result := CapacityReservationGroupsClientUpdateResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservationGroup); err != nil {
return CapacityReservationGroupsClientUpdateResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,443 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// CapacityReservationsClient contains the methods for the CapacityReservations group.
// Don't use this type directly, use NewCapacityReservationsClient() instead.
type CapacityReservationsClient struct {
internal *arm.Client
subscriptionID string
}
// NewCapacityReservationsClient creates a new instance of CapacityReservationsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewCapacityReservationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CapacityReservationsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &CapacityReservationsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreateOrUpdate - The operation to create or update a capacity reservation. Please note some properties can be set
// only during capacity reservation creation. Please refer to https://aka.ms/CapacityReservation for more
// details.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - capacityReservationGroupName - The name of the capacity reservation group.
// - capacityReservationName - The name of the capacity reservation.
// - parameters - Parameters supplied to the Create capacity reservation.
// - options - CapacityReservationsClientBeginCreateOrUpdateOptions contains the optional parameters for the CapacityReservationsClient.BeginCreateOrUpdate
// method.
func (client *CapacityReservationsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservation, options *CapacityReservationsClientBeginCreateOrUpdateOptions) (*runtime.Poller[CapacityReservationsClientCreateOrUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.createOrUpdate(ctx, resourceGroupName, capacityReservationGroupName, capacityReservationName, parameters, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CapacityReservationsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CapacityReservationsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// CreateOrUpdate - The operation to create or update a capacity reservation. Please note some properties can be set only
// during capacity reservation creation. Please refer to https://aka.ms/CapacityReservation for more
// details.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *CapacityReservationsClient) createOrUpdate(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservation, options *CapacityReservationsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
var err error
const operationName = "CapacityReservationsClient.BeginCreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, capacityReservationGroupName, capacityReservationName, parameters, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *CapacityReservationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservation, options *CapacityReservationsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations/{capacityReservationName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if capacityReservationGroupName == "" {
return nil, errors.New("parameter capacityReservationGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName))
if capacityReservationName == "" {
return nil, errors.New("parameter capacityReservationName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{capacityReservationName}", url.PathEscape(capacityReservationName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - The operation to delete a capacity reservation. This operation is allowed only when all the associated resources
// are disassociated from the capacity reservation. Please refer to
// https://aka.ms/CapacityReservation for more details.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - capacityReservationGroupName - The name of the capacity reservation group.
// - capacityReservationName - The name of the capacity reservation.
// - options - CapacityReservationsClientBeginDeleteOptions contains the optional parameters for the CapacityReservationsClient.BeginDelete
// method.
func (client *CapacityReservationsClient) BeginDelete(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, options *CapacityReservationsClientBeginDeleteOptions) (*runtime.Poller[CapacityReservationsClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, capacityReservationGroupName, capacityReservationName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CapacityReservationsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CapacityReservationsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - The operation to delete a capacity reservation. This operation is allowed only when all the associated resources
// are disassociated from the capacity reservation. Please refer to
// https://aka.ms/CapacityReservation for more details.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *CapacityReservationsClient) deleteOperation(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, options *CapacityReservationsClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "CapacityReservationsClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, capacityReservationGroupName, capacityReservationName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *CapacityReservationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, options *CapacityReservationsClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations/{capacityReservationName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if capacityReservationGroupName == "" {
return nil, errors.New("parameter capacityReservationGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName))
if capacityReservationName == "" {
return nil, errors.New("parameter capacityReservationName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{capacityReservationName}", url.PathEscape(capacityReservationName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - The operation that retrieves information about the capacity reservation.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - capacityReservationGroupName - The name of the capacity reservation group.
// - capacityReservationName - The name of the capacity reservation.
// - options - CapacityReservationsClientGetOptions contains the optional parameters for the CapacityReservationsClient.Get
// method.
func (client *CapacityReservationsClient) Get(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, options *CapacityReservationsClientGetOptions) (CapacityReservationsClientGetResponse, error) {
var err error
const operationName = "CapacityReservationsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, capacityReservationGroupName, capacityReservationName, options)
if err != nil {
return CapacityReservationsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CapacityReservationsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return CapacityReservationsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *CapacityReservationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, options *CapacityReservationsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations/{capacityReservationName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if capacityReservationGroupName == "" {
return nil, errors.New("parameter capacityReservationGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName))
if capacityReservationName == "" {
return nil, errors.New("parameter capacityReservationName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{capacityReservationName}", url.PathEscape(capacityReservationName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
if options != nil && options.Expand != nil {
reqQP.Set("$expand", string(*options.Expand))
}
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *CapacityReservationsClient) getHandleResponse(resp *http.Response) (CapacityReservationsClientGetResponse, error) {
result := CapacityReservationsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservation); err != nil {
return CapacityReservationsClientGetResponse{}, err
}
return result, nil
}
// NewListByCapacityReservationGroupPager - Lists all of the capacity reservations in the specified capacity reservation group.
// Use the nextLink property in the response to get the next page of capacity reservations.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - capacityReservationGroupName - The name of the capacity reservation group.
// - options - CapacityReservationsClientListByCapacityReservationGroupOptions contains the optional parameters for the CapacityReservationsClient.NewListByCapacityReservationGroupPager
// method.
func (client *CapacityReservationsClient) NewListByCapacityReservationGroupPager(resourceGroupName string, capacityReservationGroupName string, options *CapacityReservationsClientListByCapacityReservationGroupOptions) *runtime.Pager[CapacityReservationsClientListByCapacityReservationGroupResponse] {
return runtime.NewPager(runtime.PagingHandler[CapacityReservationsClientListByCapacityReservationGroupResponse]{
More: func(page CapacityReservationsClientListByCapacityReservationGroupResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *CapacityReservationsClientListByCapacityReservationGroupResponse) (CapacityReservationsClientListByCapacityReservationGroupResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CapacityReservationsClient.NewListByCapacityReservationGroupPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByCapacityReservationGroupCreateRequest(ctx, resourceGroupName, capacityReservationGroupName, options)
}, nil)
if err != nil {
return CapacityReservationsClientListByCapacityReservationGroupResponse{}, err
}
return client.listByCapacityReservationGroupHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByCapacityReservationGroupCreateRequest creates the ListByCapacityReservationGroup request.
func (client *CapacityReservationsClient) listByCapacityReservationGroupCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, options *CapacityReservationsClientListByCapacityReservationGroupOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if capacityReservationGroupName == "" {
return nil, errors.New("parameter capacityReservationGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByCapacityReservationGroupHandleResponse handles the ListByCapacityReservationGroup response.
func (client *CapacityReservationsClient) listByCapacityReservationGroupHandleResponse(resp *http.Response) (CapacityReservationsClientListByCapacityReservationGroupResponse, error) {
result := CapacityReservationsClientListByCapacityReservationGroupResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservationListResult); err != nil {
return CapacityReservationsClientListByCapacityReservationGroupResponse{}, err
}
return result, nil
}
// BeginUpdate - The operation to update a capacity reservation.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - capacityReservationGroupName - The name of the capacity reservation group.
// - capacityReservationName - The name of the capacity reservation.
// - parameters - Parameters supplied to the Update capacity reservation operation.
// - options - CapacityReservationsClientBeginUpdateOptions contains the optional parameters for the CapacityReservationsClient.BeginUpdate
// method.
func (client *CapacityReservationsClient) BeginUpdate(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservationUpdate, options *CapacityReservationsClientBeginUpdateOptions) (*runtime.Poller[CapacityReservationsClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, capacityReservationGroupName, capacityReservationName, parameters, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CapacityReservationsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CapacityReservationsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - The operation to update a capacity reservation.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *CapacityReservationsClient) update(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservationUpdate, options *CapacityReservationsClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "CapacityReservationsClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, capacityReservationGroupName, capacityReservationName, parameters, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *CapacityReservationsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservationUpdate, options *CapacityReservationsClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations/{capacityReservationName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if capacityReservationGroupName == "" {
return nil, errors.New("parameter capacityReservationGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName))
if capacityReservationName == "" {
return nil, errors.New("parameter capacityReservationName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{capacityReservationName}", url.PathEscape(capacityReservationName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,28 @@
# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file.
trigger:
branches:
include:
- main
- feature/*
- hotfix/*
- release/*
paths:
include:
- sdk/resourcemanager/compute/armcompute/
pr:
branches:
include:
- main
- feature/*
- hotfix/*
- release/*
paths:
include:
- sdk/resourcemanager/compute/armcompute/
stages:
- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml
parameters:
IncludeRelease: true
ServiceDirectory: 'resourcemanager/compute/armcompute'

View file

@ -0,0 +1,333 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
)
// ClientFactory is a client factory used to create any client in this module.
// Don't use this type directly, use NewClientFactory instead.
type ClientFactory struct {
subscriptionID string
credential azcore.TokenCredential
options *arm.ClientOptions
}
// NewClientFactory creates a new instance of ClientFactory with the specified values.
// The parameter values will be propagated to any client created from this factory.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) {
_, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
return &ClientFactory{
subscriptionID: subscriptionID, credential: credential,
options: options.Clone(),
}, nil
}
// NewAvailabilitySetsClient creates a new instance of AvailabilitySetsClient.
func (c *ClientFactory) NewAvailabilitySetsClient() *AvailabilitySetsClient {
subClient, _ := NewAvailabilitySetsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewCapacityReservationGroupsClient creates a new instance of CapacityReservationGroupsClient.
func (c *ClientFactory) NewCapacityReservationGroupsClient() *CapacityReservationGroupsClient {
subClient, _ := NewCapacityReservationGroupsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewCapacityReservationsClient creates a new instance of CapacityReservationsClient.
func (c *ClientFactory) NewCapacityReservationsClient() *CapacityReservationsClient {
subClient, _ := NewCapacityReservationsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewCloudServiceOperatingSystemsClient creates a new instance of CloudServiceOperatingSystemsClient.
func (c *ClientFactory) NewCloudServiceOperatingSystemsClient() *CloudServiceOperatingSystemsClient {
subClient, _ := NewCloudServiceOperatingSystemsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewCloudServiceRoleInstancesClient creates a new instance of CloudServiceRoleInstancesClient.
func (c *ClientFactory) NewCloudServiceRoleInstancesClient() *CloudServiceRoleInstancesClient {
subClient, _ := NewCloudServiceRoleInstancesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewCloudServiceRolesClient creates a new instance of CloudServiceRolesClient.
func (c *ClientFactory) NewCloudServiceRolesClient() *CloudServiceRolesClient {
subClient, _ := NewCloudServiceRolesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewCloudServicesClient creates a new instance of CloudServicesClient.
func (c *ClientFactory) NewCloudServicesClient() *CloudServicesClient {
subClient, _ := NewCloudServicesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewCloudServicesUpdateDomainClient creates a new instance of CloudServicesUpdateDomainClient.
func (c *ClientFactory) NewCloudServicesUpdateDomainClient() *CloudServicesUpdateDomainClient {
subClient, _ := NewCloudServicesUpdateDomainClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewCommunityGalleriesClient creates a new instance of CommunityGalleriesClient.
func (c *ClientFactory) NewCommunityGalleriesClient() *CommunityGalleriesClient {
subClient, _ := NewCommunityGalleriesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewCommunityGalleryImageVersionsClient creates a new instance of CommunityGalleryImageVersionsClient.
func (c *ClientFactory) NewCommunityGalleryImageVersionsClient() *CommunityGalleryImageVersionsClient {
subClient, _ := NewCommunityGalleryImageVersionsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewCommunityGalleryImagesClient creates a new instance of CommunityGalleryImagesClient.
func (c *ClientFactory) NewCommunityGalleryImagesClient() *CommunityGalleryImagesClient {
subClient, _ := NewCommunityGalleryImagesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewDedicatedHostGroupsClient creates a new instance of DedicatedHostGroupsClient.
func (c *ClientFactory) NewDedicatedHostGroupsClient() *DedicatedHostGroupsClient {
subClient, _ := NewDedicatedHostGroupsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewDedicatedHostsClient creates a new instance of DedicatedHostsClient.
func (c *ClientFactory) NewDedicatedHostsClient() *DedicatedHostsClient {
subClient, _ := NewDedicatedHostsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewDiskAccessesClient creates a new instance of DiskAccessesClient.
func (c *ClientFactory) NewDiskAccessesClient() *DiskAccessesClient {
subClient, _ := NewDiskAccessesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewDiskEncryptionSetsClient creates a new instance of DiskEncryptionSetsClient.
func (c *ClientFactory) NewDiskEncryptionSetsClient() *DiskEncryptionSetsClient {
subClient, _ := NewDiskEncryptionSetsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewDiskRestorePointClient creates a new instance of DiskRestorePointClient.
func (c *ClientFactory) NewDiskRestorePointClient() *DiskRestorePointClient {
subClient, _ := NewDiskRestorePointClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewDisksClient creates a new instance of DisksClient.
func (c *ClientFactory) NewDisksClient() *DisksClient {
subClient, _ := NewDisksClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewGalleriesClient creates a new instance of GalleriesClient.
func (c *ClientFactory) NewGalleriesClient() *GalleriesClient {
subClient, _ := NewGalleriesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewGalleryApplicationVersionsClient creates a new instance of GalleryApplicationVersionsClient.
func (c *ClientFactory) NewGalleryApplicationVersionsClient() *GalleryApplicationVersionsClient {
subClient, _ := NewGalleryApplicationVersionsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewGalleryApplicationsClient creates a new instance of GalleryApplicationsClient.
func (c *ClientFactory) NewGalleryApplicationsClient() *GalleryApplicationsClient {
subClient, _ := NewGalleryApplicationsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewGalleryImageVersionsClient creates a new instance of GalleryImageVersionsClient.
func (c *ClientFactory) NewGalleryImageVersionsClient() *GalleryImageVersionsClient {
subClient, _ := NewGalleryImageVersionsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewGalleryImagesClient creates a new instance of GalleryImagesClient.
func (c *ClientFactory) NewGalleryImagesClient() *GalleryImagesClient {
subClient, _ := NewGalleryImagesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewGallerySharingProfileClient creates a new instance of GallerySharingProfileClient.
func (c *ClientFactory) NewGallerySharingProfileClient() *GallerySharingProfileClient {
subClient, _ := NewGallerySharingProfileClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewImagesClient creates a new instance of ImagesClient.
func (c *ClientFactory) NewImagesClient() *ImagesClient {
subClient, _ := NewImagesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewLogAnalyticsClient creates a new instance of LogAnalyticsClient.
func (c *ClientFactory) NewLogAnalyticsClient() *LogAnalyticsClient {
subClient, _ := NewLogAnalyticsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewOperationsClient creates a new instance of OperationsClient.
func (c *ClientFactory) NewOperationsClient() *OperationsClient {
subClient, _ := NewOperationsClient(c.credential, c.options)
return subClient
}
// NewProximityPlacementGroupsClient creates a new instance of ProximityPlacementGroupsClient.
func (c *ClientFactory) NewProximityPlacementGroupsClient() *ProximityPlacementGroupsClient {
subClient, _ := NewProximityPlacementGroupsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewResourceSKUsClient creates a new instance of ResourceSKUsClient.
func (c *ClientFactory) NewResourceSKUsClient() *ResourceSKUsClient {
subClient, _ := NewResourceSKUsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewRestorePointCollectionsClient creates a new instance of RestorePointCollectionsClient.
func (c *ClientFactory) NewRestorePointCollectionsClient() *RestorePointCollectionsClient {
subClient, _ := NewRestorePointCollectionsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewRestorePointsClient creates a new instance of RestorePointsClient.
func (c *ClientFactory) NewRestorePointsClient() *RestorePointsClient {
subClient, _ := NewRestorePointsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewSSHPublicKeysClient creates a new instance of SSHPublicKeysClient.
func (c *ClientFactory) NewSSHPublicKeysClient() *SSHPublicKeysClient {
subClient, _ := NewSSHPublicKeysClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewSharedGalleriesClient creates a new instance of SharedGalleriesClient.
func (c *ClientFactory) NewSharedGalleriesClient() *SharedGalleriesClient {
subClient, _ := NewSharedGalleriesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewSharedGalleryImageVersionsClient creates a new instance of SharedGalleryImageVersionsClient.
func (c *ClientFactory) NewSharedGalleryImageVersionsClient() *SharedGalleryImageVersionsClient {
subClient, _ := NewSharedGalleryImageVersionsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewSharedGalleryImagesClient creates a new instance of SharedGalleryImagesClient.
func (c *ClientFactory) NewSharedGalleryImagesClient() *SharedGalleryImagesClient {
subClient, _ := NewSharedGalleryImagesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewSnapshotsClient creates a new instance of SnapshotsClient.
func (c *ClientFactory) NewSnapshotsClient() *SnapshotsClient {
subClient, _ := NewSnapshotsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewUsageClient creates a new instance of UsageClient.
func (c *ClientFactory) NewUsageClient() *UsageClient {
subClient, _ := NewUsageClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewVirtualMachineExtensionImagesClient creates a new instance of VirtualMachineExtensionImagesClient.
func (c *ClientFactory) NewVirtualMachineExtensionImagesClient() *VirtualMachineExtensionImagesClient {
subClient, _ := NewVirtualMachineExtensionImagesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewVirtualMachineExtensionsClient creates a new instance of VirtualMachineExtensionsClient.
func (c *ClientFactory) NewVirtualMachineExtensionsClient() *VirtualMachineExtensionsClient {
subClient, _ := NewVirtualMachineExtensionsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewVirtualMachineImagesClient creates a new instance of VirtualMachineImagesClient.
func (c *ClientFactory) NewVirtualMachineImagesClient() *VirtualMachineImagesClient {
subClient, _ := NewVirtualMachineImagesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewVirtualMachineImagesEdgeZoneClient creates a new instance of VirtualMachineImagesEdgeZoneClient.
func (c *ClientFactory) NewVirtualMachineImagesEdgeZoneClient() *VirtualMachineImagesEdgeZoneClient {
subClient, _ := NewVirtualMachineImagesEdgeZoneClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewVirtualMachineRunCommandsClient creates a new instance of VirtualMachineRunCommandsClient.
func (c *ClientFactory) NewVirtualMachineRunCommandsClient() *VirtualMachineRunCommandsClient {
subClient, _ := NewVirtualMachineRunCommandsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewVirtualMachineScaleSetExtensionsClient creates a new instance of VirtualMachineScaleSetExtensionsClient.
func (c *ClientFactory) NewVirtualMachineScaleSetExtensionsClient() *VirtualMachineScaleSetExtensionsClient {
subClient, _ := NewVirtualMachineScaleSetExtensionsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewVirtualMachineScaleSetRollingUpgradesClient creates a new instance of VirtualMachineScaleSetRollingUpgradesClient.
func (c *ClientFactory) NewVirtualMachineScaleSetRollingUpgradesClient() *VirtualMachineScaleSetRollingUpgradesClient {
subClient, _ := NewVirtualMachineScaleSetRollingUpgradesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewVirtualMachineScaleSetVMExtensionsClient creates a new instance of VirtualMachineScaleSetVMExtensionsClient.
func (c *ClientFactory) NewVirtualMachineScaleSetVMExtensionsClient() *VirtualMachineScaleSetVMExtensionsClient {
subClient, _ := NewVirtualMachineScaleSetVMExtensionsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewVirtualMachineScaleSetVMRunCommandsClient creates a new instance of VirtualMachineScaleSetVMRunCommandsClient.
func (c *ClientFactory) NewVirtualMachineScaleSetVMRunCommandsClient() *VirtualMachineScaleSetVMRunCommandsClient {
subClient, _ := NewVirtualMachineScaleSetVMRunCommandsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewVirtualMachineScaleSetVMsClient creates a new instance of VirtualMachineScaleSetVMsClient.
func (c *ClientFactory) NewVirtualMachineScaleSetVMsClient() *VirtualMachineScaleSetVMsClient {
subClient, _ := NewVirtualMachineScaleSetVMsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewVirtualMachineScaleSetsClient creates a new instance of VirtualMachineScaleSetsClient.
func (c *ClientFactory) NewVirtualMachineScaleSetsClient() *VirtualMachineScaleSetsClient {
subClient, _ := NewVirtualMachineScaleSetsClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewVirtualMachineSizesClient creates a new instance of VirtualMachineSizesClient.
func (c *ClientFactory) NewVirtualMachineSizesClient() *VirtualMachineSizesClient {
subClient, _ := NewVirtualMachineSizesClient(c.subscriptionID, c.credential, c.options)
return subClient
}
// NewVirtualMachinesClient creates a new instance of VirtualMachinesClient.
func (c *ClientFactory) NewVirtualMachinesClient() *VirtualMachinesClient {
subClient, _ := NewVirtualMachinesClient(c.subscriptionID, c.credential, c.options)
return subClient
}

View file

@ -0,0 +1,301 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// CloudServiceOperatingSystemsClient contains the methods for the CloudServiceOperatingSystems group.
// Don't use this type directly, use NewCloudServiceOperatingSystemsClient() instead.
type CloudServiceOperatingSystemsClient struct {
internal *arm.Client
subscriptionID string
}
// NewCloudServiceOperatingSystemsClient creates a new instance of CloudServiceOperatingSystemsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewCloudServiceOperatingSystemsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudServiceOperatingSystemsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &CloudServiceOperatingSystemsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// GetOSFamily - Gets properties of a guest operating system family that can be specified in the XML service configuration
// (.cscfg) for a cloud service.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
// - location - Name of the location that the OS family pertains to.
// - osFamilyName - Name of the OS family.
// - options - CloudServiceOperatingSystemsClientGetOSFamilyOptions contains the optional parameters for the CloudServiceOperatingSystemsClient.GetOSFamily
// method.
func (client *CloudServiceOperatingSystemsClient) GetOSFamily(ctx context.Context, location string, osFamilyName string, options *CloudServiceOperatingSystemsClientGetOSFamilyOptions) (CloudServiceOperatingSystemsClientGetOSFamilyResponse, error) {
var err error
const operationName = "CloudServiceOperatingSystemsClient.GetOSFamily"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getOSFamilyCreateRequest(ctx, location, osFamilyName, options)
if err != nil {
return CloudServiceOperatingSystemsClientGetOSFamilyResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CloudServiceOperatingSystemsClientGetOSFamilyResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return CloudServiceOperatingSystemsClientGetOSFamilyResponse{}, err
}
resp, err := client.getOSFamilyHandleResponse(httpResp)
return resp, err
}
// getOSFamilyCreateRequest creates the GetOSFamily request.
func (client *CloudServiceOperatingSystemsClient) getOSFamilyCreateRequest(ctx context.Context, location string, osFamilyName string, options *CloudServiceOperatingSystemsClientGetOSFamilyOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/cloudServiceOsFamilies/{osFamilyName}"
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if osFamilyName == "" {
return nil, errors.New("parameter osFamilyName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{osFamilyName}", url.PathEscape(osFamilyName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getOSFamilyHandleResponse handles the GetOSFamily response.
func (client *CloudServiceOperatingSystemsClient) getOSFamilyHandleResponse(resp *http.Response) (CloudServiceOperatingSystemsClientGetOSFamilyResponse, error) {
result := CloudServiceOperatingSystemsClientGetOSFamilyResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.OSFamily); err != nil {
return CloudServiceOperatingSystemsClientGetOSFamilyResponse{}, err
}
return result, nil
}
// GetOSVersion - Gets properties of a guest operating system version that can be specified in the XML service configuration
// (.cscfg) for a cloud service.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
// - location - Name of the location that the OS version pertains to.
// - osVersionName - Name of the OS version.
// - options - CloudServiceOperatingSystemsClientGetOSVersionOptions contains the optional parameters for the CloudServiceOperatingSystemsClient.GetOSVersion
// method.
func (client *CloudServiceOperatingSystemsClient) GetOSVersion(ctx context.Context, location string, osVersionName string, options *CloudServiceOperatingSystemsClientGetOSVersionOptions) (CloudServiceOperatingSystemsClientGetOSVersionResponse, error) {
var err error
const operationName = "CloudServiceOperatingSystemsClient.GetOSVersion"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getOSVersionCreateRequest(ctx, location, osVersionName, options)
if err != nil {
return CloudServiceOperatingSystemsClientGetOSVersionResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CloudServiceOperatingSystemsClientGetOSVersionResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return CloudServiceOperatingSystemsClientGetOSVersionResponse{}, err
}
resp, err := client.getOSVersionHandleResponse(httpResp)
return resp, err
}
// getOSVersionCreateRequest creates the GetOSVersion request.
func (client *CloudServiceOperatingSystemsClient) getOSVersionCreateRequest(ctx context.Context, location string, osVersionName string, options *CloudServiceOperatingSystemsClientGetOSVersionOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/cloudServiceOsVersions/{osVersionName}"
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if osVersionName == "" {
return nil, errors.New("parameter osVersionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{osVersionName}", url.PathEscape(osVersionName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getOSVersionHandleResponse handles the GetOSVersion response.
func (client *CloudServiceOperatingSystemsClient) getOSVersionHandleResponse(resp *http.Response) (CloudServiceOperatingSystemsClientGetOSVersionResponse, error) {
result := CloudServiceOperatingSystemsClientGetOSVersionResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.OSVersion); err != nil {
return CloudServiceOperatingSystemsClientGetOSVersionResponse{}, err
}
return result, nil
}
// NewListOSFamiliesPager - Gets a list of all guest operating system families available to be specified in the XML service
// configuration (.cscfg) for a cloud service. Use nextLink property in the response to get the next page
// of OS Families. Do this till nextLink is null to fetch all the OS Families.
//
// Generated from API version 2022-09-04
// - location - Name of the location that the OS families pertain to.
// - options - CloudServiceOperatingSystemsClientListOSFamiliesOptions contains the optional parameters for the CloudServiceOperatingSystemsClient.NewListOSFamiliesPager
// method.
func (client *CloudServiceOperatingSystemsClient) NewListOSFamiliesPager(location string, options *CloudServiceOperatingSystemsClientListOSFamiliesOptions) *runtime.Pager[CloudServiceOperatingSystemsClientListOSFamiliesResponse] {
return runtime.NewPager(runtime.PagingHandler[CloudServiceOperatingSystemsClientListOSFamiliesResponse]{
More: func(page CloudServiceOperatingSystemsClientListOSFamiliesResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *CloudServiceOperatingSystemsClientListOSFamiliesResponse) (CloudServiceOperatingSystemsClientListOSFamiliesResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudServiceOperatingSystemsClient.NewListOSFamiliesPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listOSFamiliesCreateRequest(ctx, location, options)
}, nil)
if err != nil {
return CloudServiceOperatingSystemsClientListOSFamiliesResponse{}, err
}
return client.listOSFamiliesHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listOSFamiliesCreateRequest creates the ListOSFamilies request.
func (client *CloudServiceOperatingSystemsClient) listOSFamiliesCreateRequest(ctx context.Context, location string, options *CloudServiceOperatingSystemsClientListOSFamiliesOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/cloudServiceOsFamilies"
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listOSFamiliesHandleResponse handles the ListOSFamilies response.
func (client *CloudServiceOperatingSystemsClient) listOSFamiliesHandleResponse(resp *http.Response) (CloudServiceOperatingSystemsClientListOSFamiliesResponse, error) {
result := CloudServiceOperatingSystemsClientListOSFamiliesResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.OSFamilyListResult); err != nil {
return CloudServiceOperatingSystemsClientListOSFamiliesResponse{}, err
}
return result, nil
}
// NewListOSVersionsPager - Gets a list of all guest operating system versions available to be specified in the XML service
// configuration (.cscfg) for a cloud service. Use nextLink property in the response to get the next page
// of OS versions. Do this till nextLink is null to fetch all the OS versions.
//
// Generated from API version 2022-09-04
// - location - Name of the location that the OS versions pertain to.
// - options - CloudServiceOperatingSystemsClientListOSVersionsOptions contains the optional parameters for the CloudServiceOperatingSystemsClient.NewListOSVersionsPager
// method.
func (client *CloudServiceOperatingSystemsClient) NewListOSVersionsPager(location string, options *CloudServiceOperatingSystemsClientListOSVersionsOptions) *runtime.Pager[CloudServiceOperatingSystemsClientListOSVersionsResponse] {
return runtime.NewPager(runtime.PagingHandler[CloudServiceOperatingSystemsClientListOSVersionsResponse]{
More: func(page CloudServiceOperatingSystemsClientListOSVersionsResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *CloudServiceOperatingSystemsClientListOSVersionsResponse) (CloudServiceOperatingSystemsClientListOSVersionsResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudServiceOperatingSystemsClient.NewListOSVersionsPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listOSVersionsCreateRequest(ctx, location, options)
}, nil)
if err != nil {
return CloudServiceOperatingSystemsClientListOSVersionsResponse{}, err
}
return client.listOSVersionsHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listOSVersionsCreateRequest creates the ListOSVersions request.
func (client *CloudServiceOperatingSystemsClient) listOSVersionsCreateRequest(ctx context.Context, location string, options *CloudServiceOperatingSystemsClientListOSVersionsOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/cloudServiceOsVersions"
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listOSVersionsHandleResponse handles the ListOSVersions response.
func (client *CloudServiceOperatingSystemsClient) listOSVersionsHandleResponse(resp *http.Response) (CloudServiceOperatingSystemsClientListOSVersionsResponse, error) {
result := CloudServiceOperatingSystemsClientListOSVersionsResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.OSVersionListResult); err != nil {
return CloudServiceOperatingSystemsClientListOSVersionsResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,648 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// CloudServiceRoleInstancesClient contains the methods for the CloudServiceRoleInstances group.
// Don't use this type directly, use NewCloudServiceRoleInstancesClient() instead.
type CloudServiceRoleInstancesClient struct {
internal *arm.Client
subscriptionID string
}
// NewCloudServiceRoleInstancesClient creates a new instance of CloudServiceRoleInstancesClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewCloudServiceRoleInstancesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudServiceRoleInstancesClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &CloudServiceRoleInstancesClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginDelete - Deletes a role instance from a cloud service.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
// - roleInstanceName - Name of the role instance.
// - resourceGroupName - Name of the resource group.
// - cloudServiceName - Name of the cloud service.
// - options - CloudServiceRoleInstancesClientBeginDeleteOptions contains the optional parameters for the CloudServiceRoleInstancesClient.BeginDelete
// method.
func (client *CloudServiceRoleInstancesClient) BeginDelete(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginDeleteOptions) (*runtime.Poller[CloudServiceRoleInstancesClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServiceRoleInstancesClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServiceRoleInstancesClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - Deletes a role instance from a cloud service.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
func (client *CloudServiceRoleInstancesClient) deleteOperation(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "CloudServiceRoleInstancesClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *CloudServiceRoleInstancesClient) deleteCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}"
if roleInstanceName == "" {
return nil, errors.New("parameter roleInstanceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if cloudServiceName == "" {
return nil, errors.New("parameter cloudServiceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - Gets a role instance from a cloud service.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
// - roleInstanceName - Name of the role instance.
// - resourceGroupName - Name of the resource group.
// - cloudServiceName - Name of the cloud service.
// - options - CloudServiceRoleInstancesClientGetOptions contains the optional parameters for the CloudServiceRoleInstancesClient.Get
// method.
func (client *CloudServiceRoleInstancesClient) Get(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientGetOptions) (CloudServiceRoleInstancesClientGetResponse, error) {
var err error
const operationName = "CloudServiceRoleInstancesClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options)
if err != nil {
return CloudServiceRoleInstancesClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CloudServiceRoleInstancesClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return CloudServiceRoleInstancesClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *CloudServiceRoleInstancesClient) getCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}"
if roleInstanceName == "" {
return nil, errors.New("parameter roleInstanceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if cloudServiceName == "" {
return nil, errors.New("parameter cloudServiceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
if options != nil && options.Expand != nil {
reqQP.Set("$expand", string(*options.Expand))
}
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *CloudServiceRoleInstancesClient) getHandleResponse(resp *http.Response) (CloudServiceRoleInstancesClientGetResponse, error) {
result := CloudServiceRoleInstancesClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.RoleInstance); err != nil {
return CloudServiceRoleInstancesClientGetResponse{}, err
}
return result, nil
}
// GetInstanceView - Retrieves information about the run-time state of a role instance in a cloud service.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
// - roleInstanceName - Name of the role instance.
// - resourceGroupName - Name of the resource group.
// - cloudServiceName - Name of the cloud service.
// - options - CloudServiceRoleInstancesClientGetInstanceViewOptions contains the optional parameters for the CloudServiceRoleInstancesClient.GetInstanceView
// method.
func (client *CloudServiceRoleInstancesClient) GetInstanceView(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientGetInstanceViewOptions) (CloudServiceRoleInstancesClientGetInstanceViewResponse, error) {
var err error
const operationName = "CloudServiceRoleInstancesClient.GetInstanceView"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getInstanceViewCreateRequest(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options)
if err != nil {
return CloudServiceRoleInstancesClientGetInstanceViewResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CloudServiceRoleInstancesClientGetInstanceViewResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return CloudServiceRoleInstancesClientGetInstanceViewResponse{}, err
}
resp, err := client.getInstanceViewHandleResponse(httpResp)
return resp, err
}
// getInstanceViewCreateRequest creates the GetInstanceView request.
func (client *CloudServiceRoleInstancesClient) getInstanceViewCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientGetInstanceViewOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/instanceView"
if roleInstanceName == "" {
return nil, errors.New("parameter roleInstanceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if cloudServiceName == "" {
return nil, errors.New("parameter cloudServiceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getInstanceViewHandleResponse handles the GetInstanceView response.
func (client *CloudServiceRoleInstancesClient) getInstanceViewHandleResponse(resp *http.Response) (CloudServiceRoleInstancesClientGetInstanceViewResponse, error) {
result := CloudServiceRoleInstancesClientGetInstanceViewResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.RoleInstanceView); err != nil {
return CloudServiceRoleInstancesClientGetInstanceViewResponse{}, err
}
return result, nil
}
// GetRemoteDesktopFile - Gets a remote desktop file for a role instance in a cloud service.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
// - roleInstanceName - Name of the role instance.
// - resourceGroupName - Name of the resource group.
// - cloudServiceName - Name of the cloud service.
// - options - CloudServiceRoleInstancesClientGetRemoteDesktopFileOptions contains the optional parameters for the CloudServiceRoleInstancesClient.GetRemoteDesktopFile
// method.
func (client *CloudServiceRoleInstancesClient) GetRemoteDesktopFile(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientGetRemoteDesktopFileOptions) (CloudServiceRoleInstancesClientGetRemoteDesktopFileResponse, error) {
var err error
const operationName = "CloudServiceRoleInstancesClient.GetRemoteDesktopFile"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getRemoteDesktopFileCreateRequest(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options)
if err != nil {
return CloudServiceRoleInstancesClientGetRemoteDesktopFileResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CloudServiceRoleInstancesClientGetRemoteDesktopFileResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return CloudServiceRoleInstancesClientGetRemoteDesktopFileResponse{}, err
}
return CloudServiceRoleInstancesClientGetRemoteDesktopFileResponse{Body: httpResp.Body}, nil
}
// getRemoteDesktopFileCreateRequest creates the GetRemoteDesktopFile request.
func (client *CloudServiceRoleInstancesClient) getRemoteDesktopFileCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientGetRemoteDesktopFileOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/remoteDesktopFile"
if roleInstanceName == "" {
return nil, errors.New("parameter roleInstanceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if cloudServiceName == "" {
return nil, errors.New("parameter cloudServiceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
runtime.SkipBodyDownload(req)
req.Raw().Header["Accept"] = []string{"application/x-rdp"}
return req, nil
}
// NewListPager - Gets the list of all role instances in a cloud service. Use nextLink property in the response to get the
// next page of role instances. Do this till nextLink is null to fetch all the role instances.
//
// Generated from API version 2022-09-04
// - resourceGroupName - Name of the resource group.
// - cloudServiceName - Name of the cloud service.
// - options - CloudServiceRoleInstancesClientListOptions contains the optional parameters for the CloudServiceRoleInstancesClient.NewListPager
// method.
func (client *CloudServiceRoleInstancesClient) NewListPager(resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientListOptions) *runtime.Pager[CloudServiceRoleInstancesClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[CloudServiceRoleInstancesClientListResponse]{
More: func(page CloudServiceRoleInstancesClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *CloudServiceRoleInstancesClientListResponse) (CloudServiceRoleInstancesClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudServiceRoleInstancesClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, resourceGroupName, cloudServiceName, options)
}, nil)
if err != nil {
return CloudServiceRoleInstancesClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *CloudServiceRoleInstancesClient) listCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if cloudServiceName == "" {
return nil, errors.New("parameter cloudServiceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
if options != nil && options.Expand != nil {
reqQP.Set("$expand", string(*options.Expand))
}
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *CloudServiceRoleInstancesClient) listHandleResponse(resp *http.Response) (CloudServiceRoleInstancesClientListResponse, error) {
result := CloudServiceRoleInstancesClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.RoleInstanceListResult); err != nil {
return CloudServiceRoleInstancesClientListResponse{}, err
}
return result, nil
}
// BeginRebuild - The Rebuild Role Instance asynchronous operation reinstalls the operating system on instances of web roles
// or worker roles and initializes the storage resources that are used by them. If you do not
// want to initialize storage resources, you can use Reimage Role Instance.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
// - roleInstanceName - Name of the role instance.
// - resourceGroupName - Name of the resource group.
// - cloudServiceName - Name of the cloud service.
// - options - CloudServiceRoleInstancesClientBeginRebuildOptions contains the optional parameters for the CloudServiceRoleInstancesClient.BeginRebuild
// method.
func (client *CloudServiceRoleInstancesClient) BeginRebuild(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginRebuildOptions) (*runtime.Poller[CloudServiceRoleInstancesClientRebuildResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.rebuild(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServiceRoleInstancesClientRebuildResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServiceRoleInstancesClientRebuildResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Rebuild - The Rebuild Role Instance asynchronous operation reinstalls the operating system on instances of web roles or
// worker roles and initializes the storage resources that are used by them. If you do not
// want to initialize storage resources, you can use Reimage Role Instance.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
func (client *CloudServiceRoleInstancesClient) rebuild(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginRebuildOptions) (*http.Response, error) {
var err error
const operationName = "CloudServiceRoleInstancesClient.BeginRebuild"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.rebuildCreateRequest(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// rebuildCreateRequest creates the Rebuild request.
func (client *CloudServiceRoleInstancesClient) rebuildCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginRebuildOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/rebuild"
if roleInstanceName == "" {
return nil, errors.New("parameter roleInstanceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if cloudServiceName == "" {
return nil, errors.New("parameter cloudServiceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// BeginReimage - The Reimage Role Instance asynchronous operation reinstalls the operating system on instances of web roles
// or worker roles.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
// - roleInstanceName - Name of the role instance.
// - resourceGroupName - Name of the resource group.
// - cloudServiceName - Name of the cloud service.
// - options - CloudServiceRoleInstancesClientBeginReimageOptions contains the optional parameters for the CloudServiceRoleInstancesClient.BeginReimage
// method.
func (client *CloudServiceRoleInstancesClient) BeginReimage(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginReimageOptions) (*runtime.Poller[CloudServiceRoleInstancesClientReimageResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.reimage(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServiceRoleInstancesClientReimageResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServiceRoleInstancesClientReimageResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Reimage - The Reimage Role Instance asynchronous operation reinstalls the operating system on instances of web roles or
// worker roles.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
func (client *CloudServiceRoleInstancesClient) reimage(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginReimageOptions) (*http.Response, error) {
var err error
const operationName = "CloudServiceRoleInstancesClient.BeginReimage"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.reimageCreateRequest(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// reimageCreateRequest creates the Reimage request.
func (client *CloudServiceRoleInstancesClient) reimageCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginReimageOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/reimage"
if roleInstanceName == "" {
return nil, errors.New("parameter roleInstanceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if cloudServiceName == "" {
return nil, errors.New("parameter cloudServiceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// BeginRestart - The Reboot Role Instance asynchronous operation requests a reboot of a role instance in the cloud service.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
// - roleInstanceName - Name of the role instance.
// - resourceGroupName - Name of the resource group.
// - cloudServiceName - Name of the cloud service.
// - options - CloudServiceRoleInstancesClientBeginRestartOptions contains the optional parameters for the CloudServiceRoleInstancesClient.BeginRestart
// method.
func (client *CloudServiceRoleInstancesClient) BeginRestart(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginRestartOptions) (*runtime.Poller[CloudServiceRoleInstancesClientRestartResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.restart(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServiceRoleInstancesClientRestartResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServiceRoleInstancesClientRestartResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Restart - The Reboot Role Instance asynchronous operation requests a reboot of a role instance in the cloud service.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
func (client *CloudServiceRoleInstancesClient) restart(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginRestartOptions) (*http.Response, error) {
var err error
const operationName = "CloudServiceRoleInstancesClient.BeginRestart"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.restartCreateRequest(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// restartCreateRequest creates the Restart request.
func (client *CloudServiceRoleInstancesClient) restartCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginRestartOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/restart"
if roleInstanceName == "" {
return nil, errors.New("parameter roleInstanceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if cloudServiceName == "" {
return nil, errors.New("parameter cloudServiceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}

View file

@ -0,0 +1,180 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// CloudServiceRolesClient contains the methods for the CloudServiceRoles group.
// Don't use this type directly, use NewCloudServiceRolesClient() instead.
type CloudServiceRolesClient struct {
internal *arm.Client
subscriptionID string
}
// NewCloudServiceRolesClient creates a new instance of CloudServiceRolesClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewCloudServiceRolesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudServiceRolesClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &CloudServiceRolesClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// Get - Gets a role from a cloud service.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
// - roleName - Name of the role.
// - resourceGroupName - Name of the resource group.
// - cloudServiceName - Name of the cloud service.
// - options - CloudServiceRolesClientGetOptions contains the optional parameters for the CloudServiceRolesClient.Get method.
func (client *CloudServiceRolesClient) Get(ctx context.Context, roleName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRolesClientGetOptions) (CloudServiceRolesClientGetResponse, error) {
var err error
const operationName = "CloudServiceRolesClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, roleName, resourceGroupName, cloudServiceName, options)
if err != nil {
return CloudServiceRolesClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CloudServiceRolesClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return CloudServiceRolesClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *CloudServiceRolesClient) getCreateRequest(ctx context.Context, roleName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRolesClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roles/{roleName}"
if roleName == "" {
return nil, errors.New("parameter roleName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{roleName}", url.PathEscape(roleName))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if cloudServiceName == "" {
return nil, errors.New("parameter cloudServiceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *CloudServiceRolesClient) getHandleResponse(resp *http.Response) (CloudServiceRolesClientGetResponse, error) {
result := CloudServiceRolesClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CloudServiceRole); err != nil {
return CloudServiceRolesClientGetResponse{}, err
}
return result, nil
}
// NewListPager - Gets a list of all roles in a cloud service. Use nextLink property in the response to get the next page
// of roles. Do this till nextLink is null to fetch all the roles.
//
// Generated from API version 2022-09-04
// - resourceGroupName - Name of the resource group.
// - cloudServiceName - Name of the cloud service.
// - options - CloudServiceRolesClientListOptions contains the optional parameters for the CloudServiceRolesClient.NewListPager
// method.
func (client *CloudServiceRolesClient) NewListPager(resourceGroupName string, cloudServiceName string, options *CloudServiceRolesClientListOptions) *runtime.Pager[CloudServiceRolesClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[CloudServiceRolesClientListResponse]{
More: func(page CloudServiceRolesClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *CloudServiceRolesClientListResponse) (CloudServiceRolesClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudServiceRolesClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, resourceGroupName, cloudServiceName, options)
}, nil)
if err != nil {
return CloudServiceRolesClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *CloudServiceRolesClient) listCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServiceRolesClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roles"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if cloudServiceName == "" {
return nil, errors.New("parameter cloudServiceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *CloudServiceRolesClient) listHandleResponse(resp *http.Response) (CloudServiceRolesClientListResponse, error) {
result := CloudServiceRolesClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CloudServiceRoleListResult); err != nil {
return CloudServiceRolesClientListResponse{}, err
}
return result, nil
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,263 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strconv"
"strings"
)
// CloudServicesUpdateDomainClient contains the methods for the CloudServicesUpdateDomain group.
// Don't use this type directly, use NewCloudServicesUpdateDomainClient() instead.
type CloudServicesUpdateDomainClient struct {
internal *arm.Client
subscriptionID string
}
// NewCloudServicesUpdateDomainClient creates a new instance of CloudServicesUpdateDomainClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewCloudServicesUpdateDomainClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudServicesUpdateDomainClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &CloudServicesUpdateDomainClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// GetUpdateDomain - Gets the specified update domain of a cloud service. Use nextLink property in the response to get the
// next page of update domains. Do this till nextLink is null to fetch all the update domains.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
// - resourceGroupName - Name of the resource group.
// - cloudServiceName - Name of the cloud service.
// - updateDomain - Specifies an integer value that identifies the update domain. Update domains are identified with a zero-based
// index: the first update domain has an ID of 0, the second has an ID of 1, and so on.
// - options - CloudServicesUpdateDomainClientGetUpdateDomainOptions contains the optional parameters for the CloudServicesUpdateDomainClient.GetUpdateDomain
// method.
func (client *CloudServicesUpdateDomainClient) GetUpdateDomain(ctx context.Context, resourceGroupName string, cloudServiceName string, updateDomain int32, options *CloudServicesUpdateDomainClientGetUpdateDomainOptions) (CloudServicesUpdateDomainClientGetUpdateDomainResponse, error) {
var err error
const operationName = "CloudServicesUpdateDomainClient.GetUpdateDomain"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getUpdateDomainCreateRequest(ctx, resourceGroupName, cloudServiceName, updateDomain, options)
if err != nil {
return CloudServicesUpdateDomainClientGetUpdateDomainResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CloudServicesUpdateDomainClientGetUpdateDomainResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return CloudServicesUpdateDomainClientGetUpdateDomainResponse{}, err
}
resp, err := client.getUpdateDomainHandleResponse(httpResp)
return resp, err
}
// getUpdateDomainCreateRequest creates the GetUpdateDomain request.
func (client *CloudServicesUpdateDomainClient) getUpdateDomainCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, updateDomain int32, options *CloudServicesUpdateDomainClientGetUpdateDomainOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/updateDomains/{updateDomain}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if cloudServiceName == "" {
return nil, errors.New("parameter cloudServiceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName))
urlPath = strings.ReplaceAll(urlPath, "{updateDomain}", url.PathEscape(strconv.FormatInt(int64(updateDomain), 10)))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getUpdateDomainHandleResponse handles the GetUpdateDomain response.
func (client *CloudServicesUpdateDomainClient) getUpdateDomainHandleResponse(resp *http.Response) (CloudServicesUpdateDomainClientGetUpdateDomainResponse, error) {
result := CloudServicesUpdateDomainClientGetUpdateDomainResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.UpdateDomain); err != nil {
return CloudServicesUpdateDomainClientGetUpdateDomainResponse{}, err
}
return result, nil
}
// NewListUpdateDomainsPager - Gets a list of all update domains in a cloud service.
//
// Generated from API version 2022-09-04
// - resourceGroupName - Name of the resource group.
// - cloudServiceName - Name of the cloud service.
// - options - CloudServicesUpdateDomainClientListUpdateDomainsOptions contains the optional parameters for the CloudServicesUpdateDomainClient.NewListUpdateDomainsPager
// method.
func (client *CloudServicesUpdateDomainClient) NewListUpdateDomainsPager(resourceGroupName string, cloudServiceName string, options *CloudServicesUpdateDomainClientListUpdateDomainsOptions) *runtime.Pager[CloudServicesUpdateDomainClientListUpdateDomainsResponse] {
return runtime.NewPager(runtime.PagingHandler[CloudServicesUpdateDomainClientListUpdateDomainsResponse]{
More: func(page CloudServicesUpdateDomainClientListUpdateDomainsResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *CloudServicesUpdateDomainClientListUpdateDomainsResponse) (CloudServicesUpdateDomainClientListUpdateDomainsResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudServicesUpdateDomainClient.NewListUpdateDomainsPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listUpdateDomainsCreateRequest(ctx, resourceGroupName, cloudServiceName, options)
}, nil)
if err != nil {
return CloudServicesUpdateDomainClientListUpdateDomainsResponse{}, err
}
return client.listUpdateDomainsHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listUpdateDomainsCreateRequest creates the ListUpdateDomains request.
func (client *CloudServicesUpdateDomainClient) listUpdateDomainsCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesUpdateDomainClientListUpdateDomainsOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/updateDomains"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if cloudServiceName == "" {
return nil, errors.New("parameter cloudServiceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listUpdateDomainsHandleResponse handles the ListUpdateDomains response.
func (client *CloudServicesUpdateDomainClient) listUpdateDomainsHandleResponse(resp *http.Response) (CloudServicesUpdateDomainClientListUpdateDomainsResponse, error) {
result := CloudServicesUpdateDomainClientListUpdateDomainsResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.UpdateDomainListResult); err != nil {
return CloudServicesUpdateDomainClientListUpdateDomainsResponse{}, err
}
return result, nil
}
// BeginWalkUpdateDomain - Updates the role instances in the specified update domain.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
// - resourceGroupName - Name of the resource group.
// - cloudServiceName - Name of the cloud service.
// - updateDomain - Specifies an integer value that identifies the update domain. Update domains are identified with a zero-based
// index: the first update domain has an ID of 0, the second has an ID of 1, and so on.
// - parameters - The update domain object.
// - options - CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions contains the optional parameters for the CloudServicesUpdateDomainClient.BeginWalkUpdateDomain
// method.
func (client *CloudServicesUpdateDomainClient) BeginWalkUpdateDomain(ctx context.Context, resourceGroupName string, cloudServiceName string, updateDomain int32, parameters UpdateDomain, options *CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions) (*runtime.Poller[CloudServicesUpdateDomainClientWalkUpdateDomainResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.walkUpdateDomain(ctx, resourceGroupName, cloudServiceName, updateDomain, parameters, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServicesUpdateDomainClientWalkUpdateDomainResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServicesUpdateDomainClientWalkUpdateDomainResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// WalkUpdateDomain - Updates the role instances in the specified update domain.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-09-04
func (client *CloudServicesUpdateDomainClient) walkUpdateDomain(ctx context.Context, resourceGroupName string, cloudServiceName string, updateDomain int32, parameters UpdateDomain, options *CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions) (*http.Response, error) {
var err error
const operationName = "CloudServicesUpdateDomainClient.BeginWalkUpdateDomain"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.walkUpdateDomainCreateRequest(ctx, resourceGroupName, cloudServiceName, updateDomain, parameters, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// walkUpdateDomainCreateRequest creates the WalkUpdateDomain request.
func (client *CloudServicesUpdateDomainClient) walkUpdateDomainCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, updateDomain int32, parameters UpdateDomain, options *CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/updateDomains/{updateDomain}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if cloudServiceName == "" {
return nil, errors.New("parameter cloudServiceName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName))
urlPath = strings.ReplaceAll(urlPath, "{updateDomain}", url.PathEscape(strconv.FormatInt(int64(updateDomain), 10)))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-09-04")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,109 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// CommunityGalleriesClient contains the methods for the CommunityGalleries group.
// Don't use this type directly, use NewCommunityGalleriesClient() instead.
type CommunityGalleriesClient struct {
internal *arm.Client
subscriptionID string
}
// NewCommunityGalleriesClient creates a new instance of CommunityGalleriesClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewCommunityGalleriesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CommunityGalleriesClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &CommunityGalleriesClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// Get - Get a community gallery by gallery public name.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - location - Resource location.
// - publicGalleryName - The public name of the community gallery.
// - options - CommunityGalleriesClientGetOptions contains the optional parameters for the CommunityGalleriesClient.Get method.
func (client *CommunityGalleriesClient) Get(ctx context.Context, location string, publicGalleryName string, options *CommunityGalleriesClientGetOptions) (CommunityGalleriesClientGetResponse, error) {
var err error
const operationName = "CommunityGalleriesClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, location, publicGalleryName, options)
if err != nil {
return CommunityGalleriesClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CommunityGalleriesClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return CommunityGalleriesClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *CommunityGalleriesClient) getCreateRequest(ctx context.Context, location string, publicGalleryName string, options *CommunityGalleriesClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/communityGalleries/{publicGalleryName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if publicGalleryName == "" {
return nil, errors.New("parameter publicGalleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{publicGalleryName}", url.PathEscape(publicGalleryName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *CommunityGalleriesClient) getHandleResponse(resp *http.Response) (CommunityGalleriesClientGetResponse, error) {
result := CommunityGalleriesClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CommunityGallery); err != nil {
return CommunityGalleriesClientGetResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,180 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// CommunityGalleryImagesClient contains the methods for the CommunityGalleryImages group.
// Don't use this type directly, use NewCommunityGalleryImagesClient() instead.
type CommunityGalleryImagesClient struct {
internal *arm.Client
subscriptionID string
}
// NewCommunityGalleryImagesClient creates a new instance of CommunityGalleryImagesClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewCommunityGalleryImagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CommunityGalleryImagesClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &CommunityGalleryImagesClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// Get - Get a community gallery image.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - location - Resource location.
// - publicGalleryName - The public name of the community gallery.
// - galleryImageName - The name of the community gallery image definition.
// - options - CommunityGalleryImagesClientGetOptions contains the optional parameters for the CommunityGalleryImagesClient.Get
// method.
func (client *CommunityGalleryImagesClient) Get(ctx context.Context, location string, publicGalleryName string, galleryImageName string, options *CommunityGalleryImagesClientGetOptions) (CommunityGalleryImagesClientGetResponse, error) {
var err error
const operationName = "CommunityGalleryImagesClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, location, publicGalleryName, galleryImageName, options)
if err != nil {
return CommunityGalleryImagesClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CommunityGalleryImagesClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return CommunityGalleryImagesClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *CommunityGalleryImagesClient) getCreateRequest(ctx context.Context, location string, publicGalleryName string, galleryImageName string, options *CommunityGalleryImagesClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/communityGalleries/{publicGalleryName}/images/{galleryImageName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if publicGalleryName == "" {
return nil, errors.New("parameter publicGalleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{publicGalleryName}", url.PathEscape(publicGalleryName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *CommunityGalleryImagesClient) getHandleResponse(resp *http.Response) (CommunityGalleryImagesClientGetResponse, error) {
result := CommunityGalleryImagesClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CommunityGalleryImage); err != nil {
return CommunityGalleryImagesClientGetResponse{}, err
}
return result, nil
}
// NewListPager - List community gallery images inside a gallery.
//
// Generated from API version 2022-03-03
// - location - Resource location.
// - publicGalleryName - The public name of the community gallery.
// - options - CommunityGalleryImagesClientListOptions contains the optional parameters for the CommunityGalleryImagesClient.NewListPager
// method.
func (client *CommunityGalleryImagesClient) NewListPager(location string, publicGalleryName string, options *CommunityGalleryImagesClientListOptions) *runtime.Pager[CommunityGalleryImagesClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[CommunityGalleryImagesClientListResponse]{
More: func(page CommunityGalleryImagesClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *CommunityGalleryImagesClientListResponse) (CommunityGalleryImagesClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CommunityGalleryImagesClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, location, publicGalleryName, options)
}, nil)
if err != nil {
return CommunityGalleryImagesClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *CommunityGalleryImagesClient) listCreateRequest(ctx context.Context, location string, publicGalleryName string, options *CommunityGalleryImagesClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/communityGalleries/{publicGalleryName}/images"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if publicGalleryName == "" {
return nil, errors.New("parameter publicGalleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{publicGalleryName}", url.PathEscape(publicGalleryName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *CommunityGalleryImagesClient) listHandleResponse(resp *http.Response) (CommunityGalleryImagesClientListResponse, error) {
result := CommunityGalleryImagesClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CommunityGalleryImageList); err != nil {
return CommunityGalleryImagesClientListResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,192 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// CommunityGalleryImageVersionsClient contains the methods for the CommunityGalleryImageVersions group.
// Don't use this type directly, use NewCommunityGalleryImageVersionsClient() instead.
type CommunityGalleryImageVersionsClient struct {
internal *arm.Client
subscriptionID string
}
// NewCommunityGalleryImageVersionsClient creates a new instance of CommunityGalleryImageVersionsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewCommunityGalleryImageVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CommunityGalleryImageVersionsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &CommunityGalleryImageVersionsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// Get - Get a community gallery image version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - location - Resource location.
// - publicGalleryName - The public name of the community gallery.
// - galleryImageName - The name of the community gallery image definition.
// - galleryImageVersionName - The name of the community gallery image version. Needs to follow semantic version name pattern:
// The allowed characters are digit and period. Digits must be within the range of a 32-bit integer.
// Format: ..
// - options - CommunityGalleryImageVersionsClientGetOptions contains the optional parameters for the CommunityGalleryImageVersionsClient.Get
// method.
func (client *CommunityGalleryImageVersionsClient) Get(ctx context.Context, location string, publicGalleryName string, galleryImageName string, galleryImageVersionName string, options *CommunityGalleryImageVersionsClientGetOptions) (CommunityGalleryImageVersionsClientGetResponse, error) {
var err error
const operationName = "CommunityGalleryImageVersionsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, location, publicGalleryName, galleryImageName, galleryImageVersionName, options)
if err != nil {
return CommunityGalleryImageVersionsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return CommunityGalleryImageVersionsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return CommunityGalleryImageVersionsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *CommunityGalleryImageVersionsClient) getCreateRequest(ctx context.Context, location string, publicGalleryName string, galleryImageName string, galleryImageVersionName string, options *CommunityGalleryImageVersionsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/communityGalleries/{publicGalleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if publicGalleryName == "" {
return nil, errors.New("parameter publicGalleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{publicGalleryName}", url.PathEscape(publicGalleryName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
if galleryImageVersionName == "" {
return nil, errors.New("parameter galleryImageVersionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageVersionName}", url.PathEscape(galleryImageVersionName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *CommunityGalleryImageVersionsClient) getHandleResponse(resp *http.Response) (CommunityGalleryImageVersionsClientGetResponse, error) {
result := CommunityGalleryImageVersionsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CommunityGalleryImageVersion); err != nil {
return CommunityGalleryImageVersionsClientGetResponse{}, err
}
return result, nil
}
// NewListPager - List community gallery image versions inside an image.
//
// Generated from API version 2022-03-03
// - location - Resource location.
// - publicGalleryName - The public name of the community gallery.
// - galleryImageName - The name of the community gallery image definition.
// - options - CommunityGalleryImageVersionsClientListOptions contains the optional parameters for the CommunityGalleryImageVersionsClient.NewListPager
// method.
func (client *CommunityGalleryImageVersionsClient) NewListPager(location string, publicGalleryName string, galleryImageName string, options *CommunityGalleryImageVersionsClientListOptions) *runtime.Pager[CommunityGalleryImageVersionsClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[CommunityGalleryImageVersionsClientListResponse]{
More: func(page CommunityGalleryImageVersionsClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *CommunityGalleryImageVersionsClientListResponse) (CommunityGalleryImageVersionsClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CommunityGalleryImageVersionsClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, location, publicGalleryName, galleryImageName, options)
}, nil)
if err != nil {
return CommunityGalleryImageVersionsClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *CommunityGalleryImageVersionsClient) listCreateRequest(ctx context.Context, location string, publicGalleryName string, galleryImageName string, options *CommunityGalleryImageVersionsClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/communityGalleries/{publicGalleryName}/images/{galleryImageName}/versions"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if publicGalleryName == "" {
return nil, errors.New("parameter publicGalleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{publicGalleryName}", url.PathEscape(publicGalleryName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *CommunityGalleryImageVersionsClient) listHandleResponse(resp *http.Response) (CommunityGalleryImageVersionsClientListResponse, error) {
result := CommunityGalleryImageVersionsClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.CommunityGalleryImageVersionList); err != nil {
return CommunityGalleryImageVersionsClientListResponse{}, err
}
return result, nil
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,423 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// DedicatedHostGroupsClient contains the methods for the DedicatedHostGroups group.
// Don't use this type directly, use NewDedicatedHostGroupsClient() instead.
type DedicatedHostGroupsClient struct {
internal *arm.Client
subscriptionID string
}
// NewDedicatedHostGroupsClient creates a new instance of DedicatedHostGroupsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewDedicatedHostGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DedicatedHostGroupsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &DedicatedHostGroupsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// CreateOrUpdate - Create or update a dedicated host group. For details of Dedicated Host and Dedicated Host Groups please
// see Dedicated Host Documentation [https://go.microsoft.com/fwlink/?linkid=2082596]
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - hostGroupName - The name of the dedicated host group.
// - parameters - Parameters supplied to the Create Dedicated Host Group.
// - options - DedicatedHostGroupsClientCreateOrUpdateOptions contains the optional parameters for the DedicatedHostGroupsClient.CreateOrUpdate
// method.
func (client *DedicatedHostGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, hostGroupName string, parameters DedicatedHostGroup, options *DedicatedHostGroupsClientCreateOrUpdateOptions) (DedicatedHostGroupsClientCreateOrUpdateResponse, error) {
var err error
const operationName = "DedicatedHostGroupsClient.CreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, hostGroupName, parameters, options)
if err != nil {
return DedicatedHostGroupsClientCreateOrUpdateResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return DedicatedHostGroupsClientCreateOrUpdateResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
err = runtime.NewResponseError(httpResp)
return DedicatedHostGroupsClientCreateOrUpdateResponse{}, err
}
resp, err := client.createOrUpdateHandleResponse(httpResp)
return resp, err
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *DedicatedHostGroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, parameters DedicatedHostGroup, options *DedicatedHostGroupsClientCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if hostGroupName == "" {
return nil, errors.New("parameter hostGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// createOrUpdateHandleResponse handles the CreateOrUpdate response.
func (client *DedicatedHostGroupsClient) createOrUpdateHandleResponse(resp *http.Response) (DedicatedHostGroupsClientCreateOrUpdateResponse, error) {
result := DedicatedHostGroupsClientCreateOrUpdateResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostGroup); err != nil {
return DedicatedHostGroupsClientCreateOrUpdateResponse{}, err
}
return result, nil
}
// Delete - Delete a dedicated host group.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - hostGroupName - The name of the dedicated host group.
// - options - DedicatedHostGroupsClientDeleteOptions contains the optional parameters for the DedicatedHostGroupsClient.Delete
// method.
func (client *DedicatedHostGroupsClient) Delete(ctx context.Context, resourceGroupName string, hostGroupName string, options *DedicatedHostGroupsClientDeleteOptions) (DedicatedHostGroupsClientDeleteResponse, error) {
var err error
const operationName = "DedicatedHostGroupsClient.Delete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, hostGroupName, options)
if err != nil {
return DedicatedHostGroupsClientDeleteResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return DedicatedHostGroupsClientDeleteResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return DedicatedHostGroupsClientDeleteResponse{}, err
}
return DedicatedHostGroupsClientDeleteResponse{}, nil
}
// deleteCreateRequest creates the Delete request.
func (client *DedicatedHostGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, options *DedicatedHostGroupsClientDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if hostGroupName == "" {
return nil, errors.New("parameter hostGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - Retrieves information about a dedicated host group.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - hostGroupName - The name of the dedicated host group.
// - options - DedicatedHostGroupsClientGetOptions contains the optional parameters for the DedicatedHostGroupsClient.Get method.
func (client *DedicatedHostGroupsClient) Get(ctx context.Context, resourceGroupName string, hostGroupName string, options *DedicatedHostGroupsClientGetOptions) (DedicatedHostGroupsClientGetResponse, error) {
var err error
const operationName = "DedicatedHostGroupsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, hostGroupName, options)
if err != nil {
return DedicatedHostGroupsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return DedicatedHostGroupsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return DedicatedHostGroupsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *DedicatedHostGroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, options *DedicatedHostGroupsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if hostGroupName == "" {
return nil, errors.New("parameter hostGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
if options != nil && options.Expand != nil {
reqQP.Set("$expand", string(*options.Expand))
}
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *DedicatedHostGroupsClient) getHandleResponse(resp *http.Response) (DedicatedHostGroupsClientGetResponse, error) {
result := DedicatedHostGroupsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostGroup); err != nil {
return DedicatedHostGroupsClientGetResponse{}, err
}
return result, nil
}
// NewListByResourceGroupPager - Lists all of the dedicated host groups in the specified resource group. Use the nextLink
// property in the response to get the next page of dedicated host groups.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - options - DedicatedHostGroupsClientListByResourceGroupOptions contains the optional parameters for the DedicatedHostGroupsClient.NewListByResourceGroupPager
// method.
func (client *DedicatedHostGroupsClient) NewListByResourceGroupPager(resourceGroupName string, options *DedicatedHostGroupsClientListByResourceGroupOptions) *runtime.Pager[DedicatedHostGroupsClientListByResourceGroupResponse] {
return runtime.NewPager(runtime.PagingHandler[DedicatedHostGroupsClientListByResourceGroupResponse]{
More: func(page DedicatedHostGroupsClientListByResourceGroupResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *DedicatedHostGroupsClientListByResourceGroupResponse) (DedicatedHostGroupsClientListByResourceGroupResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DedicatedHostGroupsClient.NewListByResourceGroupPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options)
}, nil)
if err != nil {
return DedicatedHostGroupsClientListByResourceGroupResponse{}, err
}
return client.listByResourceGroupHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *DedicatedHostGroupsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *DedicatedHostGroupsClientListByResourceGroupOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *DedicatedHostGroupsClient) listByResourceGroupHandleResponse(resp *http.Response) (DedicatedHostGroupsClientListByResourceGroupResponse, error) {
result := DedicatedHostGroupsClientListByResourceGroupResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostGroupListResult); err != nil {
return DedicatedHostGroupsClientListByResourceGroupResponse{}, err
}
return result, nil
}
// NewListBySubscriptionPager - Lists all of the dedicated host groups in the subscription. Use the nextLink property in the
// response to get the next page of dedicated host groups.
//
// Generated from API version 2023-07-01
// - options - DedicatedHostGroupsClientListBySubscriptionOptions contains the optional parameters for the DedicatedHostGroupsClient.NewListBySubscriptionPager
// method.
func (client *DedicatedHostGroupsClient) NewListBySubscriptionPager(options *DedicatedHostGroupsClientListBySubscriptionOptions) *runtime.Pager[DedicatedHostGroupsClientListBySubscriptionResponse] {
return runtime.NewPager(runtime.PagingHandler[DedicatedHostGroupsClientListBySubscriptionResponse]{
More: func(page DedicatedHostGroupsClientListBySubscriptionResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *DedicatedHostGroupsClientListBySubscriptionResponse) (DedicatedHostGroupsClientListBySubscriptionResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DedicatedHostGroupsClient.NewListBySubscriptionPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listBySubscriptionCreateRequest(ctx, options)
}, nil)
if err != nil {
return DedicatedHostGroupsClientListBySubscriptionResponse{}, err
}
return client.listBySubscriptionHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listBySubscriptionCreateRequest creates the ListBySubscription request.
func (client *DedicatedHostGroupsClient) listBySubscriptionCreateRequest(ctx context.Context, options *DedicatedHostGroupsClientListBySubscriptionOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/hostGroups"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listBySubscriptionHandleResponse handles the ListBySubscription response.
func (client *DedicatedHostGroupsClient) listBySubscriptionHandleResponse(resp *http.Response) (DedicatedHostGroupsClientListBySubscriptionResponse, error) {
result := DedicatedHostGroupsClientListBySubscriptionResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostGroupListResult); err != nil {
return DedicatedHostGroupsClientListBySubscriptionResponse{}, err
}
return result, nil
}
// Update - Update an dedicated host group.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - hostGroupName - The name of the dedicated host group.
// - parameters - Parameters supplied to the Update Dedicated Host Group operation.
// - options - DedicatedHostGroupsClientUpdateOptions contains the optional parameters for the DedicatedHostGroupsClient.Update
// method.
func (client *DedicatedHostGroupsClient) Update(ctx context.Context, resourceGroupName string, hostGroupName string, parameters DedicatedHostGroupUpdate, options *DedicatedHostGroupsClientUpdateOptions) (DedicatedHostGroupsClientUpdateResponse, error) {
var err error
const operationName = "DedicatedHostGroupsClient.Update"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, hostGroupName, parameters, options)
if err != nil {
return DedicatedHostGroupsClientUpdateResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return DedicatedHostGroupsClientUpdateResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return DedicatedHostGroupsClientUpdateResponse{}, err
}
resp, err := client.updateHandleResponse(httpResp)
return resp, err
}
// updateCreateRequest creates the Update request.
func (client *DedicatedHostGroupsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, parameters DedicatedHostGroupUpdate, options *DedicatedHostGroupsClientUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if hostGroupName == "" {
return nil, errors.New("parameter hostGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// updateHandleResponse handles the Update response.
func (client *DedicatedHostGroupsClient) updateHandleResponse(resp *http.Response) (DedicatedHostGroupsClientUpdateResponse, error) {
result := DedicatedHostGroupsClientUpdateResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostGroup); err != nil {
return DedicatedHostGroupsClientUpdateResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,593 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// DedicatedHostsClient contains the methods for the DedicatedHosts group.
// Don't use this type directly, use NewDedicatedHostsClient() instead.
type DedicatedHostsClient struct {
internal *arm.Client
subscriptionID string
}
// NewDedicatedHostsClient creates a new instance of DedicatedHostsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewDedicatedHostsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DedicatedHostsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &DedicatedHostsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreateOrUpdate - Create or update a dedicated host .
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - hostGroupName - The name of the dedicated host group.
// - hostName - The name of the dedicated host .
// - parameters - Parameters supplied to the Create Dedicated Host.
// - options - DedicatedHostsClientBeginCreateOrUpdateOptions contains the optional parameters for the DedicatedHostsClient.BeginCreateOrUpdate
// method.
func (client *DedicatedHostsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHost, options *DedicatedHostsClientBeginCreateOrUpdateOptions) (*runtime.Poller[DedicatedHostsClientCreateOrUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.createOrUpdate(ctx, resourceGroupName, hostGroupName, hostName, parameters, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DedicatedHostsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DedicatedHostsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// CreateOrUpdate - Create or update a dedicated host .
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *DedicatedHostsClient) createOrUpdate(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHost, options *DedicatedHostsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
var err error
const operationName = "DedicatedHostsClient.BeginCreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, hostGroupName, hostName, parameters, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *DedicatedHostsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHost, options *DedicatedHostsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if hostGroupName == "" {
return nil, errors.New("parameter hostGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName))
if hostName == "" {
return nil, errors.New("parameter hostName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostName}", url.PathEscape(hostName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - Delete a dedicated host.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - hostGroupName - The name of the dedicated host group.
// - hostName - The name of the dedicated host.
// - options - DedicatedHostsClientBeginDeleteOptions contains the optional parameters for the DedicatedHostsClient.BeginDelete
// method.
func (client *DedicatedHostsClient) BeginDelete(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginDeleteOptions) (*runtime.Poller[DedicatedHostsClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, hostGroupName, hostName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DedicatedHostsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DedicatedHostsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - Delete a dedicated host.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *DedicatedHostsClient) deleteOperation(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "DedicatedHostsClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, hostGroupName, hostName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *DedicatedHostsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if hostGroupName == "" {
return nil, errors.New("parameter hostGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName))
if hostName == "" {
return nil, errors.New("parameter hostName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostName}", url.PathEscape(hostName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - Retrieves information about a dedicated host.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - hostGroupName - The name of the dedicated host group.
// - hostName - The name of the dedicated host.
// - options - DedicatedHostsClientGetOptions contains the optional parameters for the DedicatedHostsClient.Get method.
func (client *DedicatedHostsClient) Get(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientGetOptions) (DedicatedHostsClientGetResponse, error) {
var err error
const operationName = "DedicatedHostsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, hostGroupName, hostName, options)
if err != nil {
return DedicatedHostsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return DedicatedHostsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return DedicatedHostsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *DedicatedHostsClient) getCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if hostGroupName == "" {
return nil, errors.New("parameter hostGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName))
if hostName == "" {
return nil, errors.New("parameter hostName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostName}", url.PathEscape(hostName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
if options != nil && options.Expand != nil {
reqQP.Set("$expand", string(*options.Expand))
}
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *DedicatedHostsClient) getHandleResponse(resp *http.Response) (DedicatedHostsClientGetResponse, error) {
result := DedicatedHostsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHost); err != nil {
return DedicatedHostsClientGetResponse{}, err
}
return result, nil
}
// NewListAvailableSizesPager - Lists all available dedicated host sizes to which the specified dedicated host can be resized.
// NOTE: The dedicated host sizes provided can be used to only scale up the existing dedicated host.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - hostGroupName - The name of the dedicated host group.
// - hostName - The name of the dedicated host.
// - options - DedicatedHostsClientListAvailableSizesOptions contains the optional parameters for the DedicatedHostsClient.NewListAvailableSizesPager
// method.
func (client *DedicatedHostsClient) NewListAvailableSizesPager(resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientListAvailableSizesOptions) *runtime.Pager[DedicatedHostsClientListAvailableSizesResponse] {
return runtime.NewPager(runtime.PagingHandler[DedicatedHostsClientListAvailableSizesResponse]{
More: func(page DedicatedHostsClientListAvailableSizesResponse) bool {
return false
},
Fetcher: func(ctx context.Context, page *DedicatedHostsClientListAvailableSizesResponse) (DedicatedHostsClientListAvailableSizesResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DedicatedHostsClient.NewListAvailableSizesPager")
req, err := client.listAvailableSizesCreateRequest(ctx, resourceGroupName, hostGroupName, hostName, options)
if err != nil {
return DedicatedHostsClientListAvailableSizesResponse{}, err
}
resp, err := client.internal.Pipeline().Do(req)
if err != nil {
return DedicatedHostsClientListAvailableSizesResponse{}, err
}
if !runtime.HasStatusCode(resp, http.StatusOK) {
return DedicatedHostsClientListAvailableSizesResponse{}, runtime.NewResponseError(resp)
}
return client.listAvailableSizesHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listAvailableSizesCreateRequest creates the ListAvailableSizes request.
func (client *DedicatedHostsClient) listAvailableSizesCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientListAvailableSizesOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}/hostSizes"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if hostGroupName == "" {
return nil, errors.New("parameter hostGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName))
if hostName == "" {
return nil, errors.New("parameter hostName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostName}", url.PathEscape(hostName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listAvailableSizesHandleResponse handles the ListAvailableSizes response.
func (client *DedicatedHostsClient) listAvailableSizesHandleResponse(resp *http.Response) (DedicatedHostsClientListAvailableSizesResponse, error) {
result := DedicatedHostsClientListAvailableSizesResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostSizeListResult); err != nil {
return DedicatedHostsClientListAvailableSizesResponse{}, err
}
return result, nil
}
// NewListByHostGroupPager - Lists all of the dedicated hosts in the specified dedicated host group. Use the nextLink property
// in the response to get the next page of dedicated hosts.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - hostGroupName - The name of the dedicated host group.
// - options - DedicatedHostsClientListByHostGroupOptions contains the optional parameters for the DedicatedHostsClient.NewListByHostGroupPager
// method.
func (client *DedicatedHostsClient) NewListByHostGroupPager(resourceGroupName string, hostGroupName string, options *DedicatedHostsClientListByHostGroupOptions) *runtime.Pager[DedicatedHostsClientListByHostGroupResponse] {
return runtime.NewPager(runtime.PagingHandler[DedicatedHostsClientListByHostGroupResponse]{
More: func(page DedicatedHostsClientListByHostGroupResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *DedicatedHostsClientListByHostGroupResponse) (DedicatedHostsClientListByHostGroupResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DedicatedHostsClient.NewListByHostGroupPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByHostGroupCreateRequest(ctx, resourceGroupName, hostGroupName, options)
}, nil)
if err != nil {
return DedicatedHostsClientListByHostGroupResponse{}, err
}
return client.listByHostGroupHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByHostGroupCreateRequest creates the ListByHostGroup request.
func (client *DedicatedHostsClient) listByHostGroupCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, options *DedicatedHostsClientListByHostGroupOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if hostGroupName == "" {
return nil, errors.New("parameter hostGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByHostGroupHandleResponse handles the ListByHostGroup response.
func (client *DedicatedHostsClient) listByHostGroupHandleResponse(resp *http.Response) (DedicatedHostsClientListByHostGroupResponse, error) {
result := DedicatedHostsClientListByHostGroupResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostListResult); err != nil {
return DedicatedHostsClientListByHostGroupResponse{}, err
}
return result, nil
}
// BeginRestart - Restart the dedicated host. The operation will complete successfully once the dedicated host has restarted
// and is running. To determine the health of VMs deployed on the dedicated host after the
// restart check the Resource Health Center in the Azure Portal. Please refer to https://docs.microsoft.com/azure/service-health/resource-health-overview
// for more details.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - hostGroupName - The name of the dedicated host group.
// - hostName - The name of the dedicated host.
// - options - DedicatedHostsClientBeginRestartOptions contains the optional parameters for the DedicatedHostsClient.BeginRestart
// method.
func (client *DedicatedHostsClient) BeginRestart(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginRestartOptions) (*runtime.Poller[DedicatedHostsClientRestartResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.restart(ctx, resourceGroupName, hostGroupName, hostName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DedicatedHostsClientRestartResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DedicatedHostsClientRestartResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Restart - Restart the dedicated host. The operation will complete successfully once the dedicated host has restarted and
// is running. To determine the health of VMs deployed on the dedicated host after the
// restart check the Resource Health Center in the Azure Portal. Please refer to https://docs.microsoft.com/azure/service-health/resource-health-overview
// for more details.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *DedicatedHostsClient) restart(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginRestartOptions) (*http.Response, error) {
var err error
const operationName = "DedicatedHostsClient.BeginRestart"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.restartCreateRequest(ctx, resourceGroupName, hostGroupName, hostName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// restartCreateRequest creates the Restart request.
func (client *DedicatedHostsClient) restartCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginRestartOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}/restart"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if hostGroupName == "" {
return nil, errors.New("parameter hostGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName))
if hostName == "" {
return nil, errors.New("parameter hostName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostName}", url.PathEscape(hostName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// BeginUpdate - Update a dedicated host .
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - hostGroupName - The name of the dedicated host group.
// - hostName - The name of the dedicated host .
// - parameters - Parameters supplied to the Update Dedicated Host operation.
// - options - DedicatedHostsClientBeginUpdateOptions contains the optional parameters for the DedicatedHostsClient.BeginUpdate
// method.
func (client *DedicatedHostsClient) BeginUpdate(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHostUpdate, options *DedicatedHostsClientBeginUpdateOptions) (*runtime.Poller[DedicatedHostsClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, hostGroupName, hostName, parameters, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DedicatedHostsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DedicatedHostsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - Update a dedicated host .
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *DedicatedHostsClient) update(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHostUpdate, options *DedicatedHostsClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "DedicatedHostsClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, hostGroupName, hostName, parameters, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *DedicatedHostsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHostUpdate, options *DedicatedHostsClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if hostGroupName == "" {
return nil, errors.New("parameter hostGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName))
if hostName == "" {
return nil, errors.New("parameter hostName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{hostName}", url.PathEscape(hostName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,846 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// DiskAccessesClient contains the methods for the DiskAccesses group.
// Don't use this type directly, use NewDiskAccessesClient() instead.
type DiskAccessesClient struct {
internal *arm.Client
subscriptionID string
}
// NewDiskAccessesClient creates a new instance of DiskAccessesClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewDiskAccessesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DiskAccessesClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &DiskAccessesClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreateOrUpdate - Creates or updates a disk access resource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption
// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The
// maximum name length is 80 characters.
// - diskAccess - disk access object supplied in the body of the Put disk access operation.
// - options - DiskAccessesClientBeginCreateOrUpdateOptions contains the optional parameters for the DiskAccessesClient.BeginCreateOrUpdate
// method.
func (client *DiskAccessesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccess, options *DiskAccessesClientBeginCreateOrUpdateOptions) (*runtime.Poller[DiskAccessesClientCreateOrUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.createOrUpdate(ctx, resourceGroupName, diskAccessName, diskAccess, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskAccessesClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskAccessesClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// CreateOrUpdate - Creates or updates a disk access resource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DiskAccessesClient) createOrUpdate(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccess, options *DiskAccessesClientBeginCreateOrUpdateOptions) (*http.Response, error) {
var err error
const operationName = "DiskAccessesClient.BeginCreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, diskAccessName, diskAccess, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *DiskAccessesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccess, options *DiskAccessesClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskAccessName == "" {
return nil, errors.New("parameter diskAccessName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, diskAccess); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - Deletes a disk access resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption
// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The
// maximum name length is 80 characters.
// - options - DiskAccessesClientBeginDeleteOptions contains the optional parameters for the DiskAccessesClient.BeginDelete
// method.
func (client *DiskAccessesClient) BeginDelete(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientBeginDeleteOptions) (*runtime.Poller[DiskAccessesClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, diskAccessName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskAccessesClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskAccessesClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - Deletes a disk access resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DiskAccessesClient) deleteOperation(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "DiskAccessesClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, diskAccessName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *DiskAccessesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskAccessName == "" {
return nil, errors.New("parameter diskAccessName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// BeginDeleteAPrivateEndpointConnection - Deletes a private endpoint connection under a disk access resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption
// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The
// maximum name length is 80 characters.
// - privateEndpointConnectionName - The name of the private endpoint connection.
// - options - DiskAccessesClientBeginDeleteAPrivateEndpointConnectionOptions contains the optional parameters for the DiskAccessesClient.BeginDeleteAPrivateEndpointConnection
// method.
func (client *DiskAccessesClient) BeginDeleteAPrivateEndpointConnection(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, options *DiskAccessesClientBeginDeleteAPrivateEndpointConnectionOptions) (*runtime.Poller[DiskAccessesClientDeleteAPrivateEndpointConnectionResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteAPrivateEndpointConnection(ctx, resourceGroupName, diskAccessName, privateEndpointConnectionName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskAccessesClientDeleteAPrivateEndpointConnectionResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskAccessesClientDeleteAPrivateEndpointConnectionResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// DeleteAPrivateEndpointConnection - Deletes a private endpoint connection under a disk access resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DiskAccessesClient) deleteAPrivateEndpointConnection(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, options *DiskAccessesClientBeginDeleteAPrivateEndpointConnectionOptions) (*http.Response, error) {
var err error
const operationName = "DiskAccessesClient.BeginDeleteAPrivateEndpointConnection"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteAPrivateEndpointConnectionCreateRequest(ctx, resourceGroupName, diskAccessName, privateEndpointConnectionName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteAPrivateEndpointConnectionCreateRequest creates the DeleteAPrivateEndpointConnection request.
func (client *DiskAccessesClient) deleteAPrivateEndpointConnectionCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, options *DiskAccessesClientBeginDeleteAPrivateEndpointConnectionOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}/privateEndpointConnections/{privateEndpointConnectionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskAccessName == "" {
return nil, errors.New("parameter diskAccessName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName))
if privateEndpointConnectionName == "" {
return nil, errors.New("parameter privateEndpointConnectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - Gets information about a disk access resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption
// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The
// maximum name length is 80 characters.
// - options - DiskAccessesClientGetOptions contains the optional parameters for the DiskAccessesClient.Get method.
func (client *DiskAccessesClient) Get(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientGetOptions) (DiskAccessesClientGetResponse, error) {
var err error
const operationName = "DiskAccessesClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, diskAccessName, options)
if err != nil {
return DiskAccessesClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return DiskAccessesClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return DiskAccessesClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *DiskAccessesClient) getCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskAccessName == "" {
return nil, errors.New("parameter diskAccessName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *DiskAccessesClient) getHandleResponse(resp *http.Response) (DiskAccessesClientGetResponse, error) {
result := DiskAccessesClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DiskAccess); err != nil {
return DiskAccessesClientGetResponse{}, err
}
return result, nil
}
// GetAPrivateEndpointConnection - Gets information about a private endpoint connection under a disk access resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption
// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The
// maximum name length is 80 characters.
// - privateEndpointConnectionName - The name of the private endpoint connection.
// - options - DiskAccessesClientGetAPrivateEndpointConnectionOptions contains the optional parameters for the DiskAccessesClient.GetAPrivateEndpointConnection
// method.
func (client *DiskAccessesClient) GetAPrivateEndpointConnection(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, options *DiskAccessesClientGetAPrivateEndpointConnectionOptions) (DiskAccessesClientGetAPrivateEndpointConnectionResponse, error) {
var err error
const operationName = "DiskAccessesClient.GetAPrivateEndpointConnection"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getAPrivateEndpointConnectionCreateRequest(ctx, resourceGroupName, diskAccessName, privateEndpointConnectionName, options)
if err != nil {
return DiskAccessesClientGetAPrivateEndpointConnectionResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return DiskAccessesClientGetAPrivateEndpointConnectionResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return DiskAccessesClientGetAPrivateEndpointConnectionResponse{}, err
}
resp, err := client.getAPrivateEndpointConnectionHandleResponse(httpResp)
return resp, err
}
// getAPrivateEndpointConnectionCreateRequest creates the GetAPrivateEndpointConnection request.
func (client *DiskAccessesClient) getAPrivateEndpointConnectionCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, options *DiskAccessesClientGetAPrivateEndpointConnectionOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}/privateEndpointConnections/{privateEndpointConnectionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskAccessName == "" {
return nil, errors.New("parameter diskAccessName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName))
if privateEndpointConnectionName == "" {
return nil, errors.New("parameter privateEndpointConnectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getAPrivateEndpointConnectionHandleResponse handles the GetAPrivateEndpointConnection response.
func (client *DiskAccessesClient) getAPrivateEndpointConnectionHandleResponse(resp *http.Response) (DiskAccessesClientGetAPrivateEndpointConnectionResponse, error) {
result := DiskAccessesClientGetAPrivateEndpointConnectionResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil {
return DiskAccessesClientGetAPrivateEndpointConnectionResponse{}, err
}
return result, nil
}
// GetPrivateLinkResources - Gets the private link resources possible under disk access resource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption
// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The
// maximum name length is 80 characters.
// - options - DiskAccessesClientGetPrivateLinkResourcesOptions contains the optional parameters for the DiskAccessesClient.GetPrivateLinkResources
// method.
func (client *DiskAccessesClient) GetPrivateLinkResources(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientGetPrivateLinkResourcesOptions) (DiskAccessesClientGetPrivateLinkResourcesResponse, error) {
var err error
const operationName = "DiskAccessesClient.GetPrivateLinkResources"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getPrivateLinkResourcesCreateRequest(ctx, resourceGroupName, diskAccessName, options)
if err != nil {
return DiskAccessesClientGetPrivateLinkResourcesResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return DiskAccessesClientGetPrivateLinkResourcesResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return DiskAccessesClientGetPrivateLinkResourcesResponse{}, err
}
resp, err := client.getPrivateLinkResourcesHandleResponse(httpResp)
return resp, err
}
// getPrivateLinkResourcesCreateRequest creates the GetPrivateLinkResources request.
func (client *DiskAccessesClient) getPrivateLinkResourcesCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientGetPrivateLinkResourcesOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}/privateLinkResources"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskAccessName == "" {
return nil, errors.New("parameter diskAccessName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getPrivateLinkResourcesHandleResponse handles the GetPrivateLinkResources response.
func (client *DiskAccessesClient) getPrivateLinkResourcesHandleResponse(resp *http.Response) (DiskAccessesClientGetPrivateLinkResourcesResponse, error) {
result := DiskAccessesClientGetPrivateLinkResourcesResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResourceListResult); err != nil {
return DiskAccessesClientGetPrivateLinkResourcesResponse{}, err
}
return result, nil
}
// NewListPager - Lists all the disk access resources under a subscription.
//
// Generated from API version 2023-04-02
// - options - DiskAccessesClientListOptions contains the optional parameters for the DiskAccessesClient.NewListPager method.
func (client *DiskAccessesClient) NewListPager(options *DiskAccessesClientListOptions) *runtime.Pager[DiskAccessesClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[DiskAccessesClientListResponse]{
More: func(page DiskAccessesClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *DiskAccessesClientListResponse) (DiskAccessesClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskAccessesClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, options)
}, nil)
if err != nil {
return DiskAccessesClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *DiskAccessesClient) listCreateRequest(ctx context.Context, options *DiskAccessesClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/diskAccesses"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *DiskAccessesClient) listHandleResponse(resp *http.Response) (DiskAccessesClientListResponse, error) {
result := DiskAccessesClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DiskAccessList); err != nil {
return DiskAccessesClientListResponse{}, err
}
return result, nil
}
// NewListByResourceGroupPager - Lists all the disk access resources under a resource group.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - options - DiskAccessesClientListByResourceGroupOptions contains the optional parameters for the DiskAccessesClient.NewListByResourceGroupPager
// method.
func (client *DiskAccessesClient) NewListByResourceGroupPager(resourceGroupName string, options *DiskAccessesClientListByResourceGroupOptions) *runtime.Pager[DiskAccessesClientListByResourceGroupResponse] {
return runtime.NewPager(runtime.PagingHandler[DiskAccessesClientListByResourceGroupResponse]{
More: func(page DiskAccessesClientListByResourceGroupResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *DiskAccessesClientListByResourceGroupResponse) (DiskAccessesClientListByResourceGroupResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskAccessesClient.NewListByResourceGroupPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options)
}, nil)
if err != nil {
return DiskAccessesClientListByResourceGroupResponse{}, err
}
return client.listByResourceGroupHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *DiskAccessesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *DiskAccessesClientListByResourceGroupOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *DiskAccessesClient) listByResourceGroupHandleResponse(resp *http.Response) (DiskAccessesClientListByResourceGroupResponse, error) {
result := DiskAccessesClientListByResourceGroupResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DiskAccessList); err != nil {
return DiskAccessesClientListByResourceGroupResponse{}, err
}
return result, nil
}
// NewListPrivateEndpointConnectionsPager - List information about private endpoint connections under a disk access resource
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption
// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The
// maximum name length is 80 characters.
// - options - DiskAccessesClientListPrivateEndpointConnectionsOptions contains the optional parameters for the DiskAccessesClient.NewListPrivateEndpointConnectionsPager
// method.
func (client *DiskAccessesClient) NewListPrivateEndpointConnectionsPager(resourceGroupName string, diskAccessName string, options *DiskAccessesClientListPrivateEndpointConnectionsOptions) *runtime.Pager[DiskAccessesClientListPrivateEndpointConnectionsResponse] {
return runtime.NewPager(runtime.PagingHandler[DiskAccessesClientListPrivateEndpointConnectionsResponse]{
More: func(page DiskAccessesClientListPrivateEndpointConnectionsResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *DiskAccessesClientListPrivateEndpointConnectionsResponse) (DiskAccessesClientListPrivateEndpointConnectionsResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskAccessesClient.NewListPrivateEndpointConnectionsPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listPrivateEndpointConnectionsCreateRequest(ctx, resourceGroupName, diskAccessName, options)
}, nil)
if err != nil {
return DiskAccessesClientListPrivateEndpointConnectionsResponse{}, err
}
return client.listPrivateEndpointConnectionsHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listPrivateEndpointConnectionsCreateRequest creates the ListPrivateEndpointConnections request.
func (client *DiskAccessesClient) listPrivateEndpointConnectionsCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientListPrivateEndpointConnectionsOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}/privateEndpointConnections"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskAccessName == "" {
return nil, errors.New("parameter diskAccessName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listPrivateEndpointConnectionsHandleResponse handles the ListPrivateEndpointConnections response.
func (client *DiskAccessesClient) listPrivateEndpointConnectionsHandleResponse(resp *http.Response) (DiskAccessesClientListPrivateEndpointConnectionsResponse, error) {
result := DiskAccessesClientListPrivateEndpointConnectionsResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionListResult); err != nil {
return DiskAccessesClientListPrivateEndpointConnectionsResponse{}, err
}
return result, nil
}
// BeginUpdate - Updates (patches) a disk access resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption
// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The
// maximum name length is 80 characters.
// - diskAccess - disk access object supplied in the body of the Patch disk access operation.
// - options - DiskAccessesClientBeginUpdateOptions contains the optional parameters for the DiskAccessesClient.BeginUpdate
// method.
func (client *DiskAccessesClient) BeginUpdate(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccessUpdate, options *DiskAccessesClientBeginUpdateOptions) (*runtime.Poller[DiskAccessesClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, diskAccessName, diskAccess, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskAccessesClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskAccessesClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - Updates (patches) a disk access resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DiskAccessesClient) update(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccessUpdate, options *DiskAccessesClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "DiskAccessesClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, diskAccessName, diskAccess, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *DiskAccessesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccessUpdate, options *DiskAccessesClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskAccessName == "" {
return nil, errors.New("parameter diskAccessName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, diskAccess); err != nil {
return nil, err
}
return req, nil
}
// BeginUpdateAPrivateEndpointConnection - Approve or reject a private endpoint connection under disk access resource, this
// can't be used to create a new private endpoint connection.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption
// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The
// maximum name length is 80 characters.
// - privateEndpointConnectionName - The name of the private endpoint connection.
// - privateEndpointConnection - private endpoint connection object supplied in the body of the Put private endpoint connection
// operation.
// - options - DiskAccessesClientBeginUpdateAPrivateEndpointConnectionOptions contains the optional parameters for the DiskAccessesClient.BeginUpdateAPrivateEndpointConnection
// method.
func (client *DiskAccessesClient) BeginUpdateAPrivateEndpointConnection(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *DiskAccessesClientBeginUpdateAPrivateEndpointConnectionOptions) (*runtime.Poller[DiskAccessesClientUpdateAPrivateEndpointConnectionResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.updateAPrivateEndpointConnection(ctx, resourceGroupName, diskAccessName, privateEndpointConnectionName, privateEndpointConnection, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskAccessesClientUpdateAPrivateEndpointConnectionResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskAccessesClientUpdateAPrivateEndpointConnectionResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// UpdateAPrivateEndpointConnection - Approve or reject a private endpoint connection under disk access resource, this can't
// be used to create a new private endpoint connection.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DiskAccessesClient) updateAPrivateEndpointConnection(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *DiskAccessesClientBeginUpdateAPrivateEndpointConnectionOptions) (*http.Response, error) {
var err error
const operationName = "DiskAccessesClient.BeginUpdateAPrivateEndpointConnection"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateAPrivateEndpointConnectionCreateRequest(ctx, resourceGroupName, diskAccessName, privateEndpointConnectionName, privateEndpointConnection, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateAPrivateEndpointConnectionCreateRequest creates the UpdateAPrivateEndpointConnection request.
func (client *DiskAccessesClient) updateAPrivateEndpointConnectionCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *DiskAccessesClientBeginUpdateAPrivateEndpointConnectionOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}/privateEndpointConnections/{privateEndpointConnectionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskAccessName == "" {
return nil, errors.New("parameter diskAccessName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName))
if privateEndpointConnectionName == "" {
return nil, errors.New("parameter privateEndpointConnectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, privateEndpointConnection); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,535 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// DiskEncryptionSetsClient contains the methods for the DiskEncryptionSets group.
// Don't use this type directly, use NewDiskEncryptionSetsClient() instead.
type DiskEncryptionSetsClient struct {
internal *arm.Client
subscriptionID string
}
// NewDiskEncryptionSetsClient creates a new instance of DiskEncryptionSetsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewDiskEncryptionSetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DiskEncryptionSetsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &DiskEncryptionSetsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreateOrUpdate - Creates or updates a disk encryption set
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the
// disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum
// name length is 80 characters.
// - diskEncryptionSet - disk encryption set object supplied in the body of the Put disk encryption set operation.
// - options - DiskEncryptionSetsClientBeginCreateOrUpdateOptions contains the optional parameters for the DiskEncryptionSetsClient.BeginCreateOrUpdate
// method.
func (client *DiskEncryptionSetsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSet, options *DiskEncryptionSetsClientBeginCreateOrUpdateOptions) (*runtime.Poller[DiskEncryptionSetsClientCreateOrUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.createOrUpdate(ctx, resourceGroupName, diskEncryptionSetName, diskEncryptionSet, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskEncryptionSetsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskEncryptionSetsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// CreateOrUpdate - Creates or updates a disk encryption set
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DiskEncryptionSetsClient) createOrUpdate(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSet, options *DiskEncryptionSetsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
var err error
const operationName = "DiskEncryptionSetsClient.BeginCreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, diskEncryptionSetName, diskEncryptionSet, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *DiskEncryptionSetsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSet, options *DiskEncryptionSetsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskEncryptionSetName == "" {
return nil, errors.New("parameter diskEncryptionSetName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskEncryptionSetName}", url.PathEscape(diskEncryptionSetName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, diskEncryptionSet); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - Deletes a disk encryption set.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the
// disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum
// name length is 80 characters.
// - options - DiskEncryptionSetsClientBeginDeleteOptions contains the optional parameters for the DiskEncryptionSetsClient.BeginDelete
// method.
func (client *DiskEncryptionSetsClient) BeginDelete(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientBeginDeleteOptions) (*runtime.Poller[DiskEncryptionSetsClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, diskEncryptionSetName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskEncryptionSetsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskEncryptionSetsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - Deletes a disk encryption set.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DiskEncryptionSetsClient) deleteOperation(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "DiskEncryptionSetsClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, diskEncryptionSetName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *DiskEncryptionSetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskEncryptionSetName == "" {
return nil, errors.New("parameter diskEncryptionSetName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskEncryptionSetName}", url.PathEscape(diskEncryptionSetName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - Gets information about a disk encryption set.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the
// disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum
// name length is 80 characters.
// - options - DiskEncryptionSetsClientGetOptions contains the optional parameters for the DiskEncryptionSetsClient.Get method.
func (client *DiskEncryptionSetsClient) Get(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientGetOptions) (DiskEncryptionSetsClientGetResponse, error) {
var err error
const operationName = "DiskEncryptionSetsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, diskEncryptionSetName, options)
if err != nil {
return DiskEncryptionSetsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return DiskEncryptionSetsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return DiskEncryptionSetsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *DiskEncryptionSetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskEncryptionSetName == "" {
return nil, errors.New("parameter diskEncryptionSetName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskEncryptionSetName}", url.PathEscape(diskEncryptionSetName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *DiskEncryptionSetsClient) getHandleResponse(resp *http.Response) (DiskEncryptionSetsClientGetResponse, error) {
result := DiskEncryptionSetsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DiskEncryptionSet); err != nil {
return DiskEncryptionSetsClientGetResponse{}, err
}
return result, nil
}
// NewListPager - Lists all the disk encryption sets under a subscription.
//
// Generated from API version 2023-04-02
// - options - DiskEncryptionSetsClientListOptions contains the optional parameters for the DiskEncryptionSetsClient.NewListPager
// method.
func (client *DiskEncryptionSetsClient) NewListPager(options *DiskEncryptionSetsClientListOptions) *runtime.Pager[DiskEncryptionSetsClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[DiskEncryptionSetsClientListResponse]{
More: func(page DiskEncryptionSetsClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *DiskEncryptionSetsClientListResponse) (DiskEncryptionSetsClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskEncryptionSetsClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, options)
}, nil)
if err != nil {
return DiskEncryptionSetsClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *DiskEncryptionSetsClient) listCreateRequest(ctx context.Context, options *DiskEncryptionSetsClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/diskEncryptionSets"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *DiskEncryptionSetsClient) listHandleResponse(resp *http.Response) (DiskEncryptionSetsClientListResponse, error) {
result := DiskEncryptionSetsClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DiskEncryptionSetList); err != nil {
return DiskEncryptionSetsClientListResponse{}, err
}
return result, nil
}
// NewListAssociatedResourcesPager - Lists all resources that are encrypted with this disk encryption set.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the
// disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum
// name length is 80 characters.
// - options - DiskEncryptionSetsClientListAssociatedResourcesOptions contains the optional parameters for the DiskEncryptionSetsClient.NewListAssociatedResourcesPager
// method.
func (client *DiskEncryptionSetsClient) NewListAssociatedResourcesPager(resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientListAssociatedResourcesOptions) *runtime.Pager[DiskEncryptionSetsClientListAssociatedResourcesResponse] {
return runtime.NewPager(runtime.PagingHandler[DiskEncryptionSetsClientListAssociatedResourcesResponse]{
More: func(page DiskEncryptionSetsClientListAssociatedResourcesResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *DiskEncryptionSetsClientListAssociatedResourcesResponse) (DiskEncryptionSetsClientListAssociatedResourcesResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskEncryptionSetsClient.NewListAssociatedResourcesPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listAssociatedResourcesCreateRequest(ctx, resourceGroupName, diskEncryptionSetName, options)
}, nil)
if err != nil {
return DiskEncryptionSetsClientListAssociatedResourcesResponse{}, err
}
return client.listAssociatedResourcesHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listAssociatedResourcesCreateRequest creates the ListAssociatedResources request.
func (client *DiskEncryptionSetsClient) listAssociatedResourcesCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientListAssociatedResourcesOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}/associatedResources"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskEncryptionSetName == "" {
return nil, errors.New("parameter diskEncryptionSetName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskEncryptionSetName}", url.PathEscape(diskEncryptionSetName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listAssociatedResourcesHandleResponse handles the ListAssociatedResources response.
func (client *DiskEncryptionSetsClient) listAssociatedResourcesHandleResponse(resp *http.Response) (DiskEncryptionSetsClientListAssociatedResourcesResponse, error) {
result := DiskEncryptionSetsClientListAssociatedResourcesResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.ResourceURIList); err != nil {
return DiskEncryptionSetsClientListAssociatedResourcesResponse{}, err
}
return result, nil
}
// NewListByResourceGroupPager - Lists all the disk encryption sets under a resource group.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - options - DiskEncryptionSetsClientListByResourceGroupOptions contains the optional parameters for the DiskEncryptionSetsClient.NewListByResourceGroupPager
// method.
func (client *DiskEncryptionSetsClient) NewListByResourceGroupPager(resourceGroupName string, options *DiskEncryptionSetsClientListByResourceGroupOptions) *runtime.Pager[DiskEncryptionSetsClientListByResourceGroupResponse] {
return runtime.NewPager(runtime.PagingHandler[DiskEncryptionSetsClientListByResourceGroupResponse]{
More: func(page DiskEncryptionSetsClientListByResourceGroupResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *DiskEncryptionSetsClientListByResourceGroupResponse) (DiskEncryptionSetsClientListByResourceGroupResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskEncryptionSetsClient.NewListByResourceGroupPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options)
}, nil)
if err != nil {
return DiskEncryptionSetsClientListByResourceGroupResponse{}, err
}
return client.listByResourceGroupHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *DiskEncryptionSetsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *DiskEncryptionSetsClientListByResourceGroupOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *DiskEncryptionSetsClient) listByResourceGroupHandleResponse(resp *http.Response) (DiskEncryptionSetsClientListByResourceGroupResponse, error) {
result := DiskEncryptionSetsClientListByResourceGroupResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DiskEncryptionSetList); err != nil {
return DiskEncryptionSetsClientListByResourceGroupResponse{}, err
}
return result, nil
}
// BeginUpdate - Updates (patches) a disk encryption set.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the
// disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum
// name length is 80 characters.
// - diskEncryptionSet - disk encryption set object supplied in the body of the Patch disk encryption set operation.
// - options - DiskEncryptionSetsClientBeginUpdateOptions contains the optional parameters for the DiskEncryptionSetsClient.BeginUpdate
// method.
func (client *DiskEncryptionSetsClient) BeginUpdate(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSetUpdate, options *DiskEncryptionSetsClientBeginUpdateOptions) (*runtime.Poller[DiskEncryptionSetsClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, diskEncryptionSetName, diskEncryptionSet, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskEncryptionSetsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskEncryptionSetsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - Updates (patches) a disk encryption set.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DiskEncryptionSetsClient) update(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSetUpdate, options *DiskEncryptionSetsClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "DiskEncryptionSetsClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, diskEncryptionSetName, diskEncryptionSet, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *DiskEncryptionSetsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSetUpdate, options *DiskEncryptionSetsClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskEncryptionSetName == "" {
return nil, errors.New("parameter diskEncryptionSetName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskEncryptionSetName}", url.PathEscape(diskEncryptionSetName))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, diskEncryptionSet); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,367 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// DiskRestorePointClient contains the methods for the DiskRestorePoint group.
// Don't use this type directly, use NewDiskRestorePointClient() instead.
type DiskRestorePointClient struct {
internal *arm.Client
subscriptionID string
}
// NewDiskRestorePointClient creates a new instance of DiskRestorePointClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewDiskRestorePointClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DiskRestorePointClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &DiskRestorePointClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// Get - Get disk restorePoint resource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - restorePointCollectionName - The name of the restore point collection that the disk restore point belongs.
// - vmRestorePointName - The name of the vm restore point that the disk disk restore point belongs.
// - diskRestorePointName - The name of the disk restore point created.
// - options - DiskRestorePointClientGetOptions contains the optional parameters for the DiskRestorePointClient.Get method.
func (client *DiskRestorePointClient) Get(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, options *DiskRestorePointClientGetOptions) (DiskRestorePointClientGetResponse, error) {
var err error
const operationName = "DiskRestorePointClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, restorePointCollectionName, vmRestorePointName, diskRestorePointName, options)
if err != nil {
return DiskRestorePointClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return DiskRestorePointClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return DiskRestorePointClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *DiskRestorePointClient) getCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, options *DiskRestorePointClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{vmRestorePointName}/diskRestorePoints/{diskRestorePointName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if restorePointCollectionName == "" {
return nil, errors.New("parameter restorePointCollectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName))
if vmRestorePointName == "" {
return nil, errors.New("parameter vmRestorePointName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{vmRestorePointName}", url.PathEscape(vmRestorePointName))
if diskRestorePointName == "" {
return nil, errors.New("parameter diskRestorePointName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskRestorePointName}", url.PathEscape(diskRestorePointName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *DiskRestorePointClient) getHandleResponse(resp *http.Response) (DiskRestorePointClientGetResponse, error) {
result := DiskRestorePointClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DiskRestorePoint); err != nil {
return DiskRestorePointClientGetResponse{}, err
}
return result, nil
}
// BeginGrantAccess - Grants access to a diskRestorePoint.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - restorePointCollectionName - The name of the restore point collection that the disk restore point belongs.
// - vmRestorePointName - The name of the vm restore point that the disk disk restore point belongs.
// - diskRestorePointName - The name of the disk restore point created.
// - grantAccessData - Access data object supplied in the body of the get disk access operation.
// - options - DiskRestorePointClientBeginGrantAccessOptions contains the optional parameters for the DiskRestorePointClient.BeginGrantAccess
// method.
func (client *DiskRestorePointClient) BeginGrantAccess(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, grantAccessData GrantAccessData, options *DiskRestorePointClientBeginGrantAccessOptions) (*runtime.Poller[DiskRestorePointClientGrantAccessResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.grantAccess(ctx, resourceGroupName, restorePointCollectionName, vmRestorePointName, diskRestorePointName, grantAccessData, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskRestorePointClientGrantAccessResponse]{
FinalStateVia: runtime.FinalStateViaLocation,
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskRestorePointClientGrantAccessResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// GrantAccess - Grants access to a diskRestorePoint.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DiskRestorePointClient) grantAccess(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, grantAccessData GrantAccessData, options *DiskRestorePointClientBeginGrantAccessOptions) (*http.Response, error) {
var err error
const operationName = "DiskRestorePointClient.BeginGrantAccess"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.grantAccessCreateRequest(ctx, resourceGroupName, restorePointCollectionName, vmRestorePointName, diskRestorePointName, grantAccessData, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// grantAccessCreateRequest creates the GrantAccess request.
func (client *DiskRestorePointClient) grantAccessCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, grantAccessData GrantAccessData, options *DiskRestorePointClientBeginGrantAccessOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{vmRestorePointName}/diskRestorePoints/{diskRestorePointName}/beginGetAccess"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if restorePointCollectionName == "" {
return nil, errors.New("parameter restorePointCollectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName))
if vmRestorePointName == "" {
return nil, errors.New("parameter vmRestorePointName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{vmRestorePointName}", url.PathEscape(vmRestorePointName))
if diskRestorePointName == "" {
return nil, errors.New("parameter diskRestorePointName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskRestorePointName}", url.PathEscape(diskRestorePointName))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, grantAccessData); err != nil {
return nil, err
}
return req, nil
}
// NewListByRestorePointPager - Lists diskRestorePoints under a vmRestorePoint.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - restorePointCollectionName - The name of the restore point collection that the disk restore point belongs.
// - vmRestorePointName - The name of the vm restore point that the disk disk restore point belongs.
// - options - DiskRestorePointClientListByRestorePointOptions contains the optional parameters for the DiskRestorePointClient.NewListByRestorePointPager
// method.
func (client *DiskRestorePointClient) NewListByRestorePointPager(resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, options *DiskRestorePointClientListByRestorePointOptions) *runtime.Pager[DiskRestorePointClientListByRestorePointResponse] {
return runtime.NewPager(runtime.PagingHandler[DiskRestorePointClientListByRestorePointResponse]{
More: func(page DiskRestorePointClientListByRestorePointResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *DiskRestorePointClientListByRestorePointResponse) (DiskRestorePointClientListByRestorePointResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskRestorePointClient.NewListByRestorePointPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByRestorePointCreateRequest(ctx, resourceGroupName, restorePointCollectionName, vmRestorePointName, options)
}, nil)
if err != nil {
return DiskRestorePointClientListByRestorePointResponse{}, err
}
return client.listByRestorePointHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByRestorePointCreateRequest creates the ListByRestorePoint request.
func (client *DiskRestorePointClient) listByRestorePointCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, options *DiskRestorePointClientListByRestorePointOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{vmRestorePointName}/diskRestorePoints"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if restorePointCollectionName == "" {
return nil, errors.New("parameter restorePointCollectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName))
if vmRestorePointName == "" {
return nil, errors.New("parameter vmRestorePointName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{vmRestorePointName}", url.PathEscape(vmRestorePointName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByRestorePointHandleResponse handles the ListByRestorePoint response.
func (client *DiskRestorePointClient) listByRestorePointHandleResponse(resp *http.Response) (DiskRestorePointClientListByRestorePointResponse, error) {
result := DiskRestorePointClientListByRestorePointResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DiskRestorePointList); err != nil {
return DiskRestorePointClientListByRestorePointResponse{}, err
}
return result, nil
}
// BeginRevokeAccess - Revokes access to a diskRestorePoint.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - restorePointCollectionName - The name of the restore point collection that the disk restore point belongs.
// - vmRestorePointName - The name of the vm restore point that the disk disk restore point belongs.
// - diskRestorePointName - The name of the disk restore point created.
// - options - DiskRestorePointClientBeginRevokeAccessOptions contains the optional parameters for the DiskRestorePointClient.BeginRevokeAccess
// method.
func (client *DiskRestorePointClient) BeginRevokeAccess(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, options *DiskRestorePointClientBeginRevokeAccessOptions) (*runtime.Poller[DiskRestorePointClientRevokeAccessResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.revokeAccess(ctx, resourceGroupName, restorePointCollectionName, vmRestorePointName, diskRestorePointName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskRestorePointClientRevokeAccessResponse]{
FinalStateVia: runtime.FinalStateViaLocation,
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskRestorePointClientRevokeAccessResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// RevokeAccess - Revokes access to a diskRestorePoint.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DiskRestorePointClient) revokeAccess(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, options *DiskRestorePointClientBeginRevokeAccessOptions) (*http.Response, error) {
var err error
const operationName = "DiskRestorePointClient.BeginRevokeAccess"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.revokeAccessCreateRequest(ctx, resourceGroupName, restorePointCollectionName, vmRestorePointName, diskRestorePointName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// revokeAccessCreateRequest creates the RevokeAccess request.
func (client *DiskRestorePointClient) revokeAccessCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, options *DiskRestorePointClientBeginRevokeAccessOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{vmRestorePointName}/diskRestorePoints/{diskRestorePointName}/endGetAccess"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if restorePointCollectionName == "" {
return nil, errors.New("parameter restorePointCollectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName))
if vmRestorePointName == "" {
return nil, errors.New("parameter vmRestorePointName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{vmRestorePointName}", url.PathEscape(vmRestorePointName))
if diskRestorePointName == "" {
return nil, errors.New("parameter diskRestorePointName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskRestorePointName}", url.PathEscape(diskRestorePointName))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}

View file

@ -0,0 +1,623 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// DisksClient contains the methods for the Disks group.
// Don't use this type directly, use NewDisksClient() instead.
type DisksClient struct {
internal *arm.Client
subscriptionID string
}
// NewDisksClient creates a new instance of DisksClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewDisksClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DisksClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &DisksClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreateOrUpdate - Creates or updates a disk.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported
// characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80
// characters.
// - disk - Disk object supplied in the body of the Put disk operation.
// - options - DisksClientBeginCreateOrUpdateOptions contains the optional parameters for the DisksClient.BeginCreateOrUpdate
// method.
func (client *DisksClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, diskName string, disk Disk, options *DisksClientBeginCreateOrUpdateOptions) (*runtime.Poller[DisksClientCreateOrUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.createOrUpdate(ctx, resourceGroupName, diskName, disk, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DisksClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DisksClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// CreateOrUpdate - Creates or updates a disk.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DisksClient) createOrUpdate(ctx context.Context, resourceGroupName string, diskName string, disk Disk, options *DisksClientBeginCreateOrUpdateOptions) (*http.Response, error) {
var err error
const operationName = "DisksClient.BeginCreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, diskName, disk, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *DisksClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, diskName string, disk Disk, options *DisksClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskName == "" {
return nil, errors.New("parameter diskName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, disk); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - Deletes a disk.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported
// characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80
// characters.
// - options - DisksClientBeginDeleteOptions contains the optional parameters for the DisksClient.BeginDelete method.
func (client *DisksClient) BeginDelete(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginDeleteOptions) (*runtime.Poller[DisksClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, diskName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DisksClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DisksClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - Deletes a disk.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DisksClient) deleteOperation(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "DisksClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, diskName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *DisksClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskName == "" {
return nil, errors.New("parameter diskName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
return req, nil
}
// Get - Gets information about a disk.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported
// characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80
// characters.
// - options - DisksClientGetOptions contains the optional parameters for the DisksClient.Get method.
func (client *DisksClient) Get(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientGetOptions) (DisksClientGetResponse, error) {
var err error
const operationName = "DisksClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, diskName, options)
if err != nil {
return DisksClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return DisksClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return DisksClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *DisksClient) getCreateRequest(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskName == "" {
return nil, errors.New("parameter diskName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *DisksClient) getHandleResponse(resp *http.Response) (DisksClientGetResponse, error) {
result := DisksClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.Disk); err != nil {
return DisksClientGetResponse{}, err
}
return result, nil
}
// BeginGrantAccess - Grants access to a disk.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported
// characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80
// characters.
// - grantAccessData - Access data object supplied in the body of the get disk access operation.
// - options - DisksClientBeginGrantAccessOptions contains the optional parameters for the DisksClient.BeginGrantAccess method.
func (client *DisksClient) BeginGrantAccess(ctx context.Context, resourceGroupName string, diskName string, grantAccessData GrantAccessData, options *DisksClientBeginGrantAccessOptions) (*runtime.Poller[DisksClientGrantAccessResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.grantAccess(ctx, resourceGroupName, diskName, grantAccessData, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DisksClientGrantAccessResponse]{
FinalStateVia: runtime.FinalStateViaLocation,
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DisksClientGrantAccessResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// GrantAccess - Grants access to a disk.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DisksClient) grantAccess(ctx context.Context, resourceGroupName string, diskName string, grantAccessData GrantAccessData, options *DisksClientBeginGrantAccessOptions) (*http.Response, error) {
var err error
const operationName = "DisksClient.BeginGrantAccess"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.grantAccessCreateRequest(ctx, resourceGroupName, diskName, grantAccessData, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// grantAccessCreateRequest creates the GrantAccess request.
func (client *DisksClient) grantAccessCreateRequest(ctx context.Context, resourceGroupName string, diskName string, grantAccessData GrantAccessData, options *DisksClientBeginGrantAccessOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}/beginGetAccess"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskName == "" {
return nil, errors.New("parameter diskName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, grantAccessData); err != nil {
return nil, err
}
return req, nil
}
// NewListPager - Lists all the disks under a subscription.
//
// Generated from API version 2023-04-02
// - options - DisksClientListOptions contains the optional parameters for the DisksClient.NewListPager method.
func (client *DisksClient) NewListPager(options *DisksClientListOptions) *runtime.Pager[DisksClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[DisksClientListResponse]{
More: func(page DisksClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *DisksClientListResponse) (DisksClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DisksClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, options)
}, nil)
if err != nil {
return DisksClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *DisksClient) listCreateRequest(ctx context.Context, options *DisksClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/disks"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *DisksClient) listHandleResponse(resp *http.Response) (DisksClientListResponse, error) {
result := DisksClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DiskList); err != nil {
return DisksClientListResponse{}, err
}
return result, nil
}
// NewListByResourceGroupPager - Lists all the disks under a resource group.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - options - DisksClientListByResourceGroupOptions contains the optional parameters for the DisksClient.NewListByResourceGroupPager
// method.
func (client *DisksClient) NewListByResourceGroupPager(resourceGroupName string, options *DisksClientListByResourceGroupOptions) *runtime.Pager[DisksClientListByResourceGroupResponse] {
return runtime.NewPager(runtime.PagingHandler[DisksClientListByResourceGroupResponse]{
More: func(page DisksClientListByResourceGroupResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *DisksClientListByResourceGroupResponse) (DisksClientListByResourceGroupResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DisksClient.NewListByResourceGroupPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options)
}, nil)
if err != nil {
return DisksClientListByResourceGroupResponse{}, err
}
return client.listByResourceGroupHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *DisksClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *DisksClientListByResourceGroupOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *DisksClient) listByResourceGroupHandleResponse(resp *http.Response) (DisksClientListByResourceGroupResponse, error) {
result := DisksClientListByResourceGroupResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.DiskList); err != nil {
return DisksClientListByResourceGroupResponse{}, err
}
return result, nil
}
// BeginRevokeAccess - Revokes access to a disk.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported
// characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80
// characters.
// - options - DisksClientBeginRevokeAccessOptions contains the optional parameters for the DisksClient.BeginRevokeAccess method.
func (client *DisksClient) BeginRevokeAccess(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginRevokeAccessOptions) (*runtime.Poller[DisksClientRevokeAccessResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.revokeAccess(ctx, resourceGroupName, diskName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DisksClientRevokeAccessResponse]{
FinalStateVia: runtime.FinalStateViaLocation,
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DisksClientRevokeAccessResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// RevokeAccess - Revokes access to a disk.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DisksClient) revokeAccess(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginRevokeAccessOptions) (*http.Response, error) {
var err error
const operationName = "DisksClient.BeginRevokeAccess"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.revokeAccessCreateRequest(ctx, resourceGroupName, diskName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// revokeAccessCreateRequest creates the RevokeAccess request.
func (client *DisksClient) revokeAccessCreateRequest(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginRevokeAccessOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}/endGetAccess"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskName == "" {
return nil, errors.New("parameter diskName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
return req, nil
}
// BeginUpdate - Updates (patches) a disk.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported
// characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80
// characters.
// - disk - Disk object supplied in the body of the Patch disk operation.
// - options - DisksClientBeginUpdateOptions contains the optional parameters for the DisksClient.BeginUpdate method.
func (client *DisksClient) BeginUpdate(ctx context.Context, resourceGroupName string, diskName string, disk DiskUpdate, options *DisksClientBeginUpdateOptions) (*runtime.Poller[DisksClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, diskName, disk, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DisksClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DisksClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - Updates (patches) a disk.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *DisksClient) update(ctx context.Context, resourceGroupName string, diskName string, disk DiskUpdate, options *DisksClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "DisksClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, diskName, disk, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *DisksClient) updateCreateRequest(ctx context.Context, resourceGroupName string, diskName string, disk DiskUpdate, options *DisksClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if diskName == "" {
return nil, errors.New("parameter diskName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, disk); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,465 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// GalleriesClient contains the methods for the Galleries group.
// Don't use this type directly, use NewGalleriesClient() instead.
type GalleriesClient struct {
internal *arm.Client
subscriptionID string
}
// NewGalleriesClient creates a new instance of GalleriesClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewGalleriesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GalleriesClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &GalleriesClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreateOrUpdate - Create or update a Shared Image Gallery.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery. The allowed characters are alphabets and numbers with dots and periods
// allowed in the middle. The maximum length is 80 characters.
// - gallery - Parameters supplied to the create or update Shared Image Gallery operation.
// - options - GalleriesClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleriesClient.BeginCreateOrUpdate
// method.
func (client *GalleriesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, gallery Gallery, options *GalleriesClientBeginCreateOrUpdateOptions) (*runtime.Poller[GalleriesClientCreateOrUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.createOrUpdate(ctx, resourceGroupName, galleryName, gallery, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleriesClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleriesClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// CreateOrUpdate - Create or update a Shared Image Gallery.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleriesClient) createOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, gallery Gallery, options *GalleriesClientBeginCreateOrUpdateOptions) (*http.Response, error) {
var err error
const operationName = "GalleriesClient.BeginCreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, galleryName, gallery, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *GalleriesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, gallery Gallery, options *GalleriesClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, gallery); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - Delete a Shared Image Gallery.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery to be deleted.
// - options - GalleriesClientBeginDeleteOptions contains the optional parameters for the GalleriesClient.BeginDelete method.
func (client *GalleriesClient) BeginDelete(ctx context.Context, resourceGroupName string, galleryName string, options *GalleriesClientBeginDeleteOptions) (*runtime.Poller[GalleriesClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, galleryName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleriesClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleriesClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - Delete a Shared Image Gallery.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleriesClient) deleteOperation(ctx context.Context, resourceGroupName string, galleryName string, options *GalleriesClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "GalleriesClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, galleryName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *GalleriesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, options *GalleriesClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - Retrieves information about a Shared Image Gallery.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery.
// - options - GalleriesClientGetOptions contains the optional parameters for the GalleriesClient.Get method.
func (client *GalleriesClient) Get(ctx context.Context, resourceGroupName string, galleryName string, options *GalleriesClientGetOptions) (GalleriesClientGetResponse, error) {
var err error
const operationName = "GalleriesClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, galleryName, options)
if err != nil {
return GalleriesClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return GalleriesClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return GalleriesClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *GalleriesClient) getCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, options *GalleriesClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
if options != nil && options.Select != nil {
reqQP.Set("$select", string(*options.Select))
}
if options != nil && options.Expand != nil {
reqQP.Set("$expand", string(*options.Expand))
}
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *GalleriesClient) getHandleResponse(resp *http.Response) (GalleriesClientGetResponse, error) {
result := GalleriesClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.Gallery); err != nil {
return GalleriesClientGetResponse{}, err
}
return result, nil
}
// NewListPager - List galleries under a subscription.
//
// Generated from API version 2022-03-03
// - options - GalleriesClientListOptions contains the optional parameters for the GalleriesClient.NewListPager method.
func (client *GalleriesClient) NewListPager(options *GalleriesClientListOptions) *runtime.Pager[GalleriesClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[GalleriesClientListResponse]{
More: func(page GalleriesClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *GalleriesClientListResponse) (GalleriesClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GalleriesClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, options)
}, nil)
if err != nil {
return GalleriesClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *GalleriesClient) listCreateRequest(ctx context.Context, options *GalleriesClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/galleries"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *GalleriesClient) listHandleResponse(resp *http.Response) (GalleriesClientListResponse, error) {
result := GalleriesClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.GalleryList); err != nil {
return GalleriesClientListResponse{}, err
}
return result, nil
}
// NewListByResourceGroupPager - List galleries under a resource group.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - options - GalleriesClientListByResourceGroupOptions contains the optional parameters for the GalleriesClient.NewListByResourceGroupPager
// method.
func (client *GalleriesClient) NewListByResourceGroupPager(resourceGroupName string, options *GalleriesClientListByResourceGroupOptions) *runtime.Pager[GalleriesClientListByResourceGroupResponse] {
return runtime.NewPager(runtime.PagingHandler[GalleriesClientListByResourceGroupResponse]{
More: func(page GalleriesClientListByResourceGroupResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *GalleriesClientListByResourceGroupResponse) (GalleriesClientListByResourceGroupResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GalleriesClient.NewListByResourceGroupPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options)
}, nil)
if err != nil {
return GalleriesClientListByResourceGroupResponse{}, err
}
return client.listByResourceGroupHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *GalleriesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *GalleriesClientListByResourceGroupOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *GalleriesClient) listByResourceGroupHandleResponse(resp *http.Response) (GalleriesClientListByResourceGroupResponse, error) {
result := GalleriesClientListByResourceGroupResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.GalleryList); err != nil {
return GalleriesClientListByResourceGroupResponse{}, err
}
return result, nil
}
// BeginUpdate - Update a Shared Image Gallery.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery. The allowed characters are alphabets and numbers with dots and periods
// allowed in the middle. The maximum length is 80 characters.
// - gallery - Parameters supplied to the update Shared Image Gallery operation.
// - options - GalleriesClientBeginUpdateOptions contains the optional parameters for the GalleriesClient.BeginUpdate method.
func (client *GalleriesClient) BeginUpdate(ctx context.Context, resourceGroupName string, galleryName string, gallery GalleryUpdate, options *GalleriesClientBeginUpdateOptions) (*runtime.Poller[GalleriesClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, galleryName, gallery, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleriesClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleriesClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - Update a Shared Image Gallery.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleriesClient) update(ctx context.Context, resourceGroupName string, galleryName string, gallery GalleryUpdate, options *GalleriesClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "GalleriesClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, galleryName, gallery, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *GalleriesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, gallery GalleryUpdate, options *GalleriesClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, gallery); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,434 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// GalleryApplicationsClient contains the methods for the GalleryApplications group.
// Don't use this type directly, use NewGalleryApplicationsClient() instead.
type GalleryApplicationsClient struct {
internal *arm.Client
subscriptionID string
}
// NewGalleryApplicationsClient creates a new instance of GalleryApplicationsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewGalleryApplicationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GalleryApplicationsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &GalleryApplicationsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreateOrUpdate - Create or update a gallery Application Definition.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Application Gallery in which the Application Definition is to be created.
// - galleryApplicationName - The name of the gallery Application Definition to be created or updated. The allowed characters
// are alphabets and numbers with dots, dashes, and periods allowed in the middle. The maximum length is 80
// characters.
// - galleryApplication - Parameters supplied to the create or update gallery Application operation.
// - options - GalleryApplicationsClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleryApplicationsClient.BeginCreateOrUpdate
// method.
func (client *GalleryApplicationsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplication GalleryApplication, options *GalleryApplicationsClientBeginCreateOrUpdateOptions) (*runtime.Poller[GalleryApplicationsClientCreateOrUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.createOrUpdate(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplication, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryApplicationsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryApplicationsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// CreateOrUpdate - Create or update a gallery Application Definition.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleryApplicationsClient) createOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplication GalleryApplication, options *GalleryApplicationsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
var err error
const operationName = "GalleryApplicationsClient.BeginCreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplication, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *GalleryApplicationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplication GalleryApplication, options *GalleryApplicationsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryApplicationName == "" {
return nil, errors.New("parameter galleryApplicationName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, galleryApplication); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - Delete a gallery Application.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Application Gallery in which the Application Definition is to be deleted.
// - galleryApplicationName - The name of the gallery Application Definition to be deleted.
// - options - GalleryApplicationsClientBeginDeleteOptions contains the optional parameters for the GalleryApplicationsClient.BeginDelete
// method.
func (client *GalleryApplicationsClient) BeginDelete(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationsClientBeginDeleteOptions) (*runtime.Poller[GalleryApplicationsClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, galleryName, galleryApplicationName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryApplicationsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryApplicationsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - Delete a gallery Application.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleryApplicationsClient) deleteOperation(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationsClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "GalleryApplicationsClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, galleryName, galleryApplicationName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *GalleryApplicationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationsClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryApplicationName == "" {
return nil, errors.New("parameter galleryApplicationName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - Retrieves information about a gallery Application Definition.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Application Gallery from which the Application Definitions are to be retrieved.
// - galleryApplicationName - The name of the gallery Application Definition to be retrieved.
// - options - GalleryApplicationsClientGetOptions contains the optional parameters for the GalleryApplicationsClient.Get method.
func (client *GalleryApplicationsClient) Get(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationsClientGetOptions) (GalleryApplicationsClientGetResponse, error) {
var err error
const operationName = "GalleryApplicationsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, galleryName, galleryApplicationName, options)
if err != nil {
return GalleryApplicationsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return GalleryApplicationsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return GalleryApplicationsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *GalleryApplicationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryApplicationName == "" {
return nil, errors.New("parameter galleryApplicationName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *GalleryApplicationsClient) getHandleResponse(resp *http.Response) (GalleryApplicationsClientGetResponse, error) {
result := GalleryApplicationsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.GalleryApplication); err != nil {
return GalleryApplicationsClientGetResponse{}, err
}
return result, nil
}
// NewListByGalleryPager - List gallery Application Definitions in a gallery.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Application Gallery from which Application Definitions are to be listed.
// - options - GalleryApplicationsClientListByGalleryOptions contains the optional parameters for the GalleryApplicationsClient.NewListByGalleryPager
// method.
func (client *GalleryApplicationsClient) NewListByGalleryPager(resourceGroupName string, galleryName string, options *GalleryApplicationsClientListByGalleryOptions) *runtime.Pager[GalleryApplicationsClientListByGalleryResponse] {
return runtime.NewPager(runtime.PagingHandler[GalleryApplicationsClientListByGalleryResponse]{
More: func(page GalleryApplicationsClientListByGalleryResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *GalleryApplicationsClientListByGalleryResponse) (GalleryApplicationsClientListByGalleryResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GalleryApplicationsClient.NewListByGalleryPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByGalleryCreateRequest(ctx, resourceGroupName, galleryName, options)
}, nil)
if err != nil {
return GalleryApplicationsClientListByGalleryResponse{}, err
}
return client.listByGalleryHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByGalleryCreateRequest creates the ListByGallery request.
func (client *GalleryApplicationsClient) listByGalleryCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, options *GalleryApplicationsClientListByGalleryOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByGalleryHandleResponse handles the ListByGallery response.
func (client *GalleryApplicationsClient) listByGalleryHandleResponse(resp *http.Response) (GalleryApplicationsClientListByGalleryResponse, error) {
result := GalleryApplicationsClientListByGalleryResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.GalleryApplicationList); err != nil {
return GalleryApplicationsClientListByGalleryResponse{}, err
}
return result, nil
}
// BeginUpdate - Update a gallery Application Definition.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Application Gallery in which the Application Definition is to be updated.
// - galleryApplicationName - The name of the gallery Application Definition to be updated. The allowed characters are alphabets
// and numbers with dots, dashes, and periods allowed in the middle. The maximum length is 80
// characters.
// - galleryApplication - Parameters supplied to the update gallery Application operation.
// - options - GalleryApplicationsClientBeginUpdateOptions contains the optional parameters for the GalleryApplicationsClient.BeginUpdate
// method.
func (client *GalleryApplicationsClient) BeginUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplication GalleryApplicationUpdate, options *GalleryApplicationsClientBeginUpdateOptions) (*runtime.Poller[GalleryApplicationsClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplication, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryApplicationsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryApplicationsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - Update a gallery Application Definition.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleryApplicationsClient) update(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplication GalleryApplicationUpdate, options *GalleryApplicationsClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "GalleryApplicationsClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplication, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *GalleryApplicationsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplication GalleryApplicationUpdate, options *GalleryApplicationsClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryApplicationName == "" {
return nil, errors.New("parameter galleryApplicationName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, galleryApplication); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,464 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// GalleryApplicationVersionsClient contains the methods for the GalleryApplicationVersions group.
// Don't use this type directly, use NewGalleryApplicationVersionsClient() instead.
type GalleryApplicationVersionsClient struct {
internal *arm.Client
subscriptionID string
}
// NewGalleryApplicationVersionsClient creates a new instance of GalleryApplicationVersionsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewGalleryApplicationVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GalleryApplicationVersionsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &GalleryApplicationVersionsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreateOrUpdate - Create or update a gallery Application Version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Application Gallery in which the Application Definition resides.
// - galleryApplicationName - The name of the gallery Application Definition in which the Application Version is to be created.
// - galleryApplicationVersionName - The name of the gallery Application Version to be created. Needs to follow semantic version
// name pattern: The allowed characters are digit and period. Digits must be within the range of a 32-bit
// integer. Format: ..
// - galleryApplicationVersion - Parameters supplied to the create or update gallery Application Version operation.
// - options - GalleryApplicationVersionsClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleryApplicationVersionsClient.BeginCreateOrUpdate
// method.
func (client *GalleryApplicationVersionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, galleryApplicationVersion GalleryApplicationVersion, options *GalleryApplicationVersionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[GalleryApplicationVersionsClientCreateOrUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.createOrUpdate(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplicationVersionName, galleryApplicationVersion, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryApplicationVersionsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryApplicationVersionsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// CreateOrUpdate - Create or update a gallery Application Version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleryApplicationVersionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, galleryApplicationVersion GalleryApplicationVersion, options *GalleryApplicationVersionsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
var err error
const operationName = "GalleryApplicationVersionsClient.BeginCreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplicationVersionName, galleryApplicationVersion, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *GalleryApplicationVersionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, galleryApplicationVersion GalleryApplicationVersion, options *GalleryApplicationVersionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}/versions/{galleryApplicationVersionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryApplicationName == "" {
return nil, errors.New("parameter galleryApplicationName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName))
if galleryApplicationVersionName == "" {
return nil, errors.New("parameter galleryApplicationVersionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationVersionName}", url.PathEscape(galleryApplicationVersionName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, galleryApplicationVersion); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - Delete a gallery Application Version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Application Gallery in which the Application Definition resides.
// - galleryApplicationName - The name of the gallery Application Definition in which the Application Version resides.
// - galleryApplicationVersionName - The name of the gallery Application Version to be deleted.
// - options - GalleryApplicationVersionsClientBeginDeleteOptions contains the optional parameters for the GalleryApplicationVersionsClient.BeginDelete
// method.
func (client *GalleryApplicationVersionsClient) BeginDelete(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, options *GalleryApplicationVersionsClientBeginDeleteOptions) (*runtime.Poller[GalleryApplicationVersionsClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplicationVersionName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryApplicationVersionsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryApplicationVersionsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - Delete a gallery Application Version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleryApplicationVersionsClient) deleteOperation(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, options *GalleryApplicationVersionsClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "GalleryApplicationVersionsClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplicationVersionName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *GalleryApplicationVersionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, options *GalleryApplicationVersionsClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}/versions/{galleryApplicationVersionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryApplicationName == "" {
return nil, errors.New("parameter galleryApplicationName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName))
if galleryApplicationVersionName == "" {
return nil, errors.New("parameter galleryApplicationVersionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationVersionName}", url.PathEscape(galleryApplicationVersionName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - Retrieves information about a gallery Application Version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Application Gallery in which the Application Definition resides.
// - galleryApplicationName - The name of the gallery Application Definition in which the Application Version resides.
// - galleryApplicationVersionName - The name of the gallery Application Version to be retrieved.
// - options - GalleryApplicationVersionsClientGetOptions contains the optional parameters for the GalleryApplicationVersionsClient.Get
// method.
func (client *GalleryApplicationVersionsClient) Get(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, options *GalleryApplicationVersionsClientGetOptions) (GalleryApplicationVersionsClientGetResponse, error) {
var err error
const operationName = "GalleryApplicationVersionsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplicationVersionName, options)
if err != nil {
return GalleryApplicationVersionsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return GalleryApplicationVersionsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return GalleryApplicationVersionsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *GalleryApplicationVersionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, options *GalleryApplicationVersionsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}/versions/{galleryApplicationVersionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryApplicationName == "" {
return nil, errors.New("parameter galleryApplicationName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName))
if galleryApplicationVersionName == "" {
return nil, errors.New("parameter galleryApplicationVersionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationVersionName}", url.PathEscape(galleryApplicationVersionName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
if options != nil && options.Expand != nil {
reqQP.Set("$expand", string(*options.Expand))
}
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *GalleryApplicationVersionsClient) getHandleResponse(resp *http.Response) (GalleryApplicationVersionsClientGetResponse, error) {
result := GalleryApplicationVersionsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.GalleryApplicationVersion); err != nil {
return GalleryApplicationVersionsClientGetResponse{}, err
}
return result, nil
}
// NewListByGalleryApplicationPager - List gallery Application Versions in a gallery Application Definition.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Application Gallery in which the Application Definition resides.
// - galleryApplicationName - The name of the Shared Application Gallery Application Definition from which the Application Versions
// are to be listed.
// - options - GalleryApplicationVersionsClientListByGalleryApplicationOptions contains the optional parameters for the GalleryApplicationVersionsClient.NewListByGalleryApplicationPager
// method.
func (client *GalleryApplicationVersionsClient) NewListByGalleryApplicationPager(resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationVersionsClientListByGalleryApplicationOptions) *runtime.Pager[GalleryApplicationVersionsClientListByGalleryApplicationResponse] {
return runtime.NewPager(runtime.PagingHandler[GalleryApplicationVersionsClientListByGalleryApplicationResponse]{
More: func(page GalleryApplicationVersionsClientListByGalleryApplicationResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *GalleryApplicationVersionsClientListByGalleryApplicationResponse) (GalleryApplicationVersionsClientListByGalleryApplicationResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GalleryApplicationVersionsClient.NewListByGalleryApplicationPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByGalleryApplicationCreateRequest(ctx, resourceGroupName, galleryName, galleryApplicationName, options)
}, nil)
if err != nil {
return GalleryApplicationVersionsClientListByGalleryApplicationResponse{}, err
}
return client.listByGalleryApplicationHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByGalleryApplicationCreateRequest creates the ListByGalleryApplication request.
func (client *GalleryApplicationVersionsClient) listByGalleryApplicationCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationVersionsClientListByGalleryApplicationOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}/versions"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryApplicationName == "" {
return nil, errors.New("parameter galleryApplicationName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByGalleryApplicationHandleResponse handles the ListByGalleryApplication response.
func (client *GalleryApplicationVersionsClient) listByGalleryApplicationHandleResponse(resp *http.Response) (GalleryApplicationVersionsClientListByGalleryApplicationResponse, error) {
result := GalleryApplicationVersionsClientListByGalleryApplicationResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.GalleryApplicationVersionList); err != nil {
return GalleryApplicationVersionsClientListByGalleryApplicationResponse{}, err
}
return result, nil
}
// BeginUpdate - Update a gallery Application Version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Application Gallery in which the Application Definition resides.
// - galleryApplicationName - The name of the gallery Application Definition in which the Application Version is to be updated.
// - galleryApplicationVersionName - The name of the gallery Application Version to be updated. Needs to follow semantic version
// name pattern: The allowed characters are digit and period. Digits must be within the range of a 32-bit
// integer. Format: ..
// - galleryApplicationVersion - Parameters supplied to the update gallery Application Version operation.
// - options - GalleryApplicationVersionsClientBeginUpdateOptions contains the optional parameters for the GalleryApplicationVersionsClient.BeginUpdate
// method.
func (client *GalleryApplicationVersionsClient) BeginUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, galleryApplicationVersion GalleryApplicationVersionUpdate, options *GalleryApplicationVersionsClientBeginUpdateOptions) (*runtime.Poller[GalleryApplicationVersionsClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplicationVersionName, galleryApplicationVersion, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryApplicationVersionsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryApplicationVersionsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - Update a gallery Application Version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleryApplicationVersionsClient) update(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, galleryApplicationVersion GalleryApplicationVersionUpdate, options *GalleryApplicationVersionsClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "GalleryApplicationVersionsClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplicationVersionName, galleryApplicationVersion, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *GalleryApplicationVersionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, galleryApplicationVersion GalleryApplicationVersionUpdate, options *GalleryApplicationVersionsClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}/versions/{galleryApplicationVersionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryApplicationName == "" {
return nil, errors.New("parameter galleryApplicationName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName))
if galleryApplicationVersionName == "" {
return nil, errors.New("parameter galleryApplicationVersionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationVersionName}", url.PathEscape(galleryApplicationVersionName))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, galleryApplicationVersion); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,433 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// GalleryImagesClient contains the methods for the GalleryImages group.
// Don't use this type directly, use NewGalleryImagesClient() instead.
type GalleryImagesClient struct {
internal *arm.Client
subscriptionID string
}
// NewGalleryImagesClient creates a new instance of GalleryImagesClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewGalleryImagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GalleryImagesClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &GalleryImagesClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreateOrUpdate - Create or update a gallery image definition.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery in which the Image Definition is to be created.
// - galleryImageName - The name of the gallery image definition to be created or updated. The allowed characters are alphabets
// and numbers with dots, dashes, and periods allowed in the middle. The maximum length is 80
// characters.
// - galleryImage - Parameters supplied to the create or update gallery image operation.
// - options - GalleryImagesClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleryImagesClient.BeginCreateOrUpdate
// method.
func (client *GalleryImagesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImage, options *GalleryImagesClientBeginCreateOrUpdateOptions) (*runtime.Poller[GalleryImagesClientCreateOrUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.createOrUpdate(ctx, resourceGroupName, galleryName, galleryImageName, galleryImage, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryImagesClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryImagesClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// CreateOrUpdate - Create or update a gallery image definition.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleryImagesClient) createOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImage, options *GalleryImagesClientBeginCreateOrUpdateOptions) (*http.Response, error) {
var err error
const operationName = "GalleryImagesClient.BeginCreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, galleryName, galleryImageName, galleryImage, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *GalleryImagesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImage, options *GalleryImagesClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, galleryImage); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - Delete a gallery image.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery in which the Image Definition is to be deleted.
// - galleryImageName - The name of the gallery image definition to be deleted.
// - options - GalleryImagesClientBeginDeleteOptions contains the optional parameters for the GalleryImagesClient.BeginDelete
// method.
func (client *GalleryImagesClient) BeginDelete(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImagesClientBeginDeleteOptions) (*runtime.Poller[GalleryImagesClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, galleryName, galleryImageName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryImagesClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryImagesClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - Delete a gallery image.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleryImagesClient) deleteOperation(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImagesClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "GalleryImagesClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, galleryName, galleryImageName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *GalleryImagesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImagesClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - Retrieves information about a gallery image definition.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery from which the Image Definitions are to be retrieved.
// - galleryImageName - The name of the gallery image definition to be retrieved.
// - options - GalleryImagesClientGetOptions contains the optional parameters for the GalleryImagesClient.Get method.
func (client *GalleryImagesClient) Get(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImagesClientGetOptions) (GalleryImagesClientGetResponse, error) {
var err error
const operationName = "GalleryImagesClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, galleryName, galleryImageName, options)
if err != nil {
return GalleryImagesClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return GalleryImagesClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return GalleryImagesClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *GalleryImagesClient) getCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImagesClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *GalleryImagesClient) getHandleResponse(resp *http.Response) (GalleryImagesClientGetResponse, error) {
result := GalleryImagesClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.GalleryImage); err != nil {
return GalleryImagesClientGetResponse{}, err
}
return result, nil
}
// NewListByGalleryPager - List gallery image definitions in a gallery.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery from which Image Definitions are to be listed.
// - options - GalleryImagesClientListByGalleryOptions contains the optional parameters for the GalleryImagesClient.NewListByGalleryPager
// method.
func (client *GalleryImagesClient) NewListByGalleryPager(resourceGroupName string, galleryName string, options *GalleryImagesClientListByGalleryOptions) *runtime.Pager[GalleryImagesClientListByGalleryResponse] {
return runtime.NewPager(runtime.PagingHandler[GalleryImagesClientListByGalleryResponse]{
More: func(page GalleryImagesClientListByGalleryResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *GalleryImagesClientListByGalleryResponse) (GalleryImagesClientListByGalleryResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GalleryImagesClient.NewListByGalleryPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByGalleryCreateRequest(ctx, resourceGroupName, galleryName, options)
}, nil)
if err != nil {
return GalleryImagesClientListByGalleryResponse{}, err
}
return client.listByGalleryHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByGalleryCreateRequest creates the ListByGallery request.
func (client *GalleryImagesClient) listByGalleryCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, options *GalleryImagesClientListByGalleryOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByGalleryHandleResponse handles the ListByGallery response.
func (client *GalleryImagesClient) listByGalleryHandleResponse(resp *http.Response) (GalleryImagesClientListByGalleryResponse, error) {
result := GalleryImagesClientListByGalleryResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.GalleryImageList); err != nil {
return GalleryImagesClientListByGalleryResponse{}, err
}
return result, nil
}
// BeginUpdate - Update a gallery image definition.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery in which the Image Definition is to be updated.
// - galleryImageName - The name of the gallery image definition to be updated. The allowed characters are alphabets and numbers
// with dots, dashes, and periods allowed in the middle. The maximum length is 80 characters.
// - galleryImage - Parameters supplied to the update gallery image operation.
// - options - GalleryImagesClientBeginUpdateOptions contains the optional parameters for the GalleryImagesClient.BeginUpdate
// method.
func (client *GalleryImagesClient) BeginUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImageUpdate, options *GalleryImagesClientBeginUpdateOptions) (*runtime.Poller[GalleryImagesClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, galleryName, galleryImageName, galleryImage, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryImagesClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryImagesClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - Update a gallery image definition.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleryImagesClient) update(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImageUpdate, options *GalleryImagesClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "GalleryImagesClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, galleryName, galleryImageName, galleryImage, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *GalleryImagesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImageUpdate, options *GalleryImagesClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, galleryImage); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,463 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// GalleryImageVersionsClient contains the methods for the GalleryImageVersions group.
// Don't use this type directly, use NewGalleryImageVersionsClient() instead.
type GalleryImageVersionsClient struct {
internal *arm.Client
subscriptionID string
}
// NewGalleryImageVersionsClient creates a new instance of GalleryImageVersionsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewGalleryImageVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GalleryImageVersionsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &GalleryImageVersionsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreateOrUpdate - Create or update a gallery image version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery in which the Image Definition resides.
// - galleryImageName - The name of the gallery image definition in which the Image Version is to be created.
// - galleryImageVersionName - The name of the gallery image version to be created. Needs to follow semantic version name pattern:
// The allowed characters are digit and period. Digits must be within the range of a 32-bit integer.
// Format: ..
// - galleryImageVersion - Parameters supplied to the create or update gallery image version operation.
// - options - GalleryImageVersionsClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleryImageVersionsClient.BeginCreateOrUpdate
// method.
func (client *GalleryImageVersionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersion, options *GalleryImageVersionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[GalleryImageVersionsClientCreateOrUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.createOrUpdate(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, galleryImageVersion, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryImageVersionsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryImageVersionsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// CreateOrUpdate - Create or update a gallery image version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleryImageVersionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersion, options *GalleryImageVersionsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
var err error
const operationName = "GalleryImageVersionsClient.BeginCreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, galleryImageVersion, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *GalleryImageVersionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersion, options *GalleryImageVersionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
if galleryImageVersionName == "" {
return nil, errors.New("parameter galleryImageVersionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageVersionName}", url.PathEscape(galleryImageVersionName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, galleryImageVersion); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - Delete a gallery image version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery in which the Image Definition resides.
// - galleryImageName - The name of the gallery image definition in which the Image Version resides.
// - galleryImageVersionName - The name of the gallery image version to be deleted.
// - options - GalleryImageVersionsClientBeginDeleteOptions contains the optional parameters for the GalleryImageVersionsClient.BeginDelete
// method.
func (client *GalleryImageVersionsClient) BeginDelete(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, options *GalleryImageVersionsClientBeginDeleteOptions) (*runtime.Poller[GalleryImageVersionsClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryImageVersionsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryImageVersionsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - Delete a gallery image version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleryImageVersionsClient) deleteOperation(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, options *GalleryImageVersionsClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "GalleryImageVersionsClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *GalleryImageVersionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, options *GalleryImageVersionsClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
if galleryImageVersionName == "" {
return nil, errors.New("parameter galleryImageVersionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageVersionName}", url.PathEscape(galleryImageVersionName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - Retrieves information about a gallery image version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery in which the Image Definition resides.
// - galleryImageName - The name of the gallery image definition in which the Image Version resides.
// - galleryImageVersionName - The name of the gallery image version to be retrieved.
// - options - GalleryImageVersionsClientGetOptions contains the optional parameters for the GalleryImageVersionsClient.Get
// method.
func (client *GalleryImageVersionsClient) Get(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, options *GalleryImageVersionsClientGetOptions) (GalleryImageVersionsClientGetResponse, error) {
var err error
const operationName = "GalleryImageVersionsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, options)
if err != nil {
return GalleryImageVersionsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return GalleryImageVersionsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return GalleryImageVersionsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *GalleryImageVersionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, options *GalleryImageVersionsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
if galleryImageVersionName == "" {
return nil, errors.New("parameter galleryImageVersionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageVersionName}", url.PathEscape(galleryImageVersionName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
if options != nil && options.Expand != nil {
reqQP.Set("$expand", string(*options.Expand))
}
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *GalleryImageVersionsClient) getHandleResponse(resp *http.Response) (GalleryImageVersionsClientGetResponse, error) {
result := GalleryImageVersionsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.GalleryImageVersion); err != nil {
return GalleryImageVersionsClientGetResponse{}, err
}
return result, nil
}
// NewListByGalleryImagePager - List gallery image versions in a gallery image definition.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery in which the Image Definition resides.
// - galleryImageName - The name of the Shared Image Gallery Image Definition from which the Image Versions are to be listed.
// - options - GalleryImageVersionsClientListByGalleryImageOptions contains the optional parameters for the GalleryImageVersionsClient.NewListByGalleryImagePager
// method.
func (client *GalleryImageVersionsClient) NewListByGalleryImagePager(resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImageVersionsClientListByGalleryImageOptions) *runtime.Pager[GalleryImageVersionsClientListByGalleryImageResponse] {
return runtime.NewPager(runtime.PagingHandler[GalleryImageVersionsClientListByGalleryImageResponse]{
More: func(page GalleryImageVersionsClientListByGalleryImageResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *GalleryImageVersionsClientListByGalleryImageResponse) (GalleryImageVersionsClientListByGalleryImageResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GalleryImageVersionsClient.NewListByGalleryImagePager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByGalleryImageCreateRequest(ctx, resourceGroupName, galleryName, galleryImageName, options)
}, nil)
if err != nil {
return GalleryImageVersionsClientListByGalleryImageResponse{}, err
}
return client.listByGalleryImageHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByGalleryImageCreateRequest creates the ListByGalleryImage request.
func (client *GalleryImageVersionsClient) listByGalleryImageCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImageVersionsClientListByGalleryImageOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByGalleryImageHandleResponse handles the ListByGalleryImage response.
func (client *GalleryImageVersionsClient) listByGalleryImageHandleResponse(resp *http.Response) (GalleryImageVersionsClientListByGalleryImageResponse, error) {
result := GalleryImageVersionsClientListByGalleryImageResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.GalleryImageVersionList); err != nil {
return GalleryImageVersionsClientListByGalleryImageResponse{}, err
}
return result, nil
}
// BeginUpdate - Update a gallery image version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery in which the Image Definition resides.
// - galleryImageName - The name of the gallery image definition in which the Image Version is to be updated.
// - galleryImageVersionName - The name of the gallery image version to be updated. Needs to follow semantic version name pattern:
// The allowed characters are digit and period. Digits must be within the range of a 32-bit integer.
// Format: ..
// - galleryImageVersion - Parameters supplied to the update gallery image version operation.
// - options - GalleryImageVersionsClientBeginUpdateOptions contains the optional parameters for the GalleryImageVersionsClient.BeginUpdate
// method.
func (client *GalleryImageVersionsClient) BeginUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersionUpdate, options *GalleryImageVersionsClientBeginUpdateOptions) (*runtime.Poller[GalleryImageVersionsClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, galleryImageVersion, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryImageVersionsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryImageVersionsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - Update a gallery image version.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GalleryImageVersionsClient) update(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersionUpdate, options *GalleryImageVersionsClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "GalleryImageVersionsClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, galleryImageVersion, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *GalleryImageVersionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersionUpdate, options *GalleryImageVersionsClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
if galleryImageVersionName == "" {
return nil, errors.New("parameter galleryImageVersionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageVersionName}", url.PathEscape(galleryImageVersionName))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, galleryImageVersion); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,125 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// GallerySharingProfileClient contains the methods for the GallerySharingProfile group.
// Don't use this type directly, use NewGallerySharingProfileClient() instead.
type GallerySharingProfileClient struct {
internal *arm.Client
subscriptionID string
}
// NewGallerySharingProfileClient creates a new instance of GallerySharingProfileClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewGallerySharingProfileClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GallerySharingProfileClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &GallerySharingProfileClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginUpdate - Update sharing profile of a gallery.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - resourceGroupName - The name of the resource group.
// - galleryName - The name of the Shared Image Gallery.
// - sharingUpdate - Parameters supplied to the update gallery sharing profile.
// - options - GallerySharingProfileClientBeginUpdateOptions contains the optional parameters for the GallerySharingProfileClient.BeginUpdate
// method.
func (client *GallerySharingProfileClient) BeginUpdate(ctx context.Context, resourceGroupName string, galleryName string, sharingUpdate SharingUpdate, options *GallerySharingProfileClientBeginUpdateOptions) (*runtime.Poller[GallerySharingProfileClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, galleryName, sharingUpdate, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GallerySharingProfileClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GallerySharingProfileClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - Update sharing profile of a gallery.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
func (client *GallerySharingProfileClient) update(ctx context.Context, resourceGroupName string, galleryName string, sharingUpdate SharingUpdate, options *GallerySharingProfileClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "GallerySharingProfileClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, galleryName, sharingUpdate, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *GallerySharingProfileClient) updateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, sharingUpdate SharingUpdate, options *GallerySharingProfileClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/share"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if galleryName == "" {
return nil, errors.New("parameter galleryName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, sharingUpdate); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,462 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// ImagesClient contains the methods for the Images group.
// Don't use this type directly, use NewImagesClient() instead.
type ImagesClient struct {
internal *arm.Client
subscriptionID string
}
// NewImagesClient creates a new instance of ImagesClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewImagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ImagesClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &ImagesClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreateOrUpdate - Create or update an image.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - imageName - The name of the image.
// - parameters - Parameters supplied to the Create Image operation.
// - options - ImagesClientBeginCreateOrUpdateOptions contains the optional parameters for the ImagesClient.BeginCreateOrUpdate
// method.
func (client *ImagesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, imageName string, parameters Image, options *ImagesClientBeginCreateOrUpdateOptions) (*runtime.Poller[ImagesClientCreateOrUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.createOrUpdate(ctx, resourceGroupName, imageName, parameters, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ImagesClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ImagesClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// CreateOrUpdate - Create or update an image.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *ImagesClient) createOrUpdate(ctx context.Context, resourceGroupName string, imageName string, parameters Image, options *ImagesClientBeginCreateOrUpdateOptions) (*http.Response, error) {
var err error
const operationName = "ImagesClient.BeginCreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, imageName, parameters, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *ImagesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, imageName string, parameters Image, options *ImagesClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if imageName == "" {
return nil, errors.New("parameter imageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{imageName}", url.PathEscape(imageName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - Deletes an Image.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - imageName - The name of the image.
// - options - ImagesClientBeginDeleteOptions contains the optional parameters for the ImagesClient.BeginDelete method.
func (client *ImagesClient) BeginDelete(ctx context.Context, resourceGroupName string, imageName string, options *ImagesClientBeginDeleteOptions) (*runtime.Poller[ImagesClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, imageName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ImagesClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ImagesClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - Deletes an Image.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *ImagesClient) deleteOperation(ctx context.Context, resourceGroupName string, imageName string, options *ImagesClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "ImagesClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, imageName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *ImagesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, imageName string, options *ImagesClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if imageName == "" {
return nil, errors.New("parameter imageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{imageName}", url.PathEscape(imageName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - Gets an image.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - imageName - The name of the image.
// - options - ImagesClientGetOptions contains the optional parameters for the ImagesClient.Get method.
func (client *ImagesClient) Get(ctx context.Context, resourceGroupName string, imageName string, options *ImagesClientGetOptions) (ImagesClientGetResponse, error) {
var err error
const operationName = "ImagesClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, imageName, options)
if err != nil {
return ImagesClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return ImagesClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return ImagesClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *ImagesClient) getCreateRequest(ctx context.Context, resourceGroupName string, imageName string, options *ImagesClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if imageName == "" {
return nil, errors.New("parameter imageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{imageName}", url.PathEscape(imageName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
if options != nil && options.Expand != nil {
reqQP.Set("$expand", *options.Expand)
}
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *ImagesClient) getHandleResponse(resp *http.Response) (ImagesClientGetResponse, error) {
result := ImagesClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.Image); err != nil {
return ImagesClientGetResponse{}, err
}
return result, nil
}
// NewListPager - Gets the list of Images in the subscription. Use nextLink property in the response to get the next page
// of Images. Do this till nextLink is null to fetch all the Images.
//
// Generated from API version 2023-07-01
// - options - ImagesClientListOptions contains the optional parameters for the ImagesClient.NewListPager method.
func (client *ImagesClient) NewListPager(options *ImagesClientListOptions) *runtime.Pager[ImagesClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[ImagesClientListResponse]{
More: func(page ImagesClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *ImagesClientListResponse) (ImagesClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ImagesClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, options)
}, nil)
if err != nil {
return ImagesClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *ImagesClient) listCreateRequest(ctx context.Context, options *ImagesClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/images"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *ImagesClient) listHandleResponse(resp *http.Response) (ImagesClientListResponse, error) {
result := ImagesClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.ImageListResult); err != nil {
return ImagesClientListResponse{}, err
}
return result, nil
}
// NewListByResourceGroupPager - Gets the list of images under a resource group. Use nextLink property in the response to
// get the next page of Images. Do this till nextLink is null to fetch all the Images.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - options - ImagesClientListByResourceGroupOptions contains the optional parameters for the ImagesClient.NewListByResourceGroupPager
// method.
func (client *ImagesClient) NewListByResourceGroupPager(resourceGroupName string, options *ImagesClientListByResourceGroupOptions) *runtime.Pager[ImagesClientListByResourceGroupResponse] {
return runtime.NewPager(runtime.PagingHandler[ImagesClientListByResourceGroupResponse]{
More: func(page ImagesClientListByResourceGroupResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *ImagesClientListByResourceGroupResponse) (ImagesClientListByResourceGroupResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ImagesClient.NewListByResourceGroupPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options)
}, nil)
if err != nil {
return ImagesClientListByResourceGroupResponse{}, err
}
return client.listByResourceGroupHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *ImagesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *ImagesClientListByResourceGroupOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *ImagesClient) listByResourceGroupHandleResponse(resp *http.Response) (ImagesClientListByResourceGroupResponse, error) {
result := ImagesClientListByResourceGroupResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.ImageListResult); err != nil {
return ImagesClientListByResourceGroupResponse{}, err
}
return result, nil
}
// BeginUpdate - Update an image.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - imageName - The name of the image.
// - parameters - Parameters supplied to the Update Image operation.
// - options - ImagesClientBeginUpdateOptions contains the optional parameters for the ImagesClient.BeginUpdate method.
func (client *ImagesClient) BeginUpdate(ctx context.Context, resourceGroupName string, imageName string, parameters ImageUpdate, options *ImagesClientBeginUpdateOptions) (*runtime.Poller[ImagesClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, imageName, parameters, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ImagesClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ImagesClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - Update an image.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *ImagesClient) update(ctx context.Context, resourceGroupName string, imageName string, parameters ImageUpdate, options *ImagesClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "ImagesClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, imageName, parameters, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *ImagesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, imageName string, parameters ImageUpdate, options *ImagesClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if imageName == "" {
return nil, errors.New("parameter imageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{imageName}", url.PathEscape(imageName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,200 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// LogAnalyticsClient contains the methods for the LogAnalytics group.
// Don't use this type directly, use NewLogAnalyticsClient() instead.
type LogAnalyticsClient struct {
internal *arm.Client
subscriptionID string
}
// NewLogAnalyticsClient creates a new instance of LogAnalyticsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewLogAnalyticsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LogAnalyticsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &LogAnalyticsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginExportRequestRateByInterval - Export logs that show Api requests made by this subscription in the given time window
// to show throttling activities.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - location - The location upon which virtual-machine-sizes is queried.
// - parameters - Parameters supplied to the LogAnalytics getRequestRateByInterval Api.
// - options - LogAnalyticsClientBeginExportRequestRateByIntervalOptions contains the optional parameters for the LogAnalyticsClient.BeginExportRequestRateByInterval
// method.
func (client *LogAnalyticsClient) BeginExportRequestRateByInterval(ctx context.Context, location string, parameters RequestRateByIntervalInput, options *LogAnalyticsClientBeginExportRequestRateByIntervalOptions) (*runtime.Poller[LogAnalyticsClientExportRequestRateByIntervalResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.exportRequestRateByInterval(ctx, location, parameters, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LogAnalyticsClientExportRequestRateByIntervalResponse]{
FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LogAnalyticsClientExportRequestRateByIntervalResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// ExportRequestRateByInterval - Export logs that show Api requests made by this subscription in the given time window to
// show throttling activities.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *LogAnalyticsClient) exportRequestRateByInterval(ctx context.Context, location string, parameters RequestRateByIntervalInput, options *LogAnalyticsClientBeginExportRequestRateByIntervalOptions) (*http.Response, error) {
var err error
const operationName = "LogAnalyticsClient.BeginExportRequestRateByInterval"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.exportRequestRateByIntervalCreateRequest(ctx, location, parameters, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// exportRequestRateByIntervalCreateRequest creates the ExportRequestRateByInterval request.
func (client *LogAnalyticsClient) exportRequestRateByIntervalCreateRequest(ctx context.Context, location string, parameters RequestRateByIntervalInput, options *LogAnalyticsClientBeginExportRequestRateByIntervalOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/logAnalytics/apiAccess/getRequestRateByInterval"
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// BeginExportThrottledRequests - Export logs that show total throttled Api requests for this subscription in the given time
// window.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - location - The location upon which virtual-machine-sizes is queried.
// - parameters - Parameters supplied to the LogAnalytics getThrottledRequests Api.
// - options - LogAnalyticsClientBeginExportThrottledRequestsOptions contains the optional parameters for the LogAnalyticsClient.BeginExportThrottledRequests
// method.
func (client *LogAnalyticsClient) BeginExportThrottledRequests(ctx context.Context, location string, parameters ThrottledRequestsInput, options *LogAnalyticsClientBeginExportThrottledRequestsOptions) (*runtime.Poller[LogAnalyticsClientExportThrottledRequestsResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.exportThrottledRequests(ctx, location, parameters, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LogAnalyticsClientExportThrottledRequestsResponse]{
FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LogAnalyticsClientExportThrottledRequestsResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// ExportThrottledRequests - Export logs that show total throttled Api requests for this subscription in the given time window.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *LogAnalyticsClient) exportThrottledRequests(ctx context.Context, location string, parameters ThrottledRequestsInput, options *LogAnalyticsClientBeginExportThrottledRequestsOptions) (*http.Response, error) {
var err error
const operationName = "LogAnalyticsClient.BeginExportThrottledRequests"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.exportThrottledRequestsCreateRequest(ctx, location, parameters, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// exportThrottledRequestsCreateRequest creates the ExportThrottledRequests request.
func (client *LogAnalyticsClient) exportThrottledRequestsCreateRequest(ctx context.Context, location string, parameters ThrottledRequestsInput, options *LogAnalyticsClientBeginExportThrottledRequestsOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/logAnalytics/apiAccess/getThrottledRequests"
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,89 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
)
// OperationsClient contains the methods for the Operations group.
// Don't use this type directly, use NewOperationsClient() instead.
type OperationsClient struct {
internal *arm.Client
}
// NewOperationsClient creates a new instance of OperationsClient with the specified values.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &OperationsClient{
internal: cl,
}
return client, nil
}
// NewListPager - Gets a list of compute operations.
//
// Generated from API version 2023-07-01
// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method.
func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{
More: func(page OperationsClientListResponse) bool {
return false
},
Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager")
req, err := client.listCreateRequest(ctx, options)
if err != nil {
return OperationsClientListResponse{}, err
}
resp, err := client.internal.Pipeline().Do(req)
if err != nil {
return OperationsClientListResponse{}, err
}
if !runtime.HasStatusCode(resp, http.StatusOK) {
return OperationsClientListResponse{}, runtime.NewResponseError(resp)
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsClientListOptions) (*policy.Request, error) {
urlPath := "/providers/Microsoft.Compute/operations"
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) {
result := OperationsClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil {
return OperationsClientListResponse{}, err
}
return result, nil
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,421 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// ProximityPlacementGroupsClient contains the methods for the ProximityPlacementGroups group.
// Don't use this type directly, use NewProximityPlacementGroupsClient() instead.
type ProximityPlacementGroupsClient struct {
internal *arm.Client
subscriptionID string
}
// NewProximityPlacementGroupsClient creates a new instance of ProximityPlacementGroupsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewProximityPlacementGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ProximityPlacementGroupsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &ProximityPlacementGroupsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// CreateOrUpdate - Create or update a proximity placement group.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - proximityPlacementGroupName - The name of the proximity placement group.
// - parameters - Parameters supplied to the Create Proximity Placement Group operation.
// - options - ProximityPlacementGroupsClientCreateOrUpdateOptions contains the optional parameters for the ProximityPlacementGroupsClient.CreateOrUpdate
// method.
func (client *ProximityPlacementGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, parameters ProximityPlacementGroup, options *ProximityPlacementGroupsClientCreateOrUpdateOptions) (ProximityPlacementGroupsClientCreateOrUpdateResponse, error) {
var err error
const operationName = "ProximityPlacementGroupsClient.CreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, proximityPlacementGroupName, parameters, options)
if err != nil {
return ProximityPlacementGroupsClientCreateOrUpdateResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return ProximityPlacementGroupsClientCreateOrUpdateResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
err = runtime.NewResponseError(httpResp)
return ProximityPlacementGroupsClientCreateOrUpdateResponse{}, err
}
resp, err := client.createOrUpdateHandleResponse(httpResp)
return resp, err
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *ProximityPlacementGroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, parameters ProximityPlacementGroup, options *ProximityPlacementGroupsClientCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if proximityPlacementGroupName == "" {
return nil, errors.New("parameter proximityPlacementGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{proximityPlacementGroupName}", url.PathEscape(proximityPlacementGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// createOrUpdateHandleResponse handles the CreateOrUpdate response.
func (client *ProximityPlacementGroupsClient) createOrUpdateHandleResponse(resp *http.Response) (ProximityPlacementGroupsClientCreateOrUpdateResponse, error) {
result := ProximityPlacementGroupsClientCreateOrUpdateResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.ProximityPlacementGroup); err != nil {
return ProximityPlacementGroupsClientCreateOrUpdateResponse{}, err
}
return result, nil
}
// Delete - Delete a proximity placement group.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - proximityPlacementGroupName - The name of the proximity placement group.
// - options - ProximityPlacementGroupsClientDeleteOptions contains the optional parameters for the ProximityPlacementGroupsClient.Delete
// method.
func (client *ProximityPlacementGroupsClient) Delete(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, options *ProximityPlacementGroupsClientDeleteOptions) (ProximityPlacementGroupsClientDeleteResponse, error) {
var err error
const operationName = "ProximityPlacementGroupsClient.Delete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, proximityPlacementGroupName, options)
if err != nil {
return ProximityPlacementGroupsClientDeleteResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return ProximityPlacementGroupsClientDeleteResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return ProximityPlacementGroupsClientDeleteResponse{}, err
}
return ProximityPlacementGroupsClientDeleteResponse{}, nil
}
// deleteCreateRequest creates the Delete request.
func (client *ProximityPlacementGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, options *ProximityPlacementGroupsClientDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if proximityPlacementGroupName == "" {
return nil, errors.New("parameter proximityPlacementGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{proximityPlacementGroupName}", url.PathEscape(proximityPlacementGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - Retrieves information about a proximity placement group .
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - proximityPlacementGroupName - The name of the proximity placement group.
// - options - ProximityPlacementGroupsClientGetOptions contains the optional parameters for the ProximityPlacementGroupsClient.Get
// method.
func (client *ProximityPlacementGroupsClient) Get(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, options *ProximityPlacementGroupsClientGetOptions) (ProximityPlacementGroupsClientGetResponse, error) {
var err error
const operationName = "ProximityPlacementGroupsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, proximityPlacementGroupName, options)
if err != nil {
return ProximityPlacementGroupsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return ProximityPlacementGroupsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return ProximityPlacementGroupsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *ProximityPlacementGroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, options *ProximityPlacementGroupsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if proximityPlacementGroupName == "" {
return nil, errors.New("parameter proximityPlacementGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{proximityPlacementGroupName}", url.PathEscape(proximityPlacementGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
if options != nil && options.IncludeColocationStatus != nil {
reqQP.Set("includeColocationStatus", *options.IncludeColocationStatus)
}
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *ProximityPlacementGroupsClient) getHandleResponse(resp *http.Response) (ProximityPlacementGroupsClientGetResponse, error) {
result := ProximityPlacementGroupsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.ProximityPlacementGroup); err != nil {
return ProximityPlacementGroupsClientGetResponse{}, err
}
return result, nil
}
// NewListByResourceGroupPager - Lists all proximity placement groups in a resource group.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - options - ProximityPlacementGroupsClientListByResourceGroupOptions contains the optional parameters for the ProximityPlacementGroupsClient.NewListByResourceGroupPager
// method.
func (client *ProximityPlacementGroupsClient) NewListByResourceGroupPager(resourceGroupName string, options *ProximityPlacementGroupsClientListByResourceGroupOptions) *runtime.Pager[ProximityPlacementGroupsClientListByResourceGroupResponse] {
return runtime.NewPager(runtime.PagingHandler[ProximityPlacementGroupsClientListByResourceGroupResponse]{
More: func(page ProximityPlacementGroupsClientListByResourceGroupResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *ProximityPlacementGroupsClientListByResourceGroupResponse) (ProximityPlacementGroupsClientListByResourceGroupResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ProximityPlacementGroupsClient.NewListByResourceGroupPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options)
}, nil)
if err != nil {
return ProximityPlacementGroupsClientListByResourceGroupResponse{}, err
}
return client.listByResourceGroupHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *ProximityPlacementGroupsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *ProximityPlacementGroupsClientListByResourceGroupOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *ProximityPlacementGroupsClient) listByResourceGroupHandleResponse(resp *http.Response) (ProximityPlacementGroupsClientListByResourceGroupResponse, error) {
result := ProximityPlacementGroupsClientListByResourceGroupResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.ProximityPlacementGroupListResult); err != nil {
return ProximityPlacementGroupsClientListByResourceGroupResponse{}, err
}
return result, nil
}
// NewListBySubscriptionPager - Lists all proximity placement groups in a subscription.
//
// Generated from API version 2023-07-01
// - options - ProximityPlacementGroupsClientListBySubscriptionOptions contains the optional parameters for the ProximityPlacementGroupsClient.NewListBySubscriptionPager
// method.
func (client *ProximityPlacementGroupsClient) NewListBySubscriptionPager(options *ProximityPlacementGroupsClientListBySubscriptionOptions) *runtime.Pager[ProximityPlacementGroupsClientListBySubscriptionResponse] {
return runtime.NewPager(runtime.PagingHandler[ProximityPlacementGroupsClientListBySubscriptionResponse]{
More: func(page ProximityPlacementGroupsClientListBySubscriptionResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *ProximityPlacementGroupsClientListBySubscriptionResponse) (ProximityPlacementGroupsClientListBySubscriptionResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ProximityPlacementGroupsClient.NewListBySubscriptionPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listBySubscriptionCreateRequest(ctx, options)
}, nil)
if err != nil {
return ProximityPlacementGroupsClientListBySubscriptionResponse{}, err
}
return client.listBySubscriptionHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listBySubscriptionCreateRequest creates the ListBySubscription request.
func (client *ProximityPlacementGroupsClient) listBySubscriptionCreateRequest(ctx context.Context, options *ProximityPlacementGroupsClientListBySubscriptionOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/proximityPlacementGroups"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listBySubscriptionHandleResponse handles the ListBySubscription response.
func (client *ProximityPlacementGroupsClient) listBySubscriptionHandleResponse(resp *http.Response) (ProximityPlacementGroupsClientListBySubscriptionResponse, error) {
result := ProximityPlacementGroupsClientListBySubscriptionResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.ProximityPlacementGroupListResult); err != nil {
return ProximityPlacementGroupsClientListBySubscriptionResponse{}, err
}
return result, nil
}
// Update - Update a proximity placement group.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - proximityPlacementGroupName - The name of the proximity placement group.
// - parameters - Parameters supplied to the Update Proximity Placement Group operation.
// - options - ProximityPlacementGroupsClientUpdateOptions contains the optional parameters for the ProximityPlacementGroupsClient.Update
// method.
func (client *ProximityPlacementGroupsClient) Update(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, parameters ProximityPlacementGroupUpdate, options *ProximityPlacementGroupsClientUpdateOptions) (ProximityPlacementGroupsClientUpdateResponse, error) {
var err error
const operationName = "ProximityPlacementGroupsClient.Update"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, proximityPlacementGroupName, parameters, options)
if err != nil {
return ProximityPlacementGroupsClientUpdateResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return ProximityPlacementGroupsClientUpdateResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return ProximityPlacementGroupsClientUpdateResponse{}, err
}
resp, err := client.updateHandleResponse(httpResp)
return resp, err
}
// updateCreateRequest creates the Update request.
func (client *ProximityPlacementGroupsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, parameters ProximityPlacementGroupUpdate, options *ProximityPlacementGroupsClientUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if proximityPlacementGroupName == "" {
return nil, errors.New("parameter proximityPlacementGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{proximityPlacementGroupName}", url.PathEscape(proximityPlacementGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// updateHandleResponse handles the Update response.
func (client *ProximityPlacementGroupsClient) updateHandleResponse(resp *http.Response) (ProximityPlacementGroupsClientUpdateResponse, error) {
result := ProximityPlacementGroupsClientUpdateResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.ProximityPlacementGroup); err != nil {
return ProximityPlacementGroupsClientUpdateResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,105 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// ResourceSKUsClient contains the methods for the ResourceSKUs group.
// Don't use this type directly, use NewResourceSKUsClient() instead.
type ResourceSKUsClient struct {
internal *arm.Client
subscriptionID string
}
// NewResourceSKUsClient creates a new instance of ResourceSKUsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewResourceSKUsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ResourceSKUsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &ResourceSKUsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// NewListPager - Gets the list of Microsoft.Compute SKUs available for your Subscription.
//
// Generated from API version 2021-07-01
// - options - ResourceSKUsClientListOptions contains the optional parameters for the ResourceSKUsClient.NewListPager method.
func (client *ResourceSKUsClient) NewListPager(options *ResourceSKUsClientListOptions) *runtime.Pager[ResourceSKUsClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[ResourceSKUsClientListResponse]{
More: func(page ResourceSKUsClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *ResourceSKUsClientListResponse) (ResourceSKUsClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ResourceSKUsClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, options)
}, nil)
if err != nil {
return ResourceSKUsClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *ResourceSKUsClient) listCreateRequest(ctx context.Context, options *ResourceSKUsClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/skus"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2021-07-01")
if options != nil && options.Filter != nil {
reqQP.Set("$filter", *options.Filter)
}
if options != nil && options.IncludeExtendedLocations != nil {
reqQP.Set("includeExtendedLocations", *options.IncludeExtendedLocations)
}
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *ResourceSKUsClient) listHandleResponse(resp *http.Response) (ResourceSKUsClientListResponse, error) {
result := ResourceSKUsClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.ResourceSKUsResult); err != nil {
return ResourceSKUsClientListResponse{}, err
}
return result, nil
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,447 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// RestorePointCollectionsClient contains the methods for the RestorePointCollections group.
// Don't use this type directly, use NewRestorePointCollectionsClient() instead.
type RestorePointCollectionsClient struct {
internal *arm.Client
subscriptionID string
}
// NewRestorePointCollectionsClient creates a new instance of RestorePointCollectionsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewRestorePointCollectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RestorePointCollectionsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &RestorePointCollectionsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// CreateOrUpdate - The operation to create or update the restore point collection. Please refer to https://aka.ms/RestorePoints
// for more details. When updating a restore point collection, only tags may be modified.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - restorePointCollectionName - The name of the restore point collection.
// - parameters - Parameters supplied to the Create or Update restore point collection operation.
// - options - RestorePointCollectionsClientCreateOrUpdateOptions contains the optional parameters for the RestorePointCollectionsClient.CreateOrUpdate
// method.
func (client *RestorePointCollectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, restorePointCollectionName string, parameters RestorePointCollection, options *RestorePointCollectionsClientCreateOrUpdateOptions) (RestorePointCollectionsClientCreateOrUpdateResponse, error) {
var err error
const operationName = "RestorePointCollectionsClient.CreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, restorePointCollectionName, parameters, options)
if err != nil {
return RestorePointCollectionsClientCreateOrUpdateResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return RestorePointCollectionsClientCreateOrUpdateResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
err = runtime.NewResponseError(httpResp)
return RestorePointCollectionsClientCreateOrUpdateResponse{}, err
}
resp, err := client.createOrUpdateHandleResponse(httpResp)
return resp, err
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *RestorePointCollectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, parameters RestorePointCollection, options *RestorePointCollectionsClientCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if restorePointCollectionName == "" {
return nil, errors.New("parameter restorePointCollectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// createOrUpdateHandleResponse handles the CreateOrUpdate response.
func (client *RestorePointCollectionsClient) createOrUpdateHandleResponse(resp *http.Response) (RestorePointCollectionsClientCreateOrUpdateResponse, error) {
result := RestorePointCollectionsClientCreateOrUpdateResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.RestorePointCollection); err != nil {
return RestorePointCollectionsClientCreateOrUpdateResponse{}, err
}
return result, nil
}
// BeginDelete - The operation to delete the restore point collection. This operation will also delete all the contained restore
// points.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - restorePointCollectionName - The name of the Restore Point Collection.
// - options - RestorePointCollectionsClientBeginDeleteOptions contains the optional parameters for the RestorePointCollectionsClient.BeginDelete
// method.
func (client *RestorePointCollectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, restorePointCollectionName string, options *RestorePointCollectionsClientBeginDeleteOptions) (*runtime.Poller[RestorePointCollectionsClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, restorePointCollectionName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RestorePointCollectionsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RestorePointCollectionsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - The operation to delete the restore point collection. This operation will also delete all the contained restore
// points.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *RestorePointCollectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, restorePointCollectionName string, options *RestorePointCollectionsClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "RestorePointCollectionsClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, restorePointCollectionName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *RestorePointCollectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, options *RestorePointCollectionsClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if restorePointCollectionName == "" {
return nil, errors.New("parameter restorePointCollectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - The operation to get the restore point collection.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - restorePointCollectionName - The name of the restore point collection.
// - options - RestorePointCollectionsClientGetOptions contains the optional parameters for the RestorePointCollectionsClient.Get
// method.
func (client *RestorePointCollectionsClient) Get(ctx context.Context, resourceGroupName string, restorePointCollectionName string, options *RestorePointCollectionsClientGetOptions) (RestorePointCollectionsClientGetResponse, error) {
var err error
const operationName = "RestorePointCollectionsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, restorePointCollectionName, options)
if err != nil {
return RestorePointCollectionsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return RestorePointCollectionsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return RestorePointCollectionsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *RestorePointCollectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, options *RestorePointCollectionsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if restorePointCollectionName == "" {
return nil, errors.New("parameter restorePointCollectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
if options != nil && options.Expand != nil {
reqQP.Set("$expand", string(*options.Expand))
}
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *RestorePointCollectionsClient) getHandleResponse(resp *http.Response) (RestorePointCollectionsClientGetResponse, error) {
result := RestorePointCollectionsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.RestorePointCollection); err != nil {
return RestorePointCollectionsClientGetResponse{}, err
}
return result, nil
}
// NewListPager - Gets the list of restore point collections in a resource group.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - options - RestorePointCollectionsClientListOptions contains the optional parameters for the RestorePointCollectionsClient.NewListPager
// method.
func (client *RestorePointCollectionsClient) NewListPager(resourceGroupName string, options *RestorePointCollectionsClientListOptions) *runtime.Pager[RestorePointCollectionsClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[RestorePointCollectionsClientListResponse]{
More: func(page RestorePointCollectionsClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *RestorePointCollectionsClientListResponse) (RestorePointCollectionsClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RestorePointCollectionsClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, resourceGroupName, options)
}, nil)
if err != nil {
return RestorePointCollectionsClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *RestorePointCollectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *RestorePointCollectionsClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *RestorePointCollectionsClient) listHandleResponse(resp *http.Response) (RestorePointCollectionsClientListResponse, error) {
result := RestorePointCollectionsClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.RestorePointCollectionListResult); err != nil {
return RestorePointCollectionsClientListResponse{}, err
}
return result, nil
}
// NewListAllPager - Gets the list of restore point collections in the subscription. Use nextLink property in the response
// to get the next page of restore point collections. Do this till nextLink is not null to fetch all
// the restore point collections.
//
// Generated from API version 2023-07-01
// - options - RestorePointCollectionsClientListAllOptions contains the optional parameters for the RestorePointCollectionsClient.NewListAllPager
// method.
func (client *RestorePointCollectionsClient) NewListAllPager(options *RestorePointCollectionsClientListAllOptions) *runtime.Pager[RestorePointCollectionsClientListAllResponse] {
return runtime.NewPager(runtime.PagingHandler[RestorePointCollectionsClientListAllResponse]{
More: func(page RestorePointCollectionsClientListAllResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *RestorePointCollectionsClientListAllResponse) (RestorePointCollectionsClientListAllResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RestorePointCollectionsClient.NewListAllPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listAllCreateRequest(ctx, options)
}, nil)
if err != nil {
return RestorePointCollectionsClientListAllResponse{}, err
}
return client.listAllHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listAllCreateRequest creates the ListAll request.
func (client *RestorePointCollectionsClient) listAllCreateRequest(ctx context.Context, options *RestorePointCollectionsClientListAllOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/restorePointCollections"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listAllHandleResponse handles the ListAll response.
func (client *RestorePointCollectionsClient) listAllHandleResponse(resp *http.Response) (RestorePointCollectionsClientListAllResponse, error) {
result := RestorePointCollectionsClientListAllResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.RestorePointCollectionListResult); err != nil {
return RestorePointCollectionsClientListAllResponse{}, err
}
return result, nil
}
// Update - The operation to update the restore point collection.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - restorePointCollectionName - The name of the restore point collection.
// - parameters - Parameters supplied to the Update restore point collection operation.
// - options - RestorePointCollectionsClientUpdateOptions contains the optional parameters for the RestorePointCollectionsClient.Update
// method.
func (client *RestorePointCollectionsClient) Update(ctx context.Context, resourceGroupName string, restorePointCollectionName string, parameters RestorePointCollectionUpdate, options *RestorePointCollectionsClientUpdateOptions) (RestorePointCollectionsClientUpdateResponse, error) {
var err error
const operationName = "RestorePointCollectionsClient.Update"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, restorePointCollectionName, parameters, options)
if err != nil {
return RestorePointCollectionsClientUpdateResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return RestorePointCollectionsClientUpdateResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return RestorePointCollectionsClientUpdateResponse{}, err
}
resp, err := client.updateHandleResponse(httpResp)
return resp, err
}
// updateCreateRequest creates the Update request.
func (client *RestorePointCollectionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, parameters RestorePointCollectionUpdate, options *RestorePointCollectionsClientUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if restorePointCollectionName == "" {
return nil, errors.New("parameter restorePointCollectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// updateHandleResponse handles the Update response.
func (client *RestorePointCollectionsClient) updateHandleResponse(resp *http.Response) (RestorePointCollectionsClientUpdateResponse, error) {
result := RestorePointCollectionsClientUpdateResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.RestorePointCollection); err != nil {
return RestorePointCollectionsClientUpdateResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,283 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// RestorePointsClient contains the methods for the RestorePoints group.
// Don't use this type directly, use NewRestorePointsClient() instead.
type RestorePointsClient struct {
internal *arm.Client
subscriptionID string
}
// NewRestorePointsClient creates a new instance of RestorePointsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewRestorePointsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RestorePointsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &RestorePointsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreate - The operation to create the restore point. Updating properties of an existing restore point is not allowed
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - restorePointCollectionName - The name of the restore point collection.
// - restorePointName - The name of the restore point.
// - parameters - Parameters supplied to the Create restore point operation.
// - options - RestorePointsClientBeginCreateOptions contains the optional parameters for the RestorePointsClient.BeginCreate
// method.
func (client *RestorePointsClient) BeginCreate(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, parameters RestorePoint, options *RestorePointsClientBeginCreateOptions) (*runtime.Poller[RestorePointsClientCreateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.create(ctx, resourceGroupName, restorePointCollectionName, restorePointName, parameters, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RestorePointsClientCreateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RestorePointsClientCreateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Create - The operation to create the restore point. Updating properties of an existing restore point is not allowed
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *RestorePointsClient) create(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, parameters RestorePoint, options *RestorePointsClientBeginCreateOptions) (*http.Response, error) {
var err error
const operationName = "RestorePointsClient.BeginCreate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createCreateRequest(ctx, resourceGroupName, restorePointCollectionName, restorePointName, parameters, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusCreated) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createCreateRequest creates the Create request.
func (client *RestorePointsClient) createCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, parameters RestorePoint, options *RestorePointsClientBeginCreateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{restorePointName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if restorePointCollectionName == "" {
return nil, errors.New("parameter restorePointCollectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName))
if restorePointName == "" {
return nil, errors.New("parameter restorePointName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointName}", url.PathEscape(restorePointName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - The operation to delete the restore point.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - restorePointCollectionName - The name of the Restore Point Collection.
// - restorePointName - The name of the restore point.
// - options - RestorePointsClientBeginDeleteOptions contains the optional parameters for the RestorePointsClient.BeginDelete
// method.
func (client *RestorePointsClient) BeginDelete(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, options *RestorePointsClientBeginDeleteOptions) (*runtime.Poller[RestorePointsClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, restorePointCollectionName, restorePointName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RestorePointsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RestorePointsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - The operation to delete the restore point.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *RestorePointsClient) deleteOperation(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, options *RestorePointsClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "RestorePointsClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, restorePointCollectionName, restorePointName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *RestorePointsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, options *RestorePointsClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{restorePointName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if restorePointCollectionName == "" {
return nil, errors.New("parameter restorePointCollectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName))
if restorePointName == "" {
return nil, errors.New("parameter restorePointName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointName}", url.PathEscape(restorePointName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - The operation to get the restore point.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - restorePointCollectionName - The name of the restore point collection.
// - restorePointName - The name of the restore point.
// - options - RestorePointsClientGetOptions contains the optional parameters for the RestorePointsClient.Get method.
func (client *RestorePointsClient) Get(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, options *RestorePointsClientGetOptions) (RestorePointsClientGetResponse, error) {
var err error
const operationName = "RestorePointsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, restorePointCollectionName, restorePointName, options)
if err != nil {
return RestorePointsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return RestorePointsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return RestorePointsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *RestorePointsClient) getCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, options *RestorePointsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{restorePointName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if restorePointCollectionName == "" {
return nil, errors.New("parameter restorePointCollectionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName))
if restorePointName == "" {
return nil, errors.New("parameter restorePointName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{restorePointName}", url.PathEscape(restorePointName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
if options != nil && options.Expand != nil {
reqQP.Set("$expand", string(*options.Expand))
}
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *RestorePointsClient) getHandleResponse(resp *http.Response) (RestorePointsClientGetResponse, error) {
result := RestorePointsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.RestorePoint); err != nil {
return RestorePointsClientGetResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,172 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// SharedGalleriesClient contains the methods for the SharedGalleries group.
// Don't use this type directly, use NewSharedGalleriesClient() instead.
type SharedGalleriesClient struct {
internal *arm.Client
subscriptionID string
}
// NewSharedGalleriesClient creates a new instance of SharedGalleriesClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewSharedGalleriesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SharedGalleriesClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &SharedGalleriesClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// Get - Get a shared gallery by subscription id or tenant id.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - location - Resource location.
// - galleryUniqueName - The unique name of the Shared Gallery.
// - options - SharedGalleriesClientGetOptions contains the optional parameters for the SharedGalleriesClient.Get method.
func (client *SharedGalleriesClient) Get(ctx context.Context, location string, galleryUniqueName string, options *SharedGalleriesClientGetOptions) (SharedGalleriesClientGetResponse, error) {
var err error
const operationName = "SharedGalleriesClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, location, galleryUniqueName, options)
if err != nil {
return SharedGalleriesClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return SharedGalleriesClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return SharedGalleriesClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *SharedGalleriesClient) getCreateRequest(ctx context.Context, location string, galleryUniqueName string, options *SharedGalleriesClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries/{galleryUniqueName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if galleryUniqueName == "" {
return nil, errors.New("parameter galleryUniqueName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryUniqueName}", url.PathEscape(galleryUniqueName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *SharedGalleriesClient) getHandleResponse(resp *http.Response) (SharedGalleriesClientGetResponse, error) {
result := SharedGalleriesClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SharedGallery); err != nil {
return SharedGalleriesClientGetResponse{}, err
}
return result, nil
}
// NewListPager - List shared galleries by subscription id or tenant id.
//
// Generated from API version 2022-03-03
// - location - Resource location.
// - options - SharedGalleriesClientListOptions contains the optional parameters for the SharedGalleriesClient.NewListPager
// method.
func (client *SharedGalleriesClient) NewListPager(location string, options *SharedGalleriesClientListOptions) *runtime.Pager[SharedGalleriesClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[SharedGalleriesClientListResponse]{
More: func(page SharedGalleriesClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *SharedGalleriesClientListResponse) (SharedGalleriesClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SharedGalleriesClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, location, options)
}, nil)
if err != nil {
return SharedGalleriesClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *SharedGalleriesClient) listCreateRequest(ctx context.Context, location string, options *SharedGalleriesClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
if options != nil && options.SharedTo != nil {
reqQP.Set("sharedTo", string(*options.SharedTo))
}
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *SharedGalleriesClient) listHandleResponse(resp *http.Response) (SharedGalleriesClientListResponse, error) {
result := SharedGalleriesClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SharedGalleryList); err != nil {
return SharedGalleriesClientListResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,182 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// SharedGalleryImagesClient contains the methods for the SharedGalleryImages group.
// Don't use this type directly, use NewSharedGalleryImagesClient() instead.
type SharedGalleryImagesClient struct {
internal *arm.Client
subscriptionID string
}
// NewSharedGalleryImagesClient creates a new instance of SharedGalleryImagesClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewSharedGalleryImagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SharedGalleryImagesClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &SharedGalleryImagesClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// Get - Get a shared gallery image by subscription id or tenant id.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - location - Resource location.
// - galleryUniqueName - The unique name of the Shared Gallery.
// - galleryImageName - The name of the Shared Gallery Image Definition from which the Image Versions are to be listed.
// - options - SharedGalleryImagesClientGetOptions contains the optional parameters for the SharedGalleryImagesClient.Get method.
func (client *SharedGalleryImagesClient) Get(ctx context.Context, location string, galleryUniqueName string, galleryImageName string, options *SharedGalleryImagesClientGetOptions) (SharedGalleryImagesClientGetResponse, error) {
var err error
const operationName = "SharedGalleryImagesClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, location, galleryUniqueName, galleryImageName, options)
if err != nil {
return SharedGalleryImagesClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return SharedGalleryImagesClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return SharedGalleryImagesClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *SharedGalleryImagesClient) getCreateRequest(ctx context.Context, location string, galleryUniqueName string, galleryImageName string, options *SharedGalleryImagesClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries/{galleryUniqueName}/images/{galleryImageName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if galleryUniqueName == "" {
return nil, errors.New("parameter galleryUniqueName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryUniqueName}", url.PathEscape(galleryUniqueName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *SharedGalleryImagesClient) getHandleResponse(resp *http.Response) (SharedGalleryImagesClientGetResponse, error) {
result := SharedGalleryImagesClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SharedGalleryImage); err != nil {
return SharedGalleryImagesClientGetResponse{}, err
}
return result, nil
}
// NewListPager - List shared gallery images by subscription id or tenant id.
//
// Generated from API version 2022-03-03
// - location - Resource location.
// - galleryUniqueName - The unique name of the Shared Gallery.
// - options - SharedGalleryImagesClientListOptions contains the optional parameters for the SharedGalleryImagesClient.NewListPager
// method.
func (client *SharedGalleryImagesClient) NewListPager(location string, galleryUniqueName string, options *SharedGalleryImagesClientListOptions) *runtime.Pager[SharedGalleryImagesClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[SharedGalleryImagesClientListResponse]{
More: func(page SharedGalleryImagesClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *SharedGalleryImagesClientListResponse) (SharedGalleryImagesClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SharedGalleryImagesClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, location, galleryUniqueName, options)
}, nil)
if err != nil {
return SharedGalleryImagesClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *SharedGalleryImagesClient) listCreateRequest(ctx context.Context, location string, galleryUniqueName string, options *SharedGalleryImagesClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries/{galleryUniqueName}/images"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if galleryUniqueName == "" {
return nil, errors.New("parameter galleryUniqueName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryUniqueName}", url.PathEscape(galleryUniqueName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
if options != nil && options.SharedTo != nil {
reqQP.Set("sharedTo", string(*options.SharedTo))
}
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *SharedGalleryImagesClient) listHandleResponse(resp *http.Response) (SharedGalleryImagesClientListResponse, error) {
result := SharedGalleryImagesClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SharedGalleryImageList); err != nil {
return SharedGalleryImagesClientListResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,195 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// SharedGalleryImageVersionsClient contains the methods for the SharedGalleryImageVersions group.
// Don't use this type directly, use NewSharedGalleryImageVersionsClient() instead.
type SharedGalleryImageVersionsClient struct {
internal *arm.Client
subscriptionID string
}
// NewSharedGalleryImageVersionsClient creates a new instance of SharedGalleryImageVersionsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewSharedGalleryImageVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SharedGalleryImageVersionsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &SharedGalleryImageVersionsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// Get - Get a shared gallery image version by subscription id or tenant id.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2022-03-03
// - location - Resource location.
// - galleryUniqueName - The unique name of the Shared Gallery.
// - galleryImageName - The name of the Shared Gallery Image Definition from which the Image Versions are to be listed.
// - galleryImageVersionName - The name of the gallery image version to be created. Needs to follow semantic version name pattern:
// The allowed characters are digit and period. Digits must be within the range of a 32-bit integer.
// Format: ..
// - options - SharedGalleryImageVersionsClientGetOptions contains the optional parameters for the SharedGalleryImageVersionsClient.Get
// method.
func (client *SharedGalleryImageVersionsClient) Get(ctx context.Context, location string, galleryUniqueName string, galleryImageName string, galleryImageVersionName string, options *SharedGalleryImageVersionsClientGetOptions) (SharedGalleryImageVersionsClientGetResponse, error) {
var err error
const operationName = "SharedGalleryImageVersionsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, location, galleryUniqueName, galleryImageName, galleryImageVersionName, options)
if err != nil {
return SharedGalleryImageVersionsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return SharedGalleryImageVersionsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return SharedGalleryImageVersionsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *SharedGalleryImageVersionsClient) getCreateRequest(ctx context.Context, location string, galleryUniqueName string, galleryImageName string, galleryImageVersionName string, options *SharedGalleryImageVersionsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries/{galleryUniqueName}/images/{galleryImageName}/versions/{galleryImageVersionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if galleryUniqueName == "" {
return nil, errors.New("parameter galleryUniqueName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryUniqueName}", url.PathEscape(galleryUniqueName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
if galleryImageVersionName == "" {
return nil, errors.New("parameter galleryImageVersionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageVersionName}", url.PathEscape(galleryImageVersionName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *SharedGalleryImageVersionsClient) getHandleResponse(resp *http.Response) (SharedGalleryImageVersionsClientGetResponse, error) {
result := SharedGalleryImageVersionsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SharedGalleryImageVersion); err != nil {
return SharedGalleryImageVersionsClientGetResponse{}, err
}
return result, nil
}
// NewListPager - List shared gallery image versions by subscription id or tenant id.
//
// Generated from API version 2022-03-03
// - location - Resource location.
// - galleryUniqueName - The unique name of the Shared Gallery.
// - galleryImageName - The name of the Shared Gallery Image Definition from which the Image Versions are to be listed.
// - options - SharedGalleryImageVersionsClientListOptions contains the optional parameters for the SharedGalleryImageVersionsClient.NewListPager
// method.
func (client *SharedGalleryImageVersionsClient) NewListPager(location string, galleryUniqueName string, galleryImageName string, options *SharedGalleryImageVersionsClientListOptions) *runtime.Pager[SharedGalleryImageVersionsClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[SharedGalleryImageVersionsClientListResponse]{
More: func(page SharedGalleryImageVersionsClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *SharedGalleryImageVersionsClientListResponse) (SharedGalleryImageVersionsClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SharedGalleryImageVersionsClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, location, galleryUniqueName, galleryImageName, options)
}, nil)
if err != nil {
return SharedGalleryImageVersionsClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *SharedGalleryImageVersionsClient) listCreateRequest(ctx context.Context, location string, galleryUniqueName string, galleryImageName string, options *SharedGalleryImageVersionsClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries/{galleryUniqueName}/images/{galleryImageName}/versions"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if galleryUniqueName == "" {
return nil, errors.New("parameter galleryUniqueName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryUniqueName}", url.PathEscape(galleryUniqueName))
if galleryImageName == "" {
return nil, errors.New("parameter galleryImageName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2022-03-03")
if options != nil && options.SharedTo != nil {
reqQP.Set("sharedTo", string(*options.SharedTo))
}
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *SharedGalleryImageVersionsClient) listHandleResponse(resp *http.Response) (SharedGalleryImageVersionsClientListResponse, error) {
result := SharedGalleryImageVersionsClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SharedGalleryImageVersionList); err != nil {
return SharedGalleryImageVersionsClientListResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,625 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// SnapshotsClient contains the methods for the Snapshots group.
// Don't use this type directly, use NewSnapshotsClient() instead.
type SnapshotsClient struct {
internal *arm.Client
subscriptionID string
}
// NewSnapshotsClient creates a new instance of SnapshotsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewSnapshotsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SnapshotsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &SnapshotsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreateOrUpdate - Creates or updates a snapshot.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created.
// Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80
// characters.
// - snapshot - Snapshot object supplied in the body of the Put disk operation.
// - options - SnapshotsClientBeginCreateOrUpdateOptions contains the optional parameters for the SnapshotsClient.BeginCreateOrUpdate
// method.
func (client *SnapshotsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, snapshotName string, snapshot Snapshot, options *SnapshotsClientBeginCreateOrUpdateOptions) (*runtime.Poller[SnapshotsClientCreateOrUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.createOrUpdate(ctx, resourceGroupName, snapshotName, snapshot, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SnapshotsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SnapshotsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// CreateOrUpdate - Creates or updates a snapshot.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *SnapshotsClient) createOrUpdate(ctx context.Context, resourceGroupName string, snapshotName string, snapshot Snapshot, options *SnapshotsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
var err error
const operationName = "SnapshotsClient.BeginCreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, snapshotName, snapshot, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *SnapshotsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, snapshotName string, snapshot Snapshot, options *SnapshotsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if snapshotName == "" {
return nil, errors.New("parameter snapshotName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{snapshotName}", url.PathEscape(snapshotName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, snapshot); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - Deletes a snapshot.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created.
// Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80
// characters.
// - options - SnapshotsClientBeginDeleteOptions contains the optional parameters for the SnapshotsClient.BeginDelete method.
func (client *SnapshotsClient) BeginDelete(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginDeleteOptions) (*runtime.Poller[SnapshotsClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, snapshotName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SnapshotsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SnapshotsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - Deletes a snapshot.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *SnapshotsClient) deleteOperation(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "SnapshotsClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, snapshotName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *SnapshotsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if snapshotName == "" {
return nil, errors.New("parameter snapshotName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{snapshotName}", url.PathEscape(snapshotName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
return req, nil
}
// Get - Gets information about a snapshot.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created.
// Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80
// characters.
// - options - SnapshotsClientGetOptions contains the optional parameters for the SnapshotsClient.Get method.
func (client *SnapshotsClient) Get(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientGetOptions) (SnapshotsClientGetResponse, error) {
var err error
const operationName = "SnapshotsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, snapshotName, options)
if err != nil {
return SnapshotsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return SnapshotsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return SnapshotsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *SnapshotsClient) getCreateRequest(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if snapshotName == "" {
return nil, errors.New("parameter snapshotName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{snapshotName}", url.PathEscape(snapshotName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *SnapshotsClient) getHandleResponse(resp *http.Response) (SnapshotsClientGetResponse, error) {
result := SnapshotsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.Snapshot); err != nil {
return SnapshotsClientGetResponse{}, err
}
return result, nil
}
// BeginGrantAccess - Grants access to a snapshot.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created.
// Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80
// characters.
// - grantAccessData - Access data object supplied in the body of the get snapshot access operation.
// - options - SnapshotsClientBeginGrantAccessOptions contains the optional parameters for the SnapshotsClient.BeginGrantAccess
// method.
func (client *SnapshotsClient) BeginGrantAccess(ctx context.Context, resourceGroupName string, snapshotName string, grantAccessData GrantAccessData, options *SnapshotsClientBeginGrantAccessOptions) (*runtime.Poller[SnapshotsClientGrantAccessResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.grantAccess(ctx, resourceGroupName, snapshotName, grantAccessData, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SnapshotsClientGrantAccessResponse]{
FinalStateVia: runtime.FinalStateViaLocation,
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SnapshotsClientGrantAccessResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// GrantAccess - Grants access to a snapshot.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *SnapshotsClient) grantAccess(ctx context.Context, resourceGroupName string, snapshotName string, grantAccessData GrantAccessData, options *SnapshotsClientBeginGrantAccessOptions) (*http.Response, error) {
var err error
const operationName = "SnapshotsClient.BeginGrantAccess"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.grantAccessCreateRequest(ctx, resourceGroupName, snapshotName, grantAccessData, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// grantAccessCreateRequest creates the GrantAccess request.
func (client *SnapshotsClient) grantAccessCreateRequest(ctx context.Context, resourceGroupName string, snapshotName string, grantAccessData GrantAccessData, options *SnapshotsClientBeginGrantAccessOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}/beginGetAccess"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if snapshotName == "" {
return nil, errors.New("parameter snapshotName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{snapshotName}", url.PathEscape(snapshotName))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, grantAccessData); err != nil {
return nil, err
}
return req, nil
}
// NewListPager - Lists snapshots under a subscription.
//
// Generated from API version 2023-04-02
// - options - SnapshotsClientListOptions contains the optional parameters for the SnapshotsClient.NewListPager method.
func (client *SnapshotsClient) NewListPager(options *SnapshotsClientListOptions) *runtime.Pager[SnapshotsClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[SnapshotsClientListResponse]{
More: func(page SnapshotsClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *SnapshotsClientListResponse) (SnapshotsClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SnapshotsClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, options)
}, nil)
if err != nil {
return SnapshotsClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *SnapshotsClient) listCreateRequest(ctx context.Context, options *SnapshotsClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/snapshots"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *SnapshotsClient) listHandleResponse(resp *http.Response) (SnapshotsClientListResponse, error) {
result := SnapshotsClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SnapshotList); err != nil {
return SnapshotsClientListResponse{}, err
}
return result, nil
}
// NewListByResourceGroupPager - Lists snapshots under a resource group.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - options - SnapshotsClientListByResourceGroupOptions contains the optional parameters for the SnapshotsClient.NewListByResourceGroupPager
// method.
func (client *SnapshotsClient) NewListByResourceGroupPager(resourceGroupName string, options *SnapshotsClientListByResourceGroupOptions) *runtime.Pager[SnapshotsClientListByResourceGroupResponse] {
return runtime.NewPager(runtime.PagingHandler[SnapshotsClientListByResourceGroupResponse]{
More: func(page SnapshotsClientListByResourceGroupResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *SnapshotsClientListByResourceGroupResponse) (SnapshotsClientListByResourceGroupResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SnapshotsClient.NewListByResourceGroupPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options)
}, nil)
if err != nil {
return SnapshotsClientListByResourceGroupResponse{}, err
}
return client.listByResourceGroupHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *SnapshotsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *SnapshotsClientListByResourceGroupOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *SnapshotsClient) listByResourceGroupHandleResponse(resp *http.Response) (SnapshotsClientListByResourceGroupResponse, error) {
result := SnapshotsClientListByResourceGroupResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SnapshotList); err != nil {
return SnapshotsClientListByResourceGroupResponse{}, err
}
return result, nil
}
// BeginRevokeAccess - Revokes access to a snapshot.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created.
// Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80
// characters.
// - options - SnapshotsClientBeginRevokeAccessOptions contains the optional parameters for the SnapshotsClient.BeginRevokeAccess
// method.
func (client *SnapshotsClient) BeginRevokeAccess(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginRevokeAccessOptions) (*runtime.Poller[SnapshotsClientRevokeAccessResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.revokeAccess(ctx, resourceGroupName, snapshotName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SnapshotsClientRevokeAccessResponse]{
FinalStateVia: runtime.FinalStateViaLocation,
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SnapshotsClientRevokeAccessResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// RevokeAccess - Revokes access to a snapshot.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *SnapshotsClient) revokeAccess(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginRevokeAccessOptions) (*http.Response, error) {
var err error
const operationName = "SnapshotsClient.BeginRevokeAccess"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.revokeAccessCreateRequest(ctx, resourceGroupName, snapshotName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// revokeAccessCreateRequest creates the RevokeAccess request.
func (client *SnapshotsClient) revokeAccessCreateRequest(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginRevokeAccessOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}/endGetAccess"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if snapshotName == "" {
return nil, errors.New("parameter snapshotName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{snapshotName}", url.PathEscape(snapshotName))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
return req, nil
}
// BeginUpdate - Updates (patches) a snapshot.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
// - resourceGroupName - The name of the resource group.
// - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created.
// Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80
// characters.
// - snapshot - Snapshot object supplied in the body of the Patch snapshot operation.
// - options - SnapshotsClientBeginUpdateOptions contains the optional parameters for the SnapshotsClient.BeginUpdate method.
func (client *SnapshotsClient) BeginUpdate(ctx context.Context, resourceGroupName string, snapshotName string, snapshot SnapshotUpdate, options *SnapshotsClientBeginUpdateOptions) (*runtime.Poller[SnapshotsClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, snapshotName, snapshot, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SnapshotsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SnapshotsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - Updates (patches) a snapshot.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-04-02
func (client *SnapshotsClient) update(ctx context.Context, resourceGroupName string, snapshotName string, snapshot SnapshotUpdate, options *SnapshotsClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "SnapshotsClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, snapshotName, snapshot, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *SnapshotsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, snapshotName string, snapshot SnapshotUpdate, options *SnapshotsClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if snapshotName == "" {
return nil, errors.New("parameter snapshotName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{snapshotName}", url.PathEscape(snapshotName))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-04-02")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, snapshot); err != nil {
return nil, err
}
return req, nil
}

View file

@ -0,0 +1,483 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// SSHPublicKeysClient contains the methods for the SSHPublicKeys group.
// Don't use this type directly, use NewSSHPublicKeysClient() instead.
type SSHPublicKeysClient struct {
internal *arm.Client
subscriptionID string
}
// NewSSHPublicKeysClient creates a new instance of SSHPublicKeysClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewSSHPublicKeysClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SSHPublicKeysClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &SSHPublicKeysClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// Create - Creates a new SSH public key resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - sshPublicKeyName - The name of the SSH public key.
// - parameters - Parameters supplied to create the SSH public key.
// - options - SSHPublicKeysClientCreateOptions contains the optional parameters for the SSHPublicKeysClient.Create method.
func (client *SSHPublicKeysClient) Create(ctx context.Context, resourceGroupName string, sshPublicKeyName string, parameters SSHPublicKeyResource, options *SSHPublicKeysClientCreateOptions) (SSHPublicKeysClientCreateResponse, error) {
var err error
const operationName = "SSHPublicKeysClient.Create"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createCreateRequest(ctx, resourceGroupName, sshPublicKeyName, parameters, options)
if err != nil {
return SSHPublicKeysClientCreateResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return SSHPublicKeysClientCreateResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
err = runtime.NewResponseError(httpResp)
return SSHPublicKeysClientCreateResponse{}, err
}
resp, err := client.createHandleResponse(httpResp)
return resp, err
}
// createCreateRequest creates the Create request.
func (client *SSHPublicKeysClient) createCreateRequest(ctx context.Context, resourceGroupName string, sshPublicKeyName string, parameters SSHPublicKeyResource, options *SSHPublicKeysClientCreateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/sshPublicKeys/{sshPublicKeyName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if sshPublicKeyName == "" {
return nil, errors.New("parameter sshPublicKeyName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{sshPublicKeyName}", url.PathEscape(sshPublicKeyName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// createHandleResponse handles the Create response.
func (client *SSHPublicKeysClient) createHandleResponse(resp *http.Response) (SSHPublicKeysClientCreateResponse, error) {
result := SSHPublicKeysClientCreateResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SSHPublicKeyResource); err != nil {
return SSHPublicKeysClientCreateResponse{}, err
}
return result, nil
}
// Delete - Delete an SSH public key.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - sshPublicKeyName - The name of the SSH public key.
// - options - SSHPublicKeysClientDeleteOptions contains the optional parameters for the SSHPublicKeysClient.Delete method.
func (client *SSHPublicKeysClient) Delete(ctx context.Context, resourceGroupName string, sshPublicKeyName string, options *SSHPublicKeysClientDeleteOptions) (SSHPublicKeysClientDeleteResponse, error) {
var err error
const operationName = "SSHPublicKeysClient.Delete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, sshPublicKeyName, options)
if err != nil {
return SSHPublicKeysClientDeleteResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return SSHPublicKeysClientDeleteResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return SSHPublicKeysClientDeleteResponse{}, err
}
return SSHPublicKeysClientDeleteResponse{}, nil
}
// deleteCreateRequest creates the Delete request.
func (client *SSHPublicKeysClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, sshPublicKeyName string, options *SSHPublicKeysClientDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/sshPublicKeys/{sshPublicKeyName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if sshPublicKeyName == "" {
return nil, errors.New("parameter sshPublicKeyName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{sshPublicKeyName}", url.PathEscape(sshPublicKeyName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// GenerateKeyPair - Generates and returns a public/private key pair and populates the SSH public key resource with the public
// key. The length of the key will be 3072 bits. This operation can only be performed once per
// SSH public key resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - sshPublicKeyName - The name of the SSH public key.
// - options - SSHPublicKeysClientGenerateKeyPairOptions contains the optional parameters for the SSHPublicKeysClient.GenerateKeyPair
// method.
func (client *SSHPublicKeysClient) GenerateKeyPair(ctx context.Context, resourceGroupName string, sshPublicKeyName string, options *SSHPublicKeysClientGenerateKeyPairOptions) (SSHPublicKeysClientGenerateKeyPairResponse, error) {
var err error
const operationName = "SSHPublicKeysClient.GenerateKeyPair"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.generateKeyPairCreateRequest(ctx, resourceGroupName, sshPublicKeyName, options)
if err != nil {
return SSHPublicKeysClientGenerateKeyPairResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return SSHPublicKeysClientGenerateKeyPairResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return SSHPublicKeysClientGenerateKeyPairResponse{}, err
}
resp, err := client.generateKeyPairHandleResponse(httpResp)
return resp, err
}
// generateKeyPairCreateRequest creates the GenerateKeyPair request.
func (client *SSHPublicKeysClient) generateKeyPairCreateRequest(ctx context.Context, resourceGroupName string, sshPublicKeyName string, options *SSHPublicKeysClientGenerateKeyPairOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/sshPublicKeys/{sshPublicKeyName}/generateKeyPair"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if sshPublicKeyName == "" {
return nil, errors.New("parameter sshPublicKeyName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{sshPublicKeyName}", url.PathEscape(sshPublicKeyName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// generateKeyPairHandleResponse handles the GenerateKeyPair response.
func (client *SSHPublicKeysClient) generateKeyPairHandleResponse(resp *http.Response) (SSHPublicKeysClientGenerateKeyPairResponse, error) {
result := SSHPublicKeysClientGenerateKeyPairResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SSHPublicKeyGenerateKeyPairResult); err != nil {
return SSHPublicKeysClientGenerateKeyPairResponse{}, err
}
return result, nil
}
// Get - Retrieves information about an SSH public key.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - sshPublicKeyName - The name of the SSH public key.
// - options - SSHPublicKeysClientGetOptions contains the optional parameters for the SSHPublicKeysClient.Get method.
func (client *SSHPublicKeysClient) Get(ctx context.Context, resourceGroupName string, sshPublicKeyName string, options *SSHPublicKeysClientGetOptions) (SSHPublicKeysClientGetResponse, error) {
var err error
const operationName = "SSHPublicKeysClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, sshPublicKeyName, options)
if err != nil {
return SSHPublicKeysClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return SSHPublicKeysClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return SSHPublicKeysClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *SSHPublicKeysClient) getCreateRequest(ctx context.Context, resourceGroupName string, sshPublicKeyName string, options *SSHPublicKeysClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/sshPublicKeys/{sshPublicKeyName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if sshPublicKeyName == "" {
return nil, errors.New("parameter sshPublicKeyName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{sshPublicKeyName}", url.PathEscape(sshPublicKeyName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *SSHPublicKeysClient) getHandleResponse(resp *http.Response) (SSHPublicKeysClientGetResponse, error) {
result := SSHPublicKeysClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SSHPublicKeyResource); err != nil {
return SSHPublicKeysClientGetResponse{}, err
}
return result, nil
}
// NewListByResourceGroupPager - Lists all of the SSH public keys in the specified resource group. Use the nextLink property
// in the response to get the next page of SSH public keys.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - options - SSHPublicKeysClientListByResourceGroupOptions contains the optional parameters for the SSHPublicKeysClient.NewListByResourceGroupPager
// method.
func (client *SSHPublicKeysClient) NewListByResourceGroupPager(resourceGroupName string, options *SSHPublicKeysClientListByResourceGroupOptions) *runtime.Pager[SSHPublicKeysClientListByResourceGroupResponse] {
return runtime.NewPager(runtime.PagingHandler[SSHPublicKeysClientListByResourceGroupResponse]{
More: func(page SSHPublicKeysClientListByResourceGroupResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *SSHPublicKeysClientListByResourceGroupResponse) (SSHPublicKeysClientListByResourceGroupResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SSHPublicKeysClient.NewListByResourceGroupPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options)
}, nil)
if err != nil {
return SSHPublicKeysClientListByResourceGroupResponse{}, err
}
return client.listByResourceGroupHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *SSHPublicKeysClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *SSHPublicKeysClientListByResourceGroupOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/sshPublicKeys"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *SSHPublicKeysClient) listByResourceGroupHandleResponse(resp *http.Response) (SSHPublicKeysClientListByResourceGroupResponse, error) {
result := SSHPublicKeysClientListByResourceGroupResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SSHPublicKeysGroupListResult); err != nil {
return SSHPublicKeysClientListByResourceGroupResponse{}, err
}
return result, nil
}
// NewListBySubscriptionPager - Lists all of the SSH public keys in the subscription. Use the nextLink property in the response
// to get the next page of SSH public keys.
//
// Generated from API version 2023-07-01
// - options - SSHPublicKeysClientListBySubscriptionOptions contains the optional parameters for the SSHPublicKeysClient.NewListBySubscriptionPager
// method.
func (client *SSHPublicKeysClient) NewListBySubscriptionPager(options *SSHPublicKeysClientListBySubscriptionOptions) *runtime.Pager[SSHPublicKeysClientListBySubscriptionResponse] {
return runtime.NewPager(runtime.PagingHandler[SSHPublicKeysClientListBySubscriptionResponse]{
More: func(page SSHPublicKeysClientListBySubscriptionResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *SSHPublicKeysClientListBySubscriptionResponse) (SSHPublicKeysClientListBySubscriptionResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SSHPublicKeysClient.NewListBySubscriptionPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listBySubscriptionCreateRequest(ctx, options)
}, nil)
if err != nil {
return SSHPublicKeysClientListBySubscriptionResponse{}, err
}
return client.listBySubscriptionHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listBySubscriptionCreateRequest creates the ListBySubscription request.
func (client *SSHPublicKeysClient) listBySubscriptionCreateRequest(ctx context.Context, options *SSHPublicKeysClientListBySubscriptionOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/sshPublicKeys"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listBySubscriptionHandleResponse handles the ListBySubscription response.
func (client *SSHPublicKeysClient) listBySubscriptionHandleResponse(resp *http.Response) (SSHPublicKeysClientListBySubscriptionResponse, error) {
result := SSHPublicKeysClientListBySubscriptionResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SSHPublicKeysGroupListResult); err != nil {
return SSHPublicKeysClientListBySubscriptionResponse{}, err
}
return result, nil
}
// Update - Updates a new SSH public key resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - sshPublicKeyName - The name of the SSH public key.
// - parameters - Parameters supplied to update the SSH public key.
// - options - SSHPublicKeysClientUpdateOptions contains the optional parameters for the SSHPublicKeysClient.Update method.
func (client *SSHPublicKeysClient) Update(ctx context.Context, resourceGroupName string, sshPublicKeyName string, parameters SSHPublicKeyUpdateResource, options *SSHPublicKeysClientUpdateOptions) (SSHPublicKeysClientUpdateResponse, error) {
var err error
const operationName = "SSHPublicKeysClient.Update"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, sshPublicKeyName, parameters, options)
if err != nil {
return SSHPublicKeysClientUpdateResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return SSHPublicKeysClientUpdateResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return SSHPublicKeysClientUpdateResponse{}, err
}
resp, err := client.updateHandleResponse(httpResp)
return resp, err
}
// updateCreateRequest creates the Update request.
func (client *SSHPublicKeysClient) updateCreateRequest(ctx context.Context, resourceGroupName string, sshPublicKeyName string, parameters SSHPublicKeyUpdateResource, options *SSHPublicKeysClientUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/sshPublicKeys/{sshPublicKeyName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if sshPublicKeyName == "" {
return nil, errors.New("parameter sshPublicKeyName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{sshPublicKeyName}", url.PathEscape(sshPublicKeyName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, parameters); err != nil {
return nil, err
}
return req, nil
}
// updateHandleResponse handles the Update response.
func (client *SSHPublicKeysClient) updateHandleResponse(resp *http.Response) (SSHPublicKeysClientUpdateResponse, error) {
result := SSHPublicKeysClientUpdateResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.SSHPublicKeyResource); err != nil {
return SSHPublicKeysClientUpdateResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,86 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"encoding/json"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"reflect"
"regexp"
"strings"
"time"
)
// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases.
var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`)
const (
utcDateTimeJSON = `"2006-01-02T15:04:05.999999999"`
utcDateTime = "2006-01-02T15:04:05.999999999"
dateTimeJSON = `"` + time.RFC3339Nano + `"`
)
type dateTimeRFC3339 time.Time
func (t dateTimeRFC3339) MarshalJSON() ([]byte, error) {
tt := time.Time(t)
return tt.MarshalJSON()
}
func (t dateTimeRFC3339) MarshalText() ([]byte, error) {
tt := time.Time(t)
return tt.MarshalText()
}
func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error {
layout := utcDateTimeJSON
if tzOffsetRegex.Match(data) {
layout = dateTimeJSON
}
return t.Parse(layout, string(data))
}
func (t *dateTimeRFC3339) UnmarshalText(data []byte) error {
layout := utcDateTime
if tzOffsetRegex.Match(data) {
layout = time.RFC3339Nano
}
return t.Parse(layout, string(data))
}
func (t *dateTimeRFC3339) Parse(layout, value string) error {
p, err := time.Parse(layout, strings.ToUpper(value))
*t = dateTimeRFC3339(p)
return err
}
func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) {
if t == nil {
return
} else if azcore.IsNullValue(t) {
m[k] = nil
return
} else if reflect.ValueOf(t).IsNil() {
return
}
m[k] = (*dateTimeRFC3339)(t)
}
func unpopulateDateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error {
if data == nil || strings.EqualFold(string(data), "null") {
return nil
}
var aux dateTimeRFC3339
if err := json.Unmarshal(data, &aux); err != nil {
return fmt.Errorf("struct field %s: %v", fn, err)
}
*t = (*time.Time)(&aux)
return nil
}

View file

@ -0,0 +1,105 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// UsageClient contains the methods for the Usage group.
// Don't use this type directly, use NewUsageClient() instead.
type UsageClient struct {
internal *arm.Client
subscriptionID string
}
// NewUsageClient creates a new instance of UsageClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewUsageClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*UsageClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &UsageClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// NewListPager - Gets, for the specified location, the current compute resource usage information as well as the limits for
// compute resources under the subscription.
//
// Generated from API version 2023-07-01
// - location - The location for which resource usage is queried.
// - options - UsageClientListOptions contains the optional parameters for the UsageClient.NewListPager method.
func (client *UsageClient) NewListPager(location string, options *UsageClientListOptions) *runtime.Pager[UsageClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[UsageClientListResponse]{
More: func(page UsageClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *UsageClientListResponse) (UsageClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "UsageClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, location, options)
}, nil)
if err != nil {
return UsageClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
}
// listCreateRequest creates the List request.
func (client *UsageClient) listCreateRequest(ctx context.Context, location string, options *UsageClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/usages"
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *UsageClient) listHandleResponse(resp *http.Response) (UsageClientListResponse, error) {
result := UsageClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.ListUsagesResult); err != nil {
return UsageClientListResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,259 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strconv"
"strings"
)
// VirtualMachineExtensionImagesClient contains the methods for the VirtualMachineExtensionImages group.
// Don't use this type directly, use NewVirtualMachineExtensionImagesClient() instead.
type VirtualMachineExtensionImagesClient struct {
internal *arm.Client
subscriptionID string
}
// NewVirtualMachineExtensionImagesClient creates a new instance of VirtualMachineExtensionImagesClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewVirtualMachineExtensionImagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineExtensionImagesClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &VirtualMachineExtensionImagesClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// Get - Gets a virtual machine extension image.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - location - The name of a supported Azure region.
// - options - VirtualMachineExtensionImagesClientGetOptions contains the optional parameters for the VirtualMachineExtensionImagesClient.Get
// method.
func (client *VirtualMachineExtensionImagesClient) Get(ctx context.Context, location string, publisherName string, typeParam string, version string, options *VirtualMachineExtensionImagesClientGetOptions) (VirtualMachineExtensionImagesClientGetResponse, error) {
var err error
const operationName = "VirtualMachineExtensionImagesClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, location, publisherName, typeParam, version, options)
if err != nil {
return VirtualMachineExtensionImagesClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return VirtualMachineExtensionImagesClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return VirtualMachineExtensionImagesClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *VirtualMachineExtensionImagesClient) getCreateRequest(ctx context.Context, location string, publisherName string, typeParam string, version string, options *VirtualMachineExtensionImagesClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types/{type}/versions/{version}"
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if publisherName == "" {
return nil, errors.New("parameter publisherName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName))
if typeParam == "" {
return nil, errors.New("parameter typeParam cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{type}", url.PathEscape(typeParam))
if version == "" {
return nil, errors.New("parameter version cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{version}", url.PathEscape(version))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *VirtualMachineExtensionImagesClient) getHandleResponse(resp *http.Response) (VirtualMachineExtensionImagesClientGetResponse, error) {
result := VirtualMachineExtensionImagesClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineExtensionImage); err != nil {
return VirtualMachineExtensionImagesClientGetResponse{}, err
}
return result, nil
}
// ListTypes - Gets a list of virtual machine extension image types.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - location - The name of a supported Azure region.
// - options - VirtualMachineExtensionImagesClientListTypesOptions contains the optional parameters for the VirtualMachineExtensionImagesClient.ListTypes
// method.
func (client *VirtualMachineExtensionImagesClient) ListTypes(ctx context.Context, location string, publisherName string, options *VirtualMachineExtensionImagesClientListTypesOptions) (VirtualMachineExtensionImagesClientListTypesResponse, error) {
var err error
const operationName = "VirtualMachineExtensionImagesClient.ListTypes"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.listTypesCreateRequest(ctx, location, publisherName, options)
if err != nil {
return VirtualMachineExtensionImagesClientListTypesResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return VirtualMachineExtensionImagesClientListTypesResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return VirtualMachineExtensionImagesClientListTypesResponse{}, err
}
resp, err := client.listTypesHandleResponse(httpResp)
return resp, err
}
// listTypesCreateRequest creates the ListTypes request.
func (client *VirtualMachineExtensionImagesClient) listTypesCreateRequest(ctx context.Context, location string, publisherName string, options *VirtualMachineExtensionImagesClientListTypesOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types"
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if publisherName == "" {
return nil, errors.New("parameter publisherName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listTypesHandleResponse handles the ListTypes response.
func (client *VirtualMachineExtensionImagesClient) listTypesHandleResponse(resp *http.Response) (VirtualMachineExtensionImagesClientListTypesResponse, error) {
result := VirtualMachineExtensionImagesClientListTypesResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineExtensionImageArray); err != nil {
return VirtualMachineExtensionImagesClientListTypesResponse{}, err
}
return result, nil
}
// ListVersions - Gets a list of virtual machine extension image versions.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - location - The name of a supported Azure region.
// - options - VirtualMachineExtensionImagesClientListVersionsOptions contains the optional parameters for the VirtualMachineExtensionImagesClient.ListVersions
// method.
func (client *VirtualMachineExtensionImagesClient) ListVersions(ctx context.Context, location string, publisherName string, typeParam string, options *VirtualMachineExtensionImagesClientListVersionsOptions) (VirtualMachineExtensionImagesClientListVersionsResponse, error) {
var err error
const operationName = "VirtualMachineExtensionImagesClient.ListVersions"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.listVersionsCreateRequest(ctx, location, publisherName, typeParam, options)
if err != nil {
return VirtualMachineExtensionImagesClientListVersionsResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return VirtualMachineExtensionImagesClientListVersionsResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return VirtualMachineExtensionImagesClientListVersionsResponse{}, err
}
resp, err := client.listVersionsHandleResponse(httpResp)
return resp, err
}
// listVersionsCreateRequest creates the ListVersions request.
func (client *VirtualMachineExtensionImagesClient) listVersionsCreateRequest(ctx context.Context, location string, publisherName string, typeParam string, options *VirtualMachineExtensionImagesClientListVersionsOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types/{type}/versions"
if location == "" {
return nil, errors.New("parameter location cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
if publisherName == "" {
return nil, errors.New("parameter publisherName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName))
if typeParam == "" {
return nil, errors.New("parameter typeParam cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{type}", url.PathEscape(typeParam))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
if options != nil && options.Filter != nil {
reqQP.Set("$filter", *options.Filter)
}
if options != nil && options.Top != nil {
reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10))
}
if options != nil && options.Orderby != nil {
reqQP.Set("$orderby", *options.Orderby)
}
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listVersionsHandleResponse handles the ListVersions response.
func (client *VirtualMachineExtensionImagesClient) listVersionsHandleResponse(resp *http.Response) (VirtualMachineExtensionImagesClientListVersionsResponse, error) {
result := VirtualMachineExtensionImagesClientListVersionsResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineExtensionImageArray); err != nil {
return VirtualMachineExtensionImagesClientListVersionsResponse{}, err
}
return result, nil
}

View file

@ -0,0 +1,437 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armcompute
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// VirtualMachineExtensionsClient contains the methods for the VirtualMachineExtensions group.
// Don't use this type directly, use NewVirtualMachineExtensionsClient() instead.
type VirtualMachineExtensionsClient struct {
internal *arm.Client
subscriptionID string
}
// NewVirtualMachineExtensionsClient creates a new instance of VirtualMachineExtensionsClient with the specified values.
// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// - credential - used to authorize requests. Usually a credential from azidentity.
// - options - pass nil to accept the default values.
func NewVirtualMachineExtensionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineExtensionsClient, error) {
cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
if err != nil {
return nil, err
}
client := &VirtualMachineExtensionsClient{
subscriptionID: subscriptionID,
internal: cl,
}
return client, nil
}
// BeginCreateOrUpdate - The operation to create or update the extension.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - vmName - The name of the virtual machine where the extension should be created or updated.
// - vmExtensionName - The name of the virtual machine extension.
// - extensionParameters - Parameters supplied to the Create Virtual Machine Extension operation.
// - options - VirtualMachineExtensionsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachineExtensionsClient.BeginCreateOrUpdate
// method.
func (client *VirtualMachineExtensionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtension, options *VirtualMachineExtensionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualMachineExtensionsClientCreateOrUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.createOrUpdate(ctx, resourceGroupName, vmName, vmExtensionName, extensionParameters, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineExtensionsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineExtensionsClientCreateOrUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// CreateOrUpdate - The operation to create or update the extension.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *VirtualMachineExtensionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtension, options *VirtualMachineExtensionsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
var err error
const operationName = "VirtualMachineExtensionsClient.BeginCreateOrUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, vmName, vmExtensionName, extensionParameters, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *VirtualMachineExtensionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtension, options *VirtualMachineExtensionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if vmName == "" {
return nil, errors.New("parameter vmName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName))
if vmExtensionName == "" {
return nil, errors.New("parameter vmExtensionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{vmExtensionName}", url.PathEscape(vmExtensionName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, extensionParameters); err != nil {
return nil, err
}
return req, nil
}
// BeginDelete - The operation to delete the extension.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - vmName - The name of the virtual machine where the extension should be deleted.
// - vmExtensionName - The name of the virtual machine extension.
// - options - VirtualMachineExtensionsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineExtensionsClient.BeginDelete
// method.
func (client *VirtualMachineExtensionsClient) BeginDelete(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, options *VirtualMachineExtensionsClientBeginDeleteOptions) (*runtime.Poller[VirtualMachineExtensionsClientDeleteResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.deleteOperation(ctx, resourceGroupName, vmName, vmExtensionName, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineExtensionsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineExtensionsClientDeleteResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Delete - The operation to delete the extension.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *VirtualMachineExtensionsClient) deleteOperation(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, options *VirtualMachineExtensionsClientBeginDeleteOptions) (*http.Response, error) {
var err error
const operationName = "VirtualMachineExtensionsClient.BeginDelete"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.deleteCreateRequest(ctx, resourceGroupName, vmName, vmExtensionName, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *VirtualMachineExtensionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, options *VirtualMachineExtensionsClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if vmName == "" {
return nil, errors.New("parameter vmName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName))
if vmExtensionName == "" {
return nil, errors.New("parameter vmExtensionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{vmExtensionName}", url.PathEscape(vmExtensionName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// Get - The operation to get the extension.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - vmName - The name of the virtual machine containing the extension.
// - vmExtensionName - The name of the virtual machine extension.
// - options - VirtualMachineExtensionsClientGetOptions contains the optional parameters for the VirtualMachineExtensionsClient.Get
// method.
func (client *VirtualMachineExtensionsClient) Get(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, options *VirtualMachineExtensionsClientGetOptions) (VirtualMachineExtensionsClientGetResponse, error) {
var err error
const operationName = "VirtualMachineExtensionsClient.Get"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.getCreateRequest(ctx, resourceGroupName, vmName, vmExtensionName, options)
if err != nil {
return VirtualMachineExtensionsClientGetResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return VirtualMachineExtensionsClientGetResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return VirtualMachineExtensionsClientGetResponse{}, err
}
resp, err := client.getHandleResponse(httpResp)
return resp, err
}
// getCreateRequest creates the Get request.
func (client *VirtualMachineExtensionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, options *VirtualMachineExtensionsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if vmName == "" {
return nil, errors.New("parameter vmName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName))
if vmExtensionName == "" {
return nil, errors.New("parameter vmExtensionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{vmExtensionName}", url.PathEscape(vmExtensionName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
if options != nil && options.Expand != nil {
reqQP.Set("$expand", *options.Expand)
}
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// getHandleResponse handles the Get response.
func (client *VirtualMachineExtensionsClient) getHandleResponse(resp *http.Response) (VirtualMachineExtensionsClientGetResponse, error) {
result := VirtualMachineExtensionsClientGetResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineExtension); err != nil {
return VirtualMachineExtensionsClientGetResponse{}, err
}
return result, nil
}
// List - The operation to get all extensions of a Virtual Machine.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - vmName - The name of the virtual machine containing the extension.
// - options - VirtualMachineExtensionsClientListOptions contains the optional parameters for the VirtualMachineExtensionsClient.List
// method.
func (client *VirtualMachineExtensionsClient) List(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachineExtensionsClientListOptions) (VirtualMachineExtensionsClientListResponse, error) {
var err error
const operationName = "VirtualMachineExtensionsClient.List"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.listCreateRequest(ctx, resourceGroupName, vmName, options)
if err != nil {
return VirtualMachineExtensionsClientListResponse{}, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return VirtualMachineExtensionsClientListResponse{}, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return VirtualMachineExtensionsClientListResponse{}, err
}
resp, err := client.listHandleResponse(httpResp)
return resp, err
}
// listCreateRequest creates the List request.
func (client *VirtualMachineExtensionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachineExtensionsClientListOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if vmName == "" {
return nil, errors.New("parameter vmName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
if options != nil && options.Expand != nil {
reqQP.Set("$expand", *options.Expand)
}
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
return req, nil
}
// listHandleResponse handles the List response.
func (client *VirtualMachineExtensionsClient) listHandleResponse(resp *http.Response) (VirtualMachineExtensionsClientListResponse, error) {
result := VirtualMachineExtensionsClientListResponse{}
if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineExtensionsListResult); err != nil {
return VirtualMachineExtensionsClientListResponse{}, err
}
return result, nil
}
// BeginUpdate - The operation to update the extension.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
// - resourceGroupName - The name of the resource group.
// - vmName - The name of the virtual machine where the extension should be updated.
// - vmExtensionName - The name of the virtual machine extension.
// - extensionParameters - Parameters supplied to the Update Virtual Machine Extension operation.
// - options - VirtualMachineExtensionsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineExtensionsClient.BeginUpdate
// method.
func (client *VirtualMachineExtensionsClient) BeginUpdate(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtensionUpdate, options *VirtualMachineExtensionsClientBeginUpdateOptions) (*runtime.Poller[VirtualMachineExtensionsClientUpdateResponse], error) {
if options == nil || options.ResumeToken == "" {
resp, err := client.update(ctx, resourceGroupName, vmName, vmExtensionName, extensionParameters, options)
if err != nil {
return nil, err
}
poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineExtensionsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
return poller, err
} else {
return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineExtensionsClientUpdateResponse]{
Tracer: client.internal.Tracer(),
})
}
}
// Update - The operation to update the extension.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-07-01
func (client *VirtualMachineExtensionsClient) update(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtensionUpdate, options *VirtualMachineExtensionsClientBeginUpdateOptions) (*http.Response, error) {
var err error
const operationName = "VirtualMachineExtensionsClient.BeginUpdate"
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
defer func() { endSpan(err) }()
req, err := client.updateCreateRequest(ctx, resourceGroupName, vmName, vmExtensionName, extensionParameters, options)
if err != nil {
return nil, err
}
httpResp, err := client.internal.Pipeline().Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(httpResp, http.StatusOK) {
err = runtime.NewResponseError(httpResp)
return nil, err
}
return httpResp, nil
}
// updateCreateRequest creates the Update request.
func (client *VirtualMachineExtensionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtensionUpdate, options *VirtualMachineExtensionsClientBeginUpdateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}"
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if vmName == "" {
return nil, errors.New("parameter vmName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName))
if vmExtensionName == "" {
return nil, errors.New("parameter vmExtensionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{vmExtensionName}", url.PathEscape(vmExtensionName))
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2023-07-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header["Accept"] = []string{"application/json"}
if err := runtime.MarshalAsJSON(req, extensionParameters); err != nil {
return nil, err
}
return req, nil
}

Some files were not shown because too many files have changed in this diff Show more