diff --git a/sdk/resourcemanager/terraform/armterraform/CHANGELOG.md b/sdk/resourcemanager/terraform/armterraform/CHANGELOG.md new file mode 100644 index 000000000000..d3688297184a --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2024-11-14) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/terraform/armterraform` is using our [next generation design principles](https://azure.github.io/azure-sdk/general_introduction.html). + +To learn more, please refer to our documentation [Quick Start](https://aka.ms/azsdk/go/mgmt). \ No newline at end of file diff --git a/sdk/resourcemanager/terraform/armterraform/LICENSE.txt b/sdk/resourcemanager/terraform/armterraform/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/LICENSE.txt @@ -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. \ No newline at end of file diff --git a/sdk/resourcemanager/terraform/armterraform/README.md b/sdk/resourcemanager/terraform/armterraform/README.md new file mode 100644 index 000000000000..9a59acbf0311 --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/README.md @@ -0,0 +1,92 @@ +# Azure Terraform Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/terraform/armterraform)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/terraform/armterraform) + +The `armterraform` module provides operations for working with Azure Terraform. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/terraform/armterraform) + +# 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 Terraform module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/terraform/armterraform +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Terraform. 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 Terraform 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 := armterraform.NewClientFactory(, 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 := armterraform.NewClientFactory(, 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.NewTerraformClient() +``` + +## 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. + +## 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 `Terraform` 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. \ No newline at end of file diff --git a/sdk/resourcemanager/terraform/armterraform/ci.yml b/sdk/resourcemanager/terraform/armterraform/ci.yml new file mode 100644 index 000000000000..1314869f6702 --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/ci.yml @@ -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/terraform/armterraform/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/terraform/armterraform/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + IncludeRelease: true + ServiceDirectory: 'resourcemanager/terraform/armterraform' diff --git a/sdk/resourcemanager/terraform/armterraform/client_factory.go b/sdk/resourcemanager/terraform/armterraform/client_factory.go new file mode 100644 index 000000000000..651f7e38a8cf --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/client_factory.go @@ -0,0 +1,48 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armterraform + +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 + internal *arm.Client +} + +// 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 - The ID of the target subscription. The value must be an UUID. +// - 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) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewTerraformClient creates a new instance of TerraformClient. +func (c *ClientFactory) NewTerraformClient() *TerraformClient { + return &TerraformClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/sdk/resourcemanager/terraform/armterraform/constants.go b/sdk/resourcemanager/terraform/armterraform/constants.go new file mode 100644 index 000000000000..efe267036c2a --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/constants.go @@ -0,0 +1,130 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armterraform + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/terraform/armterraform" + moduleVersion = "v0.1.0" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// AuthorizationScopeFilter - The Azure Resource Graph Authorization Scope Filter parameter +type AuthorizationScopeFilter string + +const ( + // AuthorizationScopeFilterAtScopeAboveAndBelow - Returns assignments for the given scope, all parent scopes, and all child + // scopes. + AuthorizationScopeFilterAtScopeAboveAndBelow AuthorizationScopeFilter = "AtScopeAboveAndBelow" + // AuthorizationScopeFilterAtScopeAndAbove - Returns assignments for the given scope and all parent scopes, but not child + // scopes. + AuthorizationScopeFilterAtScopeAndAbove AuthorizationScopeFilter = "AtScopeAndAbove" + // AuthorizationScopeFilterAtScopeAndBelow - Returns assignments for the given scope and all child scopes. + AuthorizationScopeFilterAtScopeAndBelow AuthorizationScopeFilter = "AtScopeAndBelow" + // AuthorizationScopeFilterAtScopeExact - Returns assignments only for the given scope; no parent or child scopes are included. + AuthorizationScopeFilterAtScopeExact AuthorizationScopeFilter = "AtScopeExact" +) + +// PossibleAuthorizationScopeFilterValues returns the possible values for the AuthorizationScopeFilter const type. +func PossibleAuthorizationScopeFilterValues() []AuthorizationScopeFilter { + return []AuthorizationScopeFilter{ + AuthorizationScopeFilterAtScopeAboveAndBelow, + AuthorizationScopeFilterAtScopeAndAbove, + AuthorizationScopeFilterAtScopeAndBelow, + AuthorizationScopeFilterAtScopeExact, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// ResourceProvisioningState - The provisioning state of a resource type. +type ResourceProvisioningState string + +const ( + // ResourceProvisioningStateCanceled - Resource creation was canceled. + ResourceProvisioningStateCanceled ResourceProvisioningState = "Canceled" + // ResourceProvisioningStateFailed - Resource creation failed. + ResourceProvisioningStateFailed ResourceProvisioningState = "Failed" + // ResourceProvisioningStateSucceeded - Resource has been created. + ResourceProvisioningStateSucceeded ResourceProvisioningState = "Succeeded" +) + +// PossibleResourceProvisioningStateValues returns the possible values for the ResourceProvisioningState const type. +func PossibleResourceProvisioningStateValues() []ResourceProvisioningState { + return []ResourceProvisioningState{ + ResourceProvisioningStateCanceled, + ResourceProvisioningStateFailed, + ResourceProvisioningStateSucceeded, + } +} + +// TargetProvider - The target Azure Terraform Provider +type TargetProvider string + +const ( + // TargetProviderAzapi - https://registry.terraform.io/providers/Azure/azapi/latest + TargetProviderAzapi TargetProvider = "azapi" + // TargetProviderAzurerm - https://registry.terraform.io/providers/hashicorp/azurerm/latest + TargetProviderAzurerm TargetProvider = "azurerm" +) + +// PossibleTargetProviderValues returns the possible values for the TargetProvider const type. +func PossibleTargetProviderValues() []TargetProvider { + return []TargetProvider{ + TargetProviderAzapi, + TargetProviderAzurerm, + } +} + +// Type - The parameter type +type Type string + +const ( + TypeExportQuery Type = "ExportQuery" + TypeExportResource Type = "ExportResource" + TypeExportResourceGroup Type = "ExportResourceGroup" +) + +// PossibleTypeValues returns the possible values for the Type const type. +func PossibleTypeValues() []Type { + return []Type{ + TypeExportQuery, + TypeExportResource, + TypeExportResourceGroup, + } +} diff --git a/sdk/resourcemanager/terraform/armterraform/fake/internal.go b/sdk/resourcemanager/terraform/armterraform/fake/internal.go new file mode 100644 index 000000000000..1ffebab5709c --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/fake/internal.go @@ -0,0 +1,78 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "io" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func contains[T comparable](s []T, v T) bool { + for _, vv := range s { + if vv == v { + return true + } + } + return false +} + +func readRequestBody(req *http.Request) ([]byte, error) { + if req.Body == nil { + return nil, nil + } + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + req.Body.Close() + return body, nil +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/sdk/resourcemanager/terraform/armterraform/fake/operations_server.go b/sdk/resourcemanager/terraform/armterraform/fake/operations_server.go new file mode 100644 index 000000000000..d04a92198df0 --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/fake/operations_server.go @@ -0,0 +1,117 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/terraform/armterraform" + "net/http" +) + +// OperationsServer is a fake server for instances of the armterraform.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armterraform.OperationsClientListOptions) (resp azfake.PagerResponder[armterraform.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armterraform.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armterraform.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armterraform.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armterraform.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armterraform.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/terraform/armterraform/fake/polymorphic_helpers.go b/sdk/resourcemanager/terraform/armterraform/fake/polymorphic_helpers.go new file mode 100644 index 000000000000..dff235021ac1 --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/fake/polymorphic_helpers.go @@ -0,0 +1,35 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "encoding/json" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/terraform/armterraform" +) + +func unmarshalBaseExportModelClassification(rawMsg json.RawMessage) (armterraform.BaseExportModelClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b armterraform.BaseExportModelClassification + switch m["type"] { + case string(armterraform.TypeExportQuery): + b = &armterraform.ExportQuery{} + case string(armterraform.TypeExportResource): + b = &armterraform.ExportResource{} + case string(armterraform.TypeExportResourceGroup): + b = &armterraform.ExportResourceGroup{} + default: + b = &armterraform.BaseExportModel{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/sdk/resourcemanager/terraform/armterraform/fake/server_factory.go b/sdk/resourcemanager/terraform/armterraform/fake/server_factory.go new file mode 100644 index 000000000000..73b68792b62b --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/fake/server_factory.go @@ -0,0 +1,79 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armterraform.ClientFactory type. +type ServerFactory struct { + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // TerraformServer contains the fakes for client TerraformClient + TerraformServer TerraformServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armterraform.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armterraform.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trOperationsServer *OperationsServerTransport + trTerraformServer *TerraformServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "OperationsClient": + initServer(s, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "TerraformClient": + initServer(s, &s.trTerraformServer, func() *TerraformServerTransport { return NewTerraformServerTransport(&s.srv.TerraformServer) }) + resp, err = s.trTerraformServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +func initServer[T any](s *ServerFactoryTransport, dst **T, src func() *T) { + s.trMu.Lock() + if *dst == nil { + *dst = src() + } + s.trMu.Unlock() +} diff --git a/sdk/resourcemanager/terraform/armterraform/fake/terraform_server.go b/sdk/resourcemanager/terraform/armterraform/fake/terraform_server.go new file mode 100644 index 000000000000..ab052040f9cd --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/fake/terraform_server.go @@ -0,0 +1,135 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/terraform/armterraform" + "net/http" + "regexp" +) + +// TerraformServer is a fake server for instances of the armterraform.TerraformClient type. +type TerraformServer struct { + // BeginExportTerraform is the fake for method TerraformClient.BeginExportTerraform + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginExportTerraform func(ctx context.Context, body armterraform.BaseExportModelClassification, options *armterraform.TerraformClientBeginExportTerraformOptions) (resp azfake.PollerResponder[armterraform.TerraformClientExportTerraformResponse], errResp azfake.ErrorResponder) +} + +// NewTerraformServerTransport creates a new instance of TerraformServerTransport with the provided implementation. +// The returned TerraformServerTransport instance is connected to an instance of armterraform.TerraformClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewTerraformServerTransport(srv *TerraformServer) *TerraformServerTransport { + return &TerraformServerTransport{ + srv: srv, + beginExportTerraform: newTracker[azfake.PollerResponder[armterraform.TerraformClientExportTerraformResponse]](), + } +} + +// TerraformServerTransport connects instances of armterraform.TerraformClient to instances of TerraformServer. +// Don't use this type directly, use NewTerraformServerTransport instead. +type TerraformServerTransport struct { + srv *TerraformServer + beginExportTerraform *tracker[azfake.PollerResponder[armterraform.TerraformClientExportTerraformResponse]] +} + +// Do implements the policy.Transporter interface for TerraformServerTransport. +func (t *TerraformServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return t.dispatchToMethodFake(req, method) +} + +func (t *TerraformServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if terraformServerTransportInterceptor != nil { + res.resp, res.err, intercepted = terraformServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "TerraformClient.BeginExportTerraform": + res.resp, res.err = t.dispatchBeginExportTerraform(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (t *TerraformServerTransport) dispatchBeginExportTerraform(req *http.Request) (*http.Response, error) { + if t.srv.BeginExportTerraform == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginExportTerraform not implemented")} + } + beginExportTerraform := t.beginExportTerraform.get(req) + if beginExportTerraform == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureTerraform/exportTerraform` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + raw, err := readRequestBody(req) + if err != nil { + return nil, err + } + body, err := unmarshalBaseExportModelClassification(raw) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.BeginExportTerraform(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginExportTerraform = &respr + t.beginExportTerraform.add(req, beginExportTerraform) + } + + resp, err := server.PollerResponderNext(beginExportTerraform, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + t.beginExportTerraform.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginExportTerraform) { + t.beginExportTerraform.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to TerraformServerTransport +var terraformServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/terraform/armterraform/fake/time_rfc3339.go b/sdk/resourcemanager/terraform/armterraform/fake/time_rfc3339.go new file mode 100644 index 000000000000..87ee11e83b32 --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/fake/time_rfc3339.go @@ -0,0 +1,109 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package fake + +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 ( + utcDateTime = "2006-01-02T15:04:05.999999999" + utcDateTimeJSON = `"` + utcDateTime + `"` + utcDateTimeNoT = "2006-01-02 15:04:05.999999999" + utcDateTimeJSONNoT = `"` + utcDateTimeNoT + `"` + dateTimeNoT = `2006-01-02 15:04:05.999999999Z07:00` + dateTimeJSON = `"` + time.RFC3339Nano + `"` + dateTimeJSONNoT = `"` + dateTimeNoT + `"` +) + +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 { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { + layout = dateTimeJSON + } else if tzOffset { + layout = dateTimeJSONNoT + } else if hasT { + layout = utcDateTimeJSON + } else { + layout = utcDateTimeJSONNoT + } + return t.Parse(layout, string(data)) +} + +func (t *dateTimeRFC3339) UnmarshalText(data []byte) error { + if len(data) == 0 { + return nil + } + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { + layout = time.RFC3339Nano + } else if tzOffset { + layout = dateTimeNoT + } else if hasT { + layout = utcDateTime + } else { + layout = utcDateTimeNoT + } + 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 (t dateTimeRFC3339) String() string { + return time.Time(t).Format(time.RFC3339Nano) +} + +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 || 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 +} diff --git a/sdk/resourcemanager/terraform/armterraform/go.mod b/sdk/resourcemanager/terraform/armterraform/go.mod new file mode 100644 index 000000000000..1c893c50d6c4 --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/go.mod @@ -0,0 +1,21 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/terraform/armterraform + +go 1.18 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 // indirect + github.com/golang-jwt/jwt/v5 v5.2.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect + golang.org/x/crypto v0.27.0 // indirect + golang.org/x/net v0.29.0 // indirect + golang.org/x/sys v0.25.0 // indirect + golang.org/x/text v0.18.0 // indirect +) diff --git a/sdk/resourcemanager/terraform/armterraform/go.sum b/sdk/resourcemanager/terraform/armterraform/go.sum new file mode 100644 index 000000000000..cbddbbd9ecec --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/go.sum @@ -0,0 +1,29 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0 h1:JZg6HRh6W6U4OLl6lk7BZ7BLisIzM9dG1R50zUk9C/M= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0/go.mod h1:YL1xnZ6QejvQHWJrX/AvhFl4WW4rqHVoKspWNVwFk0M= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 h1:tfLQ34V6F7tVSwoTf/4lH5sE0o6eCJuNDTmH09nDpbc= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0/go.mod h1:9kIvujWAA58nmPmWB1m23fyWic1kYZMxD9CxaWn4Qpg= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 h1:ywEEhmNahHBihViHepv3xPBn1663uRv2t2q/ESv9seY= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0/go.mod h1:iZDifYGJTIgIIkYRNWPENUnqx6bJ2xnSDFI2tjwZNuY= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 h1:XHOnouVk1mxXfQidrMEnLlPk9UMeRtyBTnEFtxkV0kU= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +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/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= +golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= +golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo= +golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= +golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/sdk/resourcemanager/terraform/armterraform/interfaces.go b/sdk/resourcemanager/terraform/armterraform/interfaces.go new file mode 100644 index 000000000000..fbad2bda44b1 --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/interfaces.go @@ -0,0 +1,14 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armterraform + +// BaseExportModelClassification provides polymorphic access to related types. +// Call the interface's GetBaseExportModel() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *BaseExportModel, *ExportQuery, *ExportResource, *ExportResourceGroup +type BaseExportModelClassification interface { + // GetBaseExportModel returns the BaseExportModel content of the underlying type. + GetBaseExportModel() *BaseExportModel +} diff --git a/sdk/resourcemanager/terraform/armterraform/models.go b/sdk/resourcemanager/terraform/armterraform/models.go new file mode 100644 index 000000000000..912800886934 --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/models.go @@ -0,0 +1,262 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armterraform + +import "time" + +// BaseExportModel - The base export parameter +type BaseExportModel struct { + // REQUIRED; The parameter type + Type *Type + + // Whether to output all non-computed properties in the generated Terraform configuration? This probably needs manual modifications + // to make it valid + FullProperties *bool + + // Mask sensitive attributes in the Terraform configuration + MaskSensitive *bool + + // The target Azure Terraform Provider + TargetProvider *TargetProvider +} + +// GetBaseExportModel implements the BaseExportModelClassification interface for type BaseExportModel. +func (b *BaseExportModel) GetBaseExportModel() *BaseExportModel { return b } + +// ErrorAdditionalInfo - The resource management error additional info. +type ErrorAdditionalInfo struct { + // READ-ONLY; The additional info. + Info *ErrorAdditionalInfoInfo + + // READ-ONLY; The additional info type. + Type *string +} + +type ErrorAdditionalInfoInfo struct { +} + +// ErrorDetail - The error detail. +type ErrorDetail struct { + // READ-ONLY; The error additional info. + AdditionalInfo []*ErrorAdditionalInfo + + // READ-ONLY; The error code. + Code *string + + // READ-ONLY; The error details. + Details []*ErrorDetail + + // READ-ONLY; The error message. + Message *string + + // READ-ONLY; The error target. + Target *string +} + +// ExportQuery - Export parameter for resources queried by ARG (Azure Resource Graph) +type ExportQuery struct { + // REQUIRED; The ARG where predicate. Note that you can combine multiple conditions in one `where` predicate, e.g. `resourceGroup + // =~ "my-rg" and type =~ "microsoft.network/virtualnetworks"` + Query *string + + // CONSTANT; The parameter type + // Field has constant value TypeExportQuery, any specified value is ignored. + Type *Type + + // The ARG Scope Filter parameter + AuthorizationScopeFilter *AuthorizationScopeFilter + + // Whether to output all non-computed properties in the generated Terraform configuration? This probably needs manual modifications + // to make it valid + FullProperties *bool + + // Mask sensitive attributes in the Terraform configuration + MaskSensitive *bool + + // The name pattern of the Terraform resources + NamePattern *string + + // Whether to recursively list child resources of the query result + Recursive *bool + + // The ARG table name + Table *string + + // The target Azure Terraform Provider + TargetProvider *TargetProvider +} + +// GetBaseExportModel implements the BaseExportModelClassification interface for type ExportQuery. +func (e *ExportQuery) GetBaseExportModel() *BaseExportModel { + return &BaseExportModel{ + FullProperties: e.FullProperties, + MaskSensitive: e.MaskSensitive, + TargetProvider: e.TargetProvider, + Type: e.Type, + } +} + +// ExportResource - Export parameter for individual resources. +type ExportResource struct { + // REQUIRED; The id of the resource to be exported + ResourceIDs []*string + + // CONSTANT; The parameter type + // Field has constant value TypeExportResource, any specified value is ignored. + Type *Type + + // Whether to output all non-computed properties in the generated Terraform configuration? This probably needs manual modifications + // to make it valid + FullProperties *bool + + // Mask sensitive attributes in the Terraform configuration + MaskSensitive *bool + + // The name pattern of the Terraform resources + NamePattern *string + + // The Terraform resource name. Only works when `resourceIds` contains only one item. + ResourceName *string + + // The Terraform resource type. Only works when `resourceIds` contains only one item. + ResourceType *string + + // The target Azure Terraform Provider + TargetProvider *TargetProvider +} + +// GetBaseExportModel implements the BaseExportModelClassification interface for type ExportResource. +func (e *ExportResource) GetBaseExportModel() *BaseExportModel { + return &BaseExportModel{ + FullProperties: e.FullProperties, + MaskSensitive: e.MaskSensitive, + TargetProvider: e.TargetProvider, + Type: e.Type, + } +} + +// ExportResourceGroup - Export parameter for a resource group +type ExportResourceGroup struct { + // REQUIRED; The name of the resource group to be exported + ResourceGroupName *string + + // CONSTANT; The parameter type + // Field has constant value TypeExportResourceGroup, any specified value is ignored. + Type *Type + + // Whether to output all non-computed properties in the generated Terraform configuration? This probably needs manual modifications + // to make it valid + FullProperties *bool + + // Mask sensitive attributes in the Terraform configuration + MaskSensitive *bool + + // The name pattern of the Terraform resources + NamePattern *string + + // The target Azure Terraform Provider + TargetProvider *TargetProvider +} + +// GetBaseExportModel implements the BaseExportModelClassification interface for type ExportResourceGroup. +func (e *ExportResourceGroup) GetBaseExportModel() *BaseExportModel { + return &BaseExportModel{ + FullProperties: e.FullProperties, + MaskSensitive: e.MaskSensitive, + TargetProvider: e.TargetProvider, + Type: e.Type, + } +} + +// ExportResult - The Terraform export result +type ExportResult struct { + // The Terraform configuration content + Configuration *string + + // A list of errors derived during exporting each resource + Errors []*ErrorDetail + + // The Terraform import blocks for the current export, which users can use to run "terraform plan" with to import the resources + Import *string + + // A list of Azure resources which are not exported to Terraform due to there is no corresponding resources in Terraform + SkippedResources []*string +} + +// Operation - Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for and operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// OperationStatus - The status of the LRO operation. +type OperationStatus struct { + // REQUIRED; The operation status + Status *ResourceProvisioningState + + // READ-ONLY; The unique identifier for the operationStatus resource + ID *string + + // READ-ONLY; Operation complete time + EndTime *time.Time + + // READ-ONLY; Errors that occurred if the operation ended with Canceled or Failed status + Error *ErrorDetail + + // READ-ONLY; The name of the operationStatus resource + Name *string + + // READ-ONLY; The progress made toward completing the operation + PercentComplete *float64 + + // READ-ONLY; RP-specific properties for the operationStatus resource, only appears when operation ended with Succeeded status + Properties *ExportResult + + // READ-ONLY; Operation start time + StartTime *time.Time +} diff --git a/sdk/resourcemanager/terraform/armterraform/models_serde.go b/sdk/resourcemanager/terraform/armterraform/models_serde.go new file mode 100644 index 000000000000..70e13fcd3534 --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/models_serde.go @@ -0,0 +1,513 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armterraform + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type BaseExportModel. +func (b BaseExportModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "fullProperties", b.FullProperties) + populate(objectMap, "maskSensitive", b.MaskSensitive) + populate(objectMap, "targetProvider", b.TargetProvider) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BaseExportModel. +func (b *BaseExportModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "fullProperties": + err = unpopulate(val, "FullProperties", &b.FullProperties) + delete(rawMsg, key) + case "maskSensitive": + err = unpopulate(val, "MaskSensitive", &b.MaskSensitive) + delete(rawMsg, key) + case "targetProvider": + err = unpopulate(val, "TargetProvider", &b.TargetProvider) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &b.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorAdditionalInfo. +func (e ErrorAdditionalInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "info", e.Info) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorAdditionalInfo. +func (e *ErrorAdditionalInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "info": + err = unpopulate(val, "Info", &e.Info) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorDetail. +func (e ErrorDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalInfo", e.AdditionalInfo) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorDetail. +func (e *ErrorDetail) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalInfo": + err = unpopulate(val, "AdditionalInfo", &e.AdditionalInfo) + delete(rawMsg, key) + case "code": + err = unpopulate(val, "Code", &e.Code) + delete(rawMsg, key) + case "details": + err = unpopulate(val, "Details", &e.Details) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &e.Message) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &e.Target) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExportQuery. +func (e ExportQuery) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authorizationScopeFilter", e.AuthorizationScopeFilter) + populate(objectMap, "fullProperties", e.FullProperties) + populate(objectMap, "maskSensitive", e.MaskSensitive) + populate(objectMap, "namePattern", e.NamePattern) + populate(objectMap, "query", e.Query) + populate(objectMap, "recursive", e.Recursive) + populate(objectMap, "table", e.Table) + populate(objectMap, "targetProvider", e.TargetProvider) + objectMap["type"] = TypeExportQuery + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExportQuery. +func (e *ExportQuery) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authorizationScopeFilter": + err = unpopulate(val, "AuthorizationScopeFilter", &e.AuthorizationScopeFilter) + delete(rawMsg, key) + case "fullProperties": + err = unpopulate(val, "FullProperties", &e.FullProperties) + delete(rawMsg, key) + case "maskSensitive": + err = unpopulate(val, "MaskSensitive", &e.MaskSensitive) + delete(rawMsg, key) + case "namePattern": + err = unpopulate(val, "NamePattern", &e.NamePattern) + delete(rawMsg, key) + case "query": + err = unpopulate(val, "Query", &e.Query) + delete(rawMsg, key) + case "recursive": + err = unpopulate(val, "Recursive", &e.Recursive) + delete(rawMsg, key) + case "table": + err = unpopulate(val, "Table", &e.Table) + delete(rawMsg, key) + case "targetProvider": + err = unpopulate(val, "TargetProvider", &e.TargetProvider) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExportResource. +func (e ExportResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "fullProperties", e.FullProperties) + populate(objectMap, "maskSensitive", e.MaskSensitive) + populate(objectMap, "namePattern", e.NamePattern) + populate(objectMap, "resourceIds", e.ResourceIDs) + populate(objectMap, "resourceName", e.ResourceName) + populate(objectMap, "resourceType", e.ResourceType) + populate(objectMap, "targetProvider", e.TargetProvider) + objectMap["type"] = TypeExportResource + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExportResource. +func (e *ExportResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "fullProperties": + err = unpopulate(val, "FullProperties", &e.FullProperties) + delete(rawMsg, key) + case "maskSensitive": + err = unpopulate(val, "MaskSensitive", &e.MaskSensitive) + delete(rawMsg, key) + case "namePattern": + err = unpopulate(val, "NamePattern", &e.NamePattern) + delete(rawMsg, key) + case "resourceIds": + err = unpopulate(val, "ResourceIDs", &e.ResourceIDs) + delete(rawMsg, key) + case "resourceName": + err = unpopulate(val, "ResourceName", &e.ResourceName) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &e.ResourceType) + delete(rawMsg, key) + case "targetProvider": + err = unpopulate(val, "TargetProvider", &e.TargetProvider) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExportResourceGroup. +func (e ExportResourceGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "fullProperties", e.FullProperties) + populate(objectMap, "maskSensitive", e.MaskSensitive) + populate(objectMap, "namePattern", e.NamePattern) + populate(objectMap, "resourceGroupName", e.ResourceGroupName) + populate(objectMap, "targetProvider", e.TargetProvider) + objectMap["type"] = TypeExportResourceGroup + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExportResourceGroup. +func (e *ExportResourceGroup) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "fullProperties": + err = unpopulate(val, "FullProperties", &e.FullProperties) + delete(rawMsg, key) + case "maskSensitive": + err = unpopulate(val, "MaskSensitive", &e.MaskSensitive) + delete(rawMsg, key) + case "namePattern": + err = unpopulate(val, "NamePattern", &e.NamePattern) + delete(rawMsg, key) + case "resourceGroupName": + err = unpopulate(val, "ResourceGroupName", &e.ResourceGroupName) + delete(rawMsg, key) + case "targetProvider": + err = unpopulate(val, "TargetProvider", &e.TargetProvider) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExportResult. +func (e ExportResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "configuration", e.Configuration) + populate(objectMap, "errors", e.Errors) + populate(objectMap, "import", e.Import) + populate(objectMap, "skippedResources", e.SkippedResources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExportResult. +func (e *ExportResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "configuration": + err = unpopulate(val, "Configuration", &e.Configuration) + delete(rawMsg, key) + case "errors": + err = unpopulate(val, "Errors", &e.Errors) + delete(rawMsg, key) + case "import": + err = unpopulate(val, "Import", &e.Import) + delete(rawMsg, key) + case "skippedResources": + err = unpopulate(val, "SkippedResources", &e.SkippedResources) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationStatus. +func (o OperationStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "endTime", o.EndTime) + populate(objectMap, "error", o.Error) + populate(objectMap, "id", o.ID) + populate(objectMap, "name", o.Name) + populate(objectMap, "percentComplete", o.PercentComplete) + populate(objectMap, "properties", o.Properties) + populateDateTimeRFC3339(objectMap, "startTime", o.StartTime) + populate(objectMap, "status", o.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationStatus. +func (o *OperationStatus) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &o.EndTime) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &o.Error) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &o.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "percentComplete": + err = unpopulate(val, "PercentComplete", &o.PercentComplete) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &o.Properties) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &o.StartTime) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &o.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/sdk/resourcemanager/terraform/armterraform/operations_client.go b/sdk/resourcemanager/terraform/armterraform/operations_client.go new file mode 100644 index 000000000000..83af3e57206f --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/operations_client.go @@ -0,0 +1,84 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armterraform + +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 - List the operations for the provider +// +// Generated from API version 2023-07-01-preview +// - 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 page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.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 OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.AzureTerraform/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-preview") + 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 +} diff --git a/sdk/resourcemanager/terraform/armterraform/operations_client_example_test.go b/sdk/resourcemanager/terraform/armterraform/operations_client_example_test.go new file mode 100644 index 000000000000..7828d87b1ccb --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/operations_client_example_test.go @@ -0,0 +1,61 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armterraform_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/terraform/armterraform" + "log" +) + +// Generated from example definition: 2023-07-01-preview/ListOperations.json +func ExampleOperationsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armterraform.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armterraform.OperationsClientListResponse{ + // OperationListResult: armterraform.OperationListResult{ + // Value: []*armterraform.Operation{ + // { + // Name: to.Ptr("Microsoft.AzureTerraform/operations/read"), + // Display: &armterraform.OperationDisplay{ + // Provider: to.Ptr("Microsoft AzureTerraform"), + // Resource: to.Ptr("Azure Terraform Resource Provider"), + // Operation: to.Ptr("ListOperations"), + // Description: to.Ptr("Lists all of the available RP operations."), + // }, + // }, + // { + // Name: to.Ptr("Microsoft.AzureTerraform/exportTerraform/action"), + // Display: &armterraform.OperationDisplay{ + // Provider: to.Ptr("Microsoft AzureTerraform"), + // Resource: to.Ptr("Azure Terraform Resource Provider"), + // Operation: to.Ptr("ExportTerraform"), + // Description: to.Ptr("Exports the Terraform configuration used for the specified scope."), + // }, + // }, + // }, + // }, + // } + } +} diff --git a/sdk/resourcemanager/terraform/armterraform/options.go b/sdk/resourcemanager/terraform/armterraform/options.go new file mode 100644 index 000000000000..0bf1f8242069 --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/options.go @@ -0,0 +1,17 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armterraform + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// TerraformClientBeginExportTerraformOptions contains the optional parameters for the TerraformClient.BeginExportTerraform +// method. +type TerraformClientBeginExportTerraformOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} diff --git a/sdk/resourcemanager/terraform/armterraform/responses.go b/sdk/resourcemanager/terraform/armterraform/responses.go new file mode 100644 index 000000000000..0876321d993b --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/responses.go @@ -0,0 +1,17 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armterraform + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// TerraformClientExportTerraformResponse contains the response from method TerraformClient.BeginExportTerraform. +type TerraformClientExportTerraformResponse struct { + // The status of the LRO operation. + OperationStatus +} diff --git a/sdk/resourcemanager/terraform/armterraform/terraform_client.go b/sdk/resourcemanager/terraform/armterraform/terraform_client.go new file mode 100644 index 000000000000..7c0eb89352ad --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/terraform_client.go @@ -0,0 +1,112 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armterraform + +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" +) + +// TerraformClient contains the methods for the Terraform group. +// Don't use this type directly, use NewTerraformClient() instead. +type TerraformClient struct { + internal *arm.Client + subscriptionID string +} + +// NewTerraformClient creates a new instance of TerraformClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewTerraformClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TerraformClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &TerraformClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginExportTerraform - Exports the Terraform configuration of the specified resource(s). +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01-preview +// - body - The request body +// - options - TerraformClientBeginExportTerraformOptions contains the optional parameters for the TerraformClient.BeginExportTerraform +// method. +func (client *TerraformClient) BeginExportTerraform(ctx context.Context, body BaseExportModelClassification, options *TerraformClientBeginExportTerraformOptions) (*runtime.Poller[TerraformClientExportTerraformResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.exportTerraform(ctx, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TerraformClientExportTerraformResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TerraformClientExportTerraformResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ExportTerraform - Exports the Terraform configuration of the specified resource(s). +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01-preview +func (client *TerraformClient) exportTerraform(ctx context.Context, body BaseExportModelClassification, options *TerraformClientBeginExportTerraformOptions) (*http.Response, error) { + var err error + const operationName = "TerraformClient.BeginExportTerraform" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.exportTerraformCreateRequest(ctx, body, 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.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// exportTerraformCreateRequest creates the ExportTerraform request. +func (client *TerraformClient) exportTerraformCreateRequest(ctx context.Context, body BaseExportModelClassification, _ *TerraformClientBeginExportTerraformOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AzureTerraform/exportTerraform" + 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-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/sdk/resourcemanager/terraform/armterraform/terraform_client_example_test.go b/sdk/resourcemanager/terraform/armterraform/terraform_client_example_test.go new file mode 100644 index 000000000000..a6fb7ee92d0d --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/terraform_client_example_test.go @@ -0,0 +1,37 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armterraform_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/terraform/armterraform" + "log" +) + +// Generated from example definition: 2023-07-01-preview/ExportTerraform.json +func ExampleTerraformClient_BeginExportTerraform() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armterraform.NewClientFactory("00000000-0000-0000-0000-000000000000", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewTerraformClient().BeginExportTerraform(ctx, armterraform.ExportResourceGroup{ + Type: to.Ptr(armterraform.TypeExportResourceGroup), + ResourceGroupName: to.Ptr("rg1"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} diff --git a/sdk/resourcemanager/terraform/armterraform/time_rfc3339.go b/sdk/resourcemanager/terraform/armterraform/time_rfc3339.go new file mode 100644 index 000000000000..9d6f72ee468a --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/time_rfc3339.go @@ -0,0 +1,109 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armterraform + +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 ( + utcDateTime = "2006-01-02T15:04:05.999999999" + utcDateTimeJSON = `"` + utcDateTime + `"` + utcDateTimeNoT = "2006-01-02 15:04:05.999999999" + utcDateTimeJSONNoT = `"` + utcDateTimeNoT + `"` + dateTimeNoT = `2006-01-02 15:04:05.999999999Z07:00` + dateTimeJSON = `"` + time.RFC3339Nano + `"` + dateTimeJSONNoT = `"` + dateTimeNoT + `"` +) + +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 { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { + layout = dateTimeJSON + } else if tzOffset { + layout = dateTimeJSONNoT + } else if hasT { + layout = utcDateTimeJSON + } else { + layout = utcDateTimeJSONNoT + } + return t.Parse(layout, string(data)) +} + +func (t *dateTimeRFC3339) UnmarshalText(data []byte) error { + if len(data) == 0 { + return nil + } + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { + layout = time.RFC3339Nano + } else if tzOffset { + layout = dateTimeNoT + } else if hasT { + layout = utcDateTime + } else { + layout = utcDateTimeNoT + } + 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 (t dateTimeRFC3339) String() string { + return time.Time(t).Format(time.RFC3339Nano) +} + +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 || 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 +} diff --git a/sdk/resourcemanager/terraform/armterraform/tsp-location.yaml b/sdk/resourcemanager/terraform/armterraform/tsp-location.yaml new file mode 100644 index 000000000000..f118d290d05c --- /dev/null +++ b/sdk/resourcemanager/terraform/armterraform/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/terraform/Microsoft.AzureTerraform.Management +commit: 1ce733f099d6e72ca94fda25704bc1484c697858 +repo: Azure/azure-rest-api-specs +additionalDirectories: \ No newline at end of file