diff --git a/sdk/resourcemanager/ci.mgmt.yml b/sdk/resourcemanager/ci.mgmt.yml index 69d2e50d37487..e844fdb04cde1 100644 --- a/sdk/resourcemanager/ci.mgmt.yml +++ b/sdk/resourcemanager/ci.mgmt.yml @@ -194,6 +194,7 @@ trigger: - sdk/subscription/Azure.ResourceManager.Subscription - sdk/support/Azure.ResourceManager.Support - sdk/synapse/Azure.ResourceManager.Synapse + - sdk/terraform/Azure.ResourceManager.Terraform - sdk/trafficmanager/Azure.ResourceManager.TrafficManager - sdk/trustedsigning/Azure.ResourceManager.TrustedSigning - sdk/voiceservices/Azure.ResourceManager.VoiceServices @@ -397,6 +398,7 @@ pr: - sdk/subscription/Azure.ResourceManager.Subscription - sdk/support/Azure.ResourceManager.Support - sdk/synapse/Azure.ResourceManager.Synapse + - sdk/terraform/Azure.ResourceManager.Terraform - sdk/trafficmanager/Azure.ResourceManager.TrafficManager - sdk/trustedsigning/Azure.ResourceManager.TrustedSigning - sdk/voiceservices/Azure.ResourceManager.VoiceServices diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/Azure.ResourceManager.Terraform.sln b/sdk/terraform/Azure.ResourceManager.Terraform/Azure.ResourceManager.Terraform.sln new file mode 100644 index 0000000000000..0fdcc0b1d313f --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/Azure.ResourceManager.Terraform.sln @@ -0,0 +1,65 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30309.148 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{57104F4E-33D2-4712-89D0-35A4165C1BA1}") = "Azure.ResourceManager.Terraform", "src\Azure.ResourceManager.Terraform.csproj", "{3457A0A4-B5E1-4184-8D42-0F1C542217C9}" +EndProject +Project("{57104F4E-33D2-4712-89D0-35A4165C1BA1}") = "Azure.ResourceManager.Terraform.Tests", "tests\Azure.ResourceManager.Terraform.Tests.csproj", "{DC07DC97-58C7-4345-B915-29DF7739ABD5}" +EndProject +Project("{57104F4E-33D2-4712-89D0-35A4165C1BA1}") = "Azure.ResourceManager.Terraform.Samples", "samples\Azure.ResourceManager.Terraform.Samples.csproj", "{0C87CC4B-8863-41FC-8704-20CC6F8A58E1}" +EndProject +Global + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {79ECAB3D-FE5F-4AF2-9214-2D6F13CB7F9C} + EndGlobalSection + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3457A0A4-B5E1-4184-8D42-0F1C542217C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3457A0A4-B5E1-4184-8D42-0F1C542217C9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3457A0A4-B5E1-4184-8D42-0F1C542217C9}.Debug|x64.ActiveCfg = Debug|Any CPU + {3457A0A4-B5E1-4184-8D42-0F1C542217C9}.Debug|x64.Build.0 = Debug|Any CPU + {3457A0A4-B5E1-4184-8D42-0F1C542217C9}.Debug|x86.ActiveCfg = Debug|Any CPU + {3457A0A4-B5E1-4184-8D42-0F1C542217C9}.Debug|x86.Build.0 = Debug|Any CPU + {3457A0A4-B5E1-4184-8D42-0F1C542217C9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3457A0A4-B5E1-4184-8D42-0F1C542217C9}.Release|Any CPU.Build.0 = Release|Any CPU + {3457A0A4-B5E1-4184-8D42-0F1C542217C9}.Release|x64.ActiveCfg = Release|Any CPU + {3457A0A4-B5E1-4184-8D42-0F1C542217C9}.Release|x64.Build.0 = Release|Any CPU + {3457A0A4-B5E1-4184-8D42-0F1C542217C9}.Release|x86.ActiveCfg = Release|Any CPU + {3457A0A4-B5E1-4184-8D42-0F1C542217C9}.Release|x86.Build.0 = Release|Any CPU + {DC07DC97-58C7-4345-B915-29DF7739ABD5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DC07DC97-58C7-4345-B915-29DF7739ABD5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DC07DC97-58C7-4345-B915-29DF7739ABD5}.Debug|x64.ActiveCfg = Debug|Any CPU + {DC07DC97-58C7-4345-B915-29DF7739ABD5}.Debug|x64.Build.0 = Debug|Any CPU + {DC07DC97-58C7-4345-B915-29DF7739ABD5}.Debug|x86.ActiveCfg = Debug|Any CPU + {DC07DC97-58C7-4345-B915-29DF7739ABD5}.Debug|x86.Build.0 = Debug|Any CPU + {DC07DC97-58C7-4345-B915-29DF7739ABD5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DC07DC97-58C7-4345-B915-29DF7739ABD5}.Release|Any CPU.Build.0 = Release|Any CPU + {DC07DC97-58C7-4345-B915-29DF7739ABD5}.Release|x64.ActiveCfg = Release|Any CPU + {DC07DC97-58C7-4345-B915-29DF7739ABD5}.Release|x64.Build.0 = Release|Any CPU + {DC07DC97-58C7-4345-B915-29DF7739ABD5}.Release|x86.ActiveCfg = Release|Any CPU + {DC07DC97-58C7-4345-B915-29DF7739ABD5}.Release|x86.Build.0 = Release|Any CPU + {0C87CC4B-8863-41FC-8704-20CC6F8A58E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0C87CC4B-8863-41FC-8704-20CC6F8A58E1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0C87CC4B-8863-41FC-8704-20CC6F8A58E1}.Debug|x64.ActiveCfg = Debug|Any CPU + {0C87CC4B-8863-41FC-8704-20CC6F8A58E1}.Debug|x64.Build.0 = Debug|Any CPU + {0C87CC4B-8863-41FC-8704-20CC6F8A58E1}.Debug|x86.ActiveCfg = Debug|Any CPU + {0C87CC4B-8863-41FC-8704-20CC6F8A58E1}.Debug|x86.Build.0 = Debug|Any CPU + {0C87CC4B-8863-41FC-8704-20CC6F8A58E1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0C87CC4B-8863-41FC-8704-20CC6F8A58E1}.Release|Any CPU.Build.0 = Release|Any CPU + {0C87CC4B-8863-41FC-8704-20CC6F8A58E1}.Release|x64.ActiveCfg = Release|Any CPU + {0C87CC4B-8863-41FC-8704-20CC6F8A58E1}.Release|x64.Build.0 = Release|Any CPU + {0C87CC4B-8863-41FC-8704-20CC6F8A58E1}.Release|x86.ActiveCfg = Release|Any CPU + {0C87CC4B-8863-41FC-8704-20CC6F8A58E1}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/CHANGELOG.md b/sdk/terraform/Azure.ResourceManager.Terraform/CHANGELOG.md new file mode 100644 index 0000000000000..da00c15054249 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/CHANGELOG.md @@ -0,0 +1,17 @@ +# Release History + +## 1.0.0-beta.1 (2024-10-31) + +### Features Added + +This package follows the [new Azure SDK guidelines](https://azure.github.io/azure-sdk/general_introduction.html), and provides many core capabilities: + + - Support MSAL.NET, Azure.Identity is out of box for supporting MSAL.NET. + - Support [OpenTelemetry](https://opentelemetry.io/) for distributed tracing. + - HTTP pipeline with custom policies. + - Better error-handling. + - Support uniform telemetry across all languages. + +This package is a Public Preview version, so expect incompatible changes in subsequent releases as we improve the product. To provide feedback, submit an issue in our [Azure SDK for .NET GitHub repo](https://github.com/Azure/azure-sdk-for-net/issues). + +> NOTE: For more information about unified authentication, please refer to [Microsoft Azure Identity documentation for .NET](https://docs.microsoft.com//dotnet/api/overview/azure/identity-readme?view=azure-dotnet). diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/Directory.Build.props b/sdk/terraform/Azure.ResourceManager.Terraform/Directory.Build.props new file mode 100644 index 0000000000000..1a9611bd49242 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/Directory.Build.props @@ -0,0 +1,6 @@ + + + + diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/README.md b/sdk/terraform/Azure.ResourceManager.Terraform/README.md new file mode 100644 index 0000000000000..7eae62f4da191 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/README.md @@ -0,0 +1,82 @@ +# Microsoft Azure terraform management client library for .NET + +The Azure Terraform Export API aims to export existing Azure resources into its equivalent Terraform configurations, +for either azurerm provider or azapi provider. It is equivalent to ARM Template Export API for Terraform. + +This library follows the [new Azure SDK guidelines](https://azure.github.io/azure-sdk/general_introduction.html), and provides many core capabilities: + +- Support MSAL.NET, Azure.Identity is out of box for supporting MSAL.NET. +- Support [OpenTelemetry](https://opentelemetry.io/) for distributed tracing. +- HTTP pipeline with custom policies. +- Better error-handling. +- Support uniform telemetry across all languages. + +## Getting started + +### Install the package + +Install the Microsoft Azure terraform management library for .NET with [NuGet](https://www.nuget.org/): + +```dotnetcli +dotnet add package Azure.ResourceManager.Terraform --prerelease +``` + +### Prerequisites + +- You must have an [Microsoft Azure subscription](https://azure.microsoft.com/free/dotnet/). + +### Authenticate the Client + +To create an authenticated client and start interacting with Microsoft Azure resources, see the [quickstart guide here](https://github.com/Azure/azure-sdk-for-net/blob/main/doc/dev/mgmt_quickstart.md). + +## Key concepts + +Key concepts of the Microsoft Azure SDK for .NET can be found [here](https://azure.github.io/azure-sdk/dotnet_introduction.html) + +## Documentation + +Documentation is available to help you learn how to use this package: + +- [Quickstart](https://github.com/Azure/azure-sdk-for-net/blob/main/doc/dev/mgmt_quickstart.md). +- [API References](https://docs.microsoft.com/dotnet/api/?view=azure-dotnet). +- [Authentication](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/README.md). + +## Examples + +Code samples for using the management library for .NET can be found in the following locations + +- [.NET Management Library Code Samples](https://aka.ms/azuresdk-net-mgmt-samples) + +## Troubleshooting + +- File an issue via [GitHub Issues](https://github.com/Azure/azure-sdk-for-net/issues). +- Check [previous questions](https://stackoverflow.com/questions/tagged/azure+.net) or ask new ones on Stack Overflow using Azure and .NET tags. + +## Next steps + +For more information about Microsoft Azure SDK, see [this website](https://azure.github.io/azure-sdk/). + +## Contributing + +For details on contributing to this repository, see the [contributing +guide][cg]. + +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 . + +When you submit a pull request, a CLA-bot will automatically determine +whether you need to provide a CLA and decorate the PR appropriately +(for example, label, comment). Follow the instructions provided by the +bot. You'll only need to do this action once across all repositories +using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For +more information, see the [Code of Conduct FAQ][coc_faq] or contact + with any other questions or comments. + + +[cg]: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/resourcemanager/Azure.ResourceManager/docs/CONTRIBUTING.md +[coc]: https://opensource.microsoft.com/codeofconduct/ +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/api/Azure.ResourceManager.Terraform.netstandard2.0.cs b/sdk/terraform/Azure.ResourceManager.Terraform/api/Azure.ResourceManager.Terraform.netstandard2.0.cs new file mode 100644 index 0000000000000..6ba77b806a8b8 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/api/Azure.ResourceManager.Terraform.netstandard2.0.cs @@ -0,0 +1,146 @@ +namespace Azure.ResourceManager.Terraform +{ + public static partial class TerraformExtensions + { + public static Azure.ResourceManager.ArmOperation ExportTerraform(this Azure.ResourceManager.Resources.SubscriptionResource subscriptionResource, Azure.WaitUntil waitUntil, Azure.ResourceManager.Terraform.Models.CommonExportProperties body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public static System.Threading.Tasks.Task> ExportTerraformAsync(this Azure.ResourceManager.Resources.SubscriptionResource subscriptionResource, Azure.WaitUntil waitUntil, Azure.ResourceManager.Terraform.Models.CommonExportProperties body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + } +} +namespace Azure.ResourceManager.Terraform.Mocking +{ + public partial class MockableTerraformSubscriptionResource : Azure.ResourceManager.ArmResource + { + protected MockableTerraformSubscriptionResource() { } + public virtual Azure.ResourceManager.ArmOperation ExportTerraform(Azure.WaitUntil waitUntil, Azure.ResourceManager.Terraform.Models.CommonExportProperties body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> ExportTerraformAsync(Azure.WaitUntil waitUntil, Azure.ResourceManager.Terraform.Models.CommonExportProperties body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + } +} +namespace Azure.ResourceManager.Terraform.Models +{ + public static partial class ArmTerraformModelFactory + { + public static Azure.ResourceManager.Terraform.Models.ExportQueryTerraform ExportQueryTerraform(Azure.ResourceManager.Terraform.Models.TargetTerraformProvider? targetProvider = default(Azure.ResourceManager.Terraform.Models.TargetTerraformProvider?), bool? isOutputFullPropertiesEnabled = default(bool?), bool? isMaskSensitiveEnabled = default(bool?), string query = null, string namePattern = null, bool? isRecursive = default(bool?)) { throw null; } + public static Azure.ResourceManager.Terraform.Models.ExportResourceGroupTerraform ExportResourceGroupTerraform(Azure.ResourceManager.Terraform.Models.TargetTerraformProvider? targetProvider = default(Azure.ResourceManager.Terraform.Models.TargetTerraformProvider?), bool? isOutputFullPropertiesEnabled = default(bool?), bool? isMaskSensitiveEnabled = default(bool?), string resourceGroupName = null, string namePattern = null) { throw null; } + public static Azure.ResourceManager.Terraform.Models.TerraformExportResult TerraformExportResult(string configuration = null, System.Collections.Generic.IEnumerable skippedResourceIds = null, System.Collections.Generic.IEnumerable errors = null) { throw null; } + public static Azure.ResourceManager.Terraform.Models.TerraformOperationStatus TerraformOperationStatus(Azure.ResourceManager.Terraform.Models.TerraformExportResult properties = null, Azure.ResourceManager.Terraform.Models.TerraformResourceProvisioningState status = default(Azure.ResourceManager.Terraform.Models.TerraformResourceProvisioningState), string name = null, System.DateTimeOffset? startOn = default(System.DateTimeOffset?), System.DateTimeOffset? endOn = default(System.DateTimeOffset?), double? percentComplete = default(double?), Azure.ResponseError error = null) { throw null; } + } + public abstract partial class CommonExportProperties : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + protected CommonExportProperties() { } + public bool? IsMaskSensitiveEnabled { get { throw null; } set { } } + public bool? IsOutputFullPropertiesEnabled { get { throw null; } set { } } + public Azure.ResourceManager.Terraform.Models.TargetTerraformProvider? TargetProvider { get { throw null; } set { } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Terraform.Models.CommonExportProperties System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Terraform.Models.CommonExportProperties System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class ExportQueryTerraform : Azure.ResourceManager.Terraform.Models.CommonExportProperties, System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public ExportQueryTerraform(string query) { } + public bool? IsRecursive { get { throw null; } set { } } + public string NamePattern { get { throw null; } set { } } + public string Query { get { throw null; } } + protected override void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Terraform.Models.ExportQueryTerraform System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Terraform.Models.ExportQueryTerraform System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class ExportResourceGroupTerraform : Azure.ResourceManager.Terraform.Models.CommonExportProperties, System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public ExportResourceGroupTerraform(string resourceGroupName) { } + public string NamePattern { get { throw null; } set { } } + public string ResourceGroupName { get { throw null; } } + protected override void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Terraform.Models.ExportResourceGroupTerraform System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Terraform.Models.ExportResourceGroupTerraform System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class ExportResourceTerraform : Azure.ResourceManager.Terraform.Models.CommonExportProperties, System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public ExportResourceTerraform(System.Collections.Generic.IEnumerable resourceIds) { } + public string NamePattern { get { throw null; } set { } } + public System.Collections.Generic.IList ResourceIds { get { throw null; } } + public string ResourceName { get { throw null; } set { } } + public string ResourceType { get { throw null; } set { } } + protected override void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Terraform.Models.ExportResourceTerraform System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Terraform.Models.ExportResourceTerraform System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct TargetTerraformProvider : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public TargetTerraformProvider(string value) { throw null; } + public static Azure.ResourceManager.Terraform.Models.TargetTerraformProvider AzApi { get { throw null; } } + public static Azure.ResourceManager.Terraform.Models.TargetTerraformProvider AzureRM { get { throw null; } } + public bool Equals(Azure.ResourceManager.Terraform.Models.TargetTerraformProvider other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.ResourceManager.Terraform.Models.TargetTerraformProvider left, Azure.ResourceManager.Terraform.Models.TargetTerraformProvider right) { throw null; } + public static implicit operator Azure.ResourceManager.Terraform.Models.TargetTerraformProvider (string value) { throw null; } + public static bool operator !=(Azure.ResourceManager.Terraform.Models.TargetTerraformProvider left, Azure.ResourceManager.Terraform.Models.TargetTerraformProvider right) { throw null; } + public override string ToString() { throw null; } + } + public partial class TerraformExportResult : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal TerraformExportResult() { } + public string Configuration { get { throw null; } } + public System.Collections.Generic.IReadOnlyList Errors { get { throw null; } } + public System.Collections.Generic.IReadOnlyList SkippedResourceIds { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Terraform.Models.TerraformExportResult System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Terraform.Models.TerraformExportResult System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class TerraformOperationStatus : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal TerraformOperationStatus() { } + public System.DateTimeOffset? EndOn { get { throw null; } } + public Azure.ResponseError Error { get { throw null; } } + public string Name { get { throw null; } } + public double? PercentComplete { get { throw null; } } + public Azure.ResourceManager.Terraform.Models.TerraformExportResult Properties { get { throw null; } } + public System.DateTimeOffset? StartOn { get { throw null; } } + public Azure.ResourceManager.Terraform.Models.TerraformResourceProvisioningState Status { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Terraform.Models.TerraformOperationStatus System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Terraform.Models.TerraformOperationStatus System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct TerraformResourceProvisioningState : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public TerraformResourceProvisioningState(string value) { throw null; } + public static Azure.ResourceManager.Terraform.Models.TerraformResourceProvisioningState Canceled { get { throw null; } } + public static Azure.ResourceManager.Terraform.Models.TerraformResourceProvisioningState Failed { get { throw null; } } + public static Azure.ResourceManager.Terraform.Models.TerraformResourceProvisioningState Succeeded { get { throw null; } } + public bool Equals(Azure.ResourceManager.Terraform.Models.TerraformResourceProvisioningState other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.ResourceManager.Terraform.Models.TerraformResourceProvisioningState left, Azure.ResourceManager.Terraform.Models.TerraformResourceProvisioningState right) { throw null; } + public static implicit operator Azure.ResourceManager.Terraform.Models.TerraformResourceProvisioningState (string value) { throw null; } + public static bool operator !=(Azure.ResourceManager.Terraform.Models.TerraformResourceProvisioningState left, Azure.ResourceManager.Terraform.Models.TerraformResourceProvisioningState right) { throw null; } + public override string ToString() { throw null; } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/assets.json b/sdk/terraform/Azure.ResourceManager.Terraform/assets.json new file mode 100644 index 0000000000000..255b73238d74e --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/assets.json @@ -0,0 +1,6 @@ +{ + "AssetsRepo": "Azure/azure-sdk-assets", + "AssetsRepoPrefixPath": "net", + "TagPrefix": "net/terraform/Azure.ResourceManager.Terraform", + "Tag": "net/terraform/Azure.ResourceManager.Terraform_ac6492ee96" +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/samples/Azure.ResourceManager.Terraform.Samples.csproj b/sdk/terraform/Azure.ResourceManager.Terraform/samples/Azure.ResourceManager.Terraform.Samples.csproj new file mode 100644 index 0000000000000..8d2d95777931e --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/samples/Azure.ResourceManager.Terraform.Samples.csproj @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/samples/Generated/Samples/Sample_SubscriptionResourceExtensions.cs b/sdk/terraform/Azure.ResourceManager.Terraform/samples/Generated/Samples/Sample_SubscriptionResourceExtensions.cs new file mode 100644 index 0000000000000..ac302321fa08c --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/samples/Generated/Samples/Sample_SubscriptionResourceExtensions.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using Azure.ResourceManager.Resources; +using Azure.ResourceManager.Terraform.Models; + +namespace Azure.ResourceManager.Terraform.Samples +{ + public partial class Sample_SubscriptionResourceExtensions + { + // ExportTerraform + [NUnit.Framework.Test] + [NUnit.Framework.Ignore("Only verifying that the sample builds")] + public async Task ExportTerraform_ExportTerraform() + { + // Generated from example definition: 2023-07-01-preview/ExportTerraform.json + // this example is just showing the usage of "Terraform_ExportTerraform" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this SubscriptionResource created on azure + // for more information of creating SubscriptionResource, please refer to the document of SubscriptionResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId); + SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); + + // invoke the operation + CommonExportProperties body = new ExportResourceGroupTerraform("rg1"); + ArmOperation lro = await subscriptionResource.ExportTerraformAsync(WaitUntil.Completed, body); + TerraformOperationStatus result = lro.Value; + + Console.WriteLine($"Succeeded: {result}"); + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Azure.ResourceManager.Terraform.csproj b/sdk/terraform/Azure.ResourceManager.Terraform/src/Azure.ResourceManager.Terraform.csproj new file mode 100644 index 0000000000000..f2dd197dd4a3f --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Azure.ResourceManager.Terraform.csproj @@ -0,0 +1,8 @@ + + + 1.0.0-beta.1 + Azure.ResourceManager.Terraform + Azure Resource Manager client SDK for Azure resource provider terraform. + azure;management;arm;resource manager;terraform + + diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/ArmTerraformModelFactory.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/ArmTerraformModelFactory.cs new file mode 100644 index 0000000000000..72b56c7b2a602 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/ArmTerraformModelFactory.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; +using Azure.Core; + +namespace Azure.ResourceManager.Terraform.Models +{ + /// Model factory for models. + public static partial class ArmTerraformModelFactory + { + /// Initializes a new instance of . + /// The target Azure Terraform Provider. + /// Whether to output all non-computed properties in the generated Terraform configuration? This probably needs manual modifications to make it valid. + /// Mask sensitive attributes in the Terraform configuration. + /// 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"`. + /// The name pattern of the Terraform resources. + /// Whether to recursively list child resources of the query result. + /// A new instance for mocking. + public static ExportQueryTerraform ExportQueryTerraform(TargetTerraformProvider? targetProvider = null, bool? isOutputFullPropertiesEnabled = null, bool? isMaskSensitiveEnabled = null, string query = null, string namePattern = null, bool? isRecursive = null) + { + return new ExportQueryTerraform( + CommonExportType.ExportQuery, + targetProvider, + isOutputFullPropertiesEnabled, + isMaskSensitiveEnabled, + serializedAdditionalRawData: null, + query, + namePattern, + isRecursive); + } + + /// Initializes a new instance of . + /// The target Azure Terraform Provider. + /// Whether to output all non-computed properties in the generated Terraform configuration? This probably needs manual modifications to make it valid. + /// Mask sensitive attributes in the Terraform configuration. + /// The name of the resource group to be exported. + /// The name pattern of the Terraform resources. + /// A new instance for mocking. + public static ExportResourceGroupTerraform ExportResourceGroupTerraform(TargetTerraformProvider? targetProvider = null, bool? isOutputFullPropertiesEnabled = null, bool? isMaskSensitiveEnabled = null, string resourceGroupName = null, string namePattern = null) + { + return new ExportResourceGroupTerraform( + CommonExportType.ExportResourceGroup, + targetProvider, + isOutputFullPropertiesEnabled, + isMaskSensitiveEnabled, + serializedAdditionalRawData: null, + resourceGroupName, + namePattern); + } + + /// Initializes a new instance of . + /// RP-specific properties for the operationStatus resource, only appears when operation ended with Succeeded status. + /// The operation status. + /// The name of the operationStatus resource. + /// Operation start time. + /// Operation complete time. + /// The progress made toward completing the operation. + /// Errors that occurred if the operation ended with Canceled or Failed status. + /// A new instance for mocking. + public static TerraformOperationStatus TerraformOperationStatus(TerraformExportResult properties = null, TerraformResourceProvisioningState status = default, string name = null, DateTimeOffset? startOn = null, DateTimeOffset? endOn = null, double? percentComplete = null, ResponseError error = null) + { + return new TerraformOperationStatus( + properties, + status, + name, + startOn, + endOn, + percentComplete, + error, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The Terraform configuration content. + /// A list of Azure resources which are not exported to Terraform due to there is no corresponding resources in Terraform. + /// A list of errors derived during exporting each resource. + /// A new instance for mocking. + public static TerraformExportResult TerraformExportResult(string configuration = null, IEnumerable skippedResourceIds = null, IEnumerable errors = null) + { + skippedResourceIds ??= new List(); + errors ??= new List(); + + return new TerraformExportResult(configuration, skippedResourceIds?.ToList(), errors?.ToList(), serializedAdditionalRawData: null); + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Extensions/MockableTerraformSubscriptionResource.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Extensions/MockableTerraformSubscriptionResource.cs new file mode 100644 index 0000000000000..a49365c8727db --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Extensions/MockableTerraformSubscriptionResource.cs @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; +using Azure.ResourceManager.Terraform.Models; + +namespace Azure.ResourceManager.Terraform.Mocking +{ + /// A class to add extension methods to SubscriptionResource. + public partial class MockableTerraformSubscriptionResource : ArmResource + { + private ClientDiagnostics _terraformClientDiagnostics; + private TerraformRestOperations _terraformRestClient; + + /// Initializes a new instance of the class for mocking. + protected MockableTerraformSubscriptionResource() + { + } + + /// Initializes a new instance of the class. + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + internal MockableTerraformSubscriptionResource(ArmClient client, ResourceIdentifier id) : base(client, id) + { + } + + private ClientDiagnostics TerraformClientDiagnostics => _terraformClientDiagnostics ??= new ClientDiagnostics("Azure.ResourceManager.Terraform", ProviderConstants.DefaultProviderNamespace, Diagnostics); + private TerraformRestOperations TerraformRestClient => _terraformRestClient ??= new TerraformRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint); + + private string GetApiVersionOrNull(ResourceType resourceType) + { + TryGetApiVersion(resourceType, out string apiVersion); + return apiVersion; + } + + /// + /// Exports the Terraform configuration of the specified resource(s). + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/providers/Microsoft.AzureTerraform/exportTerraform + /// + /// + /// Operation Id + /// Terraform_ExportTerraform + /// + /// + /// Default Api Version + /// 2023-07-01-preview + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The request body. + /// The cancellation token to use. + /// is null. + public virtual async Task> ExportTerraformAsync(WaitUntil waitUntil, CommonExportProperties body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(body, nameof(body)); + + using var scope = TerraformClientDiagnostics.CreateScope("MockableTerraformSubscriptionResource.ExportTerraform"); + scope.Start(); + try + { + var response = await TerraformRestClient.ExportTerraformAsync(Id.SubscriptionId, body, cancellationToken).ConfigureAwait(false); + var operation = new TerraformArmOperation(new TerraformOperationStatusOperationSource(), TerraformClientDiagnostics, Pipeline, TerraformRestClient.CreateExportTerraformRequest(Id.SubscriptionId, body).Request, response, OperationFinalStateVia.AzureAsyncOperation); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Exports the Terraform configuration of the specified resource(s). + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/providers/Microsoft.AzureTerraform/exportTerraform + /// + /// + /// Operation Id + /// Terraform_ExportTerraform + /// + /// + /// Default Api Version + /// 2023-07-01-preview + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The request body. + /// The cancellation token to use. + /// is null. + public virtual ArmOperation ExportTerraform(WaitUntil waitUntil, CommonExportProperties body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(body, nameof(body)); + + using var scope = TerraformClientDiagnostics.CreateScope("MockableTerraformSubscriptionResource.ExportTerraform"); + scope.Start(); + try + { + var response = TerraformRestClient.ExportTerraform(Id.SubscriptionId, body, cancellationToken); + var operation = new TerraformArmOperation(new TerraformOperationStatusOperationSource(), TerraformClientDiagnostics, Pipeline, TerraformRestClient.CreateExportTerraformRequest(Id.SubscriptionId, body).Request, response, OperationFinalStateVia.AzureAsyncOperation); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Extensions/TerraformExtensions.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Extensions/TerraformExtensions.cs new file mode 100644 index 0000000000000..07abb8eda0f3b --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Extensions/TerraformExtensions.cs @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure.ResourceManager.Resources; +using Azure.ResourceManager.Terraform.Mocking; +using Azure.ResourceManager.Terraform.Models; + +namespace Azure.ResourceManager.Terraform +{ + /// A class to add extension methods to Azure.ResourceManager.Terraform. + public static partial class TerraformExtensions + { + private static MockableTerraformSubscriptionResource GetMockableTerraformSubscriptionResource(ArmResource resource) + { + return resource.GetCachedClient(client => new MockableTerraformSubscriptionResource(client, resource.Id)); + } + + /// + /// Exports the Terraform configuration of the specified resource(s). + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/providers/Microsoft.AzureTerraform/exportTerraform + /// + /// + /// Operation Id + /// Terraform_ExportTerraform + /// + /// + /// Default Api Version + /// 2023-07-01-preview + /// + /// + /// + /// Mocking + /// To mock this method, please mock instead. + /// + /// + /// The instance the method will execute against. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The request body. + /// The cancellation token to use. + /// or is null. + public static async Task> ExportTerraformAsync(this SubscriptionResource subscriptionResource, WaitUntil waitUntil, CommonExportProperties body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(subscriptionResource, nameof(subscriptionResource)); + + return await GetMockableTerraformSubscriptionResource(subscriptionResource).ExportTerraformAsync(waitUntil, body, cancellationToken).ConfigureAwait(false); + } + + /// + /// Exports the Terraform configuration of the specified resource(s). + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/providers/Microsoft.AzureTerraform/exportTerraform + /// + /// + /// Operation Id + /// Terraform_ExportTerraform + /// + /// + /// Default Api Version + /// 2023-07-01-preview + /// + /// + /// + /// Mocking + /// To mock this method, please mock instead. + /// + /// + /// The instance the method will execute against. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The request body. + /// The cancellation token to use. + /// or is null. + public static ArmOperation ExportTerraform(this SubscriptionResource subscriptionResource, WaitUntil waitUntil, CommonExportProperties body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(subscriptionResource, nameof(subscriptionResource)); + + return GetMockableTerraformSubscriptionResource(subscriptionResource).ExportTerraform(waitUntil, body, cancellationToken); + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/Argument.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/Argument.cs new file mode 100644 index 0000000000000..2cbf70c62fe1e --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/Argument.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Terraform +{ + internal static class Argument + { + public static void AssertNotNull(T value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNull(T? value, string name) + where T : struct + { + if (!value.HasValue) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNullOrEmpty(IEnumerable value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value is ICollection collectionOfT && collectionOfT.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + if (value is ICollection collection && collection.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + using IEnumerator e = value.GetEnumerator(); + if (!e.MoveNext()) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + } + + public static void AssertNotNullOrEmpty(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value.Length == 0) + { + throw new ArgumentException("Value cannot be an empty string.", name); + } + } + + public static void AssertNotNullOrWhiteSpace(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Value cannot be empty or contain only white-space characters.", name); + } + } + + public static void AssertNotDefault(ref T value, string name) + where T : struct, IEquatable + { + if (value.Equals(default)) + { + throw new ArgumentException("Value cannot be empty.", name); + } + } + + public static void AssertInRange(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (minimum.CompareTo(value) > 0) + { + throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed."); + } + if (maximum.CompareTo(value) < 0) + { + throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed."); + } + } + + public static void AssertEnumDefined(Type enumType, object value, string name) + { + if (!Enum.IsDefined(enumType, value)) + { + throw new ArgumentException($"Value not defined for {enumType.FullName}.", name); + } + } + + public static T CheckNotNull(T value, string name) + where T : class + { + AssertNotNull(value, name); + return value; + } + + public static string CheckNotNullOrEmpty(string value, string name) + { + AssertNotNullOrEmpty(value, name); + return value; + } + + public static void AssertNull(T value, string name, string message = null) + { + if (value != null) + { + throw new ArgumentException(message ?? "Value must be null.", name); + } + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 0000000000000..975398aa4c203 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Terraform +{ + internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull + { + private IDictionary _innerDictionary; + + public ChangeTrackingDictionary() + { + } + + public ChangeTrackingDictionary(IDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(dictionary); + } + + public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(); + foreach (var pair in dictionary) + { + _innerDictionary.Add(pair); + } + } + + public bool IsUndefined => _innerDictionary == null; + + public int Count => IsUndefined ? 0 : EnsureDictionary().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; + + public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; + + public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; + + public TValue this[TKey key] + { + get + { + if (IsUndefined) + { + throw new KeyNotFoundException(nameof(key)); + } + return EnsureDictionary()[key]; + } + set + { + EnsureDictionary()[key] = value; + } + } + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Values => Values; + + public IEnumerator> GetEnumerator() + { + if (IsUndefined) + { + IEnumerator> enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureDictionary().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + EnsureDictionary().Add(item); + } + + public void Clear() + { + EnsureDictionary().Clear(); + } + + public bool Contains(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int index) + { + if (IsUndefined) + { + return; + } + EnsureDictionary().CopyTo(array, index); + } + + public bool Remove(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(item); + } + + public void Add(TKey key, TValue value) + { + EnsureDictionary().Add(key, value); + } + + public bool ContainsKey(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().ContainsKey(key); + } + + public bool Remove(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(key); + } + + public bool TryGetValue(TKey key, out TValue value) + { + if (IsUndefined) + { + value = default; + return false; + } + return EnsureDictionary().TryGetValue(key, out value); + } + + public IDictionary EnsureDictionary() + { + return _innerDictionary ??= new Dictionary(); + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/ChangeTrackingList.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 0000000000000..3060ed9470d2c --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/ChangeTrackingList.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.ResourceManager.Terraform +{ + internal class ChangeTrackingList : IList, IReadOnlyList + { + private IList _innerList; + + public ChangeTrackingList() + { + } + + public ChangeTrackingList(IList innerList) + { + if (innerList != null) + { + _innerList = innerList; + } + } + + public ChangeTrackingList(IReadOnlyList innerList) + { + if (innerList != null) + { + _innerList = innerList.ToList(); + } + } + + public bool IsUndefined => _innerList == null; + + public int Count => IsUndefined ? 0 : EnsureList().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; + + public T this[int index] + { + get + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + return EnsureList()[index]; + } + set + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList()[index] = value; + } + } + + public void Reset() + { + _innerList = null; + } + + public IEnumerator GetEnumerator() + { + if (IsUndefined) + { + IEnumerator enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureList().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(T item) + { + EnsureList().Add(item); + } + + public void Clear() + { + EnsureList().Clear(); + } + + public bool Contains(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Contains(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + if (IsUndefined) + { + return; + } + EnsureList().CopyTo(array, arrayIndex); + } + + public bool Remove(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Remove(item); + } + + public int IndexOf(T item) + { + if (IsUndefined) + { + return -1; + } + return EnsureList().IndexOf(item); + } + + public void Insert(int index, T item) + { + EnsureList().Insert(index, item); + } + + public void RemoveAt(int index) + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList().RemoveAt(index); + } + + public IList EnsureList() + { + return _innerList ??= new List(); + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 0000000000000..763bd6f7f9977 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/ModelSerializationExtensions.cs @@ -0,0 +1,398 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using System.Xml; +using Azure.Core; + +namespace Azure.ResourceManager.Terraform +{ + internal static class ModelSerializationExtensions + { + internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); + + public static object GetObject(this JsonElement element) + { + switch (element.ValueKind) + { + case JsonValueKind.String: + return element.GetString(); + case JsonValueKind.Number: + if (element.TryGetInt32(out int intValue)) + { + return intValue; + } + if (element.TryGetInt64(out long longValue)) + { + return longValue; + } + return element.GetDouble(); + case JsonValueKind.True: + return true; + case JsonValueKind.False: + return false; + case JsonValueKind.Undefined: + case JsonValueKind.Null: + return null; + case JsonValueKind.Object: + var dictionary = new Dictionary(); + foreach (var jsonProperty in element.EnumerateObject()) + { + dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); + } + return dictionary; + case JsonValueKind.Array: + var list = new List(); + foreach (var item in element.EnumerateArray()) + { + list.Add(item.GetObject()); + } + return list.ToArray(); + default: + throw new NotSupportedException($"Not supported value kind {element.ValueKind}"); + } + } + + public static byte[] GetBytesFromBase64(this JsonElement element, string format) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + + return format switch + { + "U" => TypeFormatters.FromBase64UrlString(element.GetRequiredString()), + "D" => element.GetBytesFromBase64(), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + } + + public static DateTimeOffset GetDateTimeOffset(this JsonElement element, string format) => format switch + { + "U" when element.ValueKind == JsonValueKind.Number => DateTimeOffset.FromUnixTimeSeconds(element.GetInt64()), + _ => TypeFormatters.ParseDateTimeOffset(element.GetString(), format) + }; + + public static TimeSpan GetTimeSpan(this JsonElement element, string format) => TypeFormatters.ParseTimeSpan(element.GetString(), format); + + public static char GetChar(this JsonElement element) + { + if (element.ValueKind == JsonValueKind.String) + { + var text = element.GetString(); + if (text == null || text.Length != 1) + { + throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); + } + return text[0]; + } + else + { + throw new NotSupportedException($"Cannot convert {element.ValueKind} to a char"); + } + } + + [Conditional("DEBUG")] + public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) + { + throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); + } + + public static string GetRequiredString(this JsonElement element) + { + var value = element.GetString(); + if (value == null) + { + throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); + } + return value; + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTime value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, TimeSpan value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, char value) + { + writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); + } + + public static void WriteBase64StringValue(this Utf8JsonWriter writer, byte[] value, string format) + { + if (value == null) + { + writer.WriteNullValue(); + return; + } + switch (format) + { + case "U": + writer.WriteStringValue(TypeFormatters.ToBase64UrlString(value)); + break; + case "D": + writer.WriteBase64StringValue(value); + break; + default: + throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)); + } + } + + public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + if (format != "U") + { + throw new ArgumentOutOfRangeException(nameof(format), "Only 'U' format is supported when writing a DateTimeOffset as a Number."); + } + writer.WriteNumberValue(value.ToUnixTimeSeconds()); + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) + { + switch (value) + { + case null: + writer.WriteNullValue(); + break; + case IJsonModel jsonModel: + jsonModel.Write(writer, options ?? WireOptions); + break; + case IUtf8JsonSerializable serializable: + serializable.Write(writer); + break; + case byte[] bytes: + writer.WriteBase64StringValue(bytes); + break; + case BinaryData bytes0: + writer.WriteBase64StringValue(bytes0); + break; + case JsonElement json: + json.WriteTo(writer); + break; + case int i: + writer.WriteNumberValue(i); + break; + case decimal d: + writer.WriteNumberValue(d); + break; + case double d0: + if (double.IsNaN(d0)) + { + writer.WriteStringValue("NaN"); + } + else + { + writer.WriteNumberValue(d0); + } + break; + case float f: + writer.WriteNumberValue(f); + break; + case long l: + writer.WriteNumberValue(l); + break; + case string s: + writer.WriteStringValue(s); + break; + case bool b: + writer.WriteBooleanValue(b); + break; + case Guid g: + writer.WriteStringValue(g); + break; + case DateTimeOffset dateTimeOffset: + writer.WriteStringValue(dateTimeOffset, "O"); + break; + case DateTime dateTime: + writer.WriteStringValue(dateTime, "O"); + break; + case IEnumerable> enumerable: + writer.WriteStartObject(); + foreach (var pair in enumerable) + { + writer.WritePropertyName(pair.Key); + writer.WriteObjectValue(pair.Value, options); + } + writer.WriteEndObject(); + break; + case IEnumerable objectEnumerable: + writer.WriteStartArray(); + foreach (var item in objectEnumerable) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + break; + case TimeSpan timeSpan: + writer.WriteStringValue(timeSpan, "P"); + break; + default: + throw new NotSupportedException($"Not supported type {value.GetType()}"); + } + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) + { + writer.WriteObjectValue(value, options); + } + + internal static class TypeFormatters + { + private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; + public const string DefaultNumberFormat = "G"; + + public static string ToString(bool value) => value ? "true" : "false"; + + public static string ToString(DateTime value, string format) => value.Kind switch + { + DateTimeKind.Utc => ToString((DateTimeOffset)value, format), + _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") + }; + + public static string ToString(DateTimeOffset value, string format) => format switch + { + "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "R" => value.ToString("r", CultureInfo.InvariantCulture), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(TimeSpan value, string format) => format switch + { + "P" => XmlConvert.ToString(value), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(byte[] value, string format) => format switch + { + "U" => ToBase64UrlString(value), + "D" => Convert.ToBase64String(value), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + + public static string ToBase64UrlString(byte[] value) + { + int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; + int size = checked(numWholeOrPartialInputBlocks * 4); + char[] output = new char[size]; + + int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); + + int i = 0; + for (; i < numBase64Chars; i++) + { + char ch = output[i]; + if (ch == '+') + { + output[i] = '-'; + } + else + { + if (ch == '/') + { + output[i] = '_'; + } + else + { + if (ch == '=') + { + break; + } + } + } + } + + return new string(output, 0, i); + } + + public static byte[] FromBase64UrlString(string value) + { + int paddingCharsToAdd = (value.Length % 4) switch + { + 0 => 0, + 2 => 2, + 3 => 1, + _ => throw new InvalidOperationException("Malformed input") + }; + char[] output = new char[(value.Length + paddingCharsToAdd)]; + int i = 0; + for (; i < value.Length; i++) + { + char ch = value[i]; + if (ch == '-') + { + output[i] = '+'; + } + else + { + if (ch == '_') + { + output[i] = '/'; + } + else + { + output[i] = ch; + } + } + } + + for (; i < output.Length; i++) + { + output[i] = '='; + } + + return Convert.FromBase64CharArray(output, 0, output.Length); + } + + public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch + { + "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), + _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) + }; + + public static TimeSpan ParseTimeSpan(string value, string format) => format switch + { + "P" => XmlConvert.ToTimeSpan(value), + _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) + }; + + public static string ConvertToString(object value, string format = null) => value switch + { + null => "null", + string s => s, + bool b => ToString(b), + int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), + byte[] b0 when format != null => ToString(b0, format), + IEnumerable s0 => string.Join(",", s0), + DateTimeOffset dateTime when format != null => ToString(dateTime, format), + TimeSpan timeSpan when format != null => ToString(timeSpan, format), + TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), + Guid guid => guid.ToString(), + BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), + _ => value.ToString() + }; + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/Optional.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/Optional.cs new file mode 100644 index 0000000000000..3eceaa43bffe6 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/Optional.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; + +namespace Azure.ResourceManager.Terraform +{ + internal static class Optional + { + public static bool IsCollectionDefined(IEnumerable collection) + { + return !(collection is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined); + } + + public static bool IsCollectionDefined(IDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsCollectionDefined(IReadOnlyDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsDefined(T? value) + where T : struct + { + return value.HasValue; + } + + public static bool IsDefined(object value) + { + return value != null; + } + + public static bool IsDefined(JsonElement value) + { + return value.ValueKind != JsonValueKind.Undefined; + } + + public static bool IsDefined(string value) + { + return value != null; + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/Utf8JsonRequestContent.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 0000000000000..dcad4261c64d2 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; + +namespace Azure.ResourceManager.Terraform +{ + internal class Utf8JsonRequestContent : RequestContent + { + private readonly MemoryStream _stream; + private readonly RequestContent _content; + + public Utf8JsonRequestContent() + { + _stream = new MemoryStream(); + _content = Create(_stream); + JsonWriter = new Utf8JsonWriter(_stream); + } + + public Utf8JsonWriter JsonWriter { get; } + + public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) + { + await JsonWriter.FlushAsync().ConfigureAwait(false); + await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); + } + + public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) + { + JsonWriter.Flush(); + _content.WriteTo(stream, cancellationToken); + } + + public override bool TryComputeLength(out long length) + { + length = JsonWriter.BytesCommitted + JsonWriter.BytesPending; + return true; + } + + public override void Dispose() + { + JsonWriter.Dispose(); + _content.Dispose(); + _stream.Dispose(); + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/LongRunningOperation/TerraformArmOperationOfT.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/LongRunningOperation/TerraformArmOperationOfT.cs new file mode 100644 index 0000000000000..23e4d4dba878c --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/LongRunningOperation/TerraformArmOperationOfT.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.ResourceManager.Terraform +{ +#pragma warning disable SA1649 // File name should match first type name + internal class TerraformArmOperation : ArmOperation +#pragma warning restore SA1649 // File name should match first type name + { + private readonly OperationInternal _operation; + private readonly RehydrationToken? _completeRehydrationToken; + private readonly NextLinkOperationImplementation _nextLinkOperation; + private readonly string _operationId; + + /// Initializes a new instance of TerraformArmOperation for mocking. + protected TerraformArmOperation() + { + } + + internal TerraformArmOperation(Response response, RehydrationToken? rehydrationToken = null) + { + _operation = OperationInternal.Succeeded(response.GetRawResponse(), response.Value); + _completeRehydrationToken = rehydrationToken; + _operationId = GetOperationId(rehydrationToken); + } + + internal TerraformArmOperation(IOperationSource source, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response, OperationFinalStateVia finalStateVia, bool skipApiVersionOverride = false, string apiVersionOverrideValue = null) + { + var nextLinkOperation = NextLinkOperationImplementation.Create(pipeline, request.Method, request.Uri.ToUri(), response, finalStateVia, skipApiVersionOverride, apiVersionOverrideValue); + if (nextLinkOperation is NextLinkOperationImplementation nextLinkOperationValue) + { + _nextLinkOperation = nextLinkOperationValue; + _operationId = _nextLinkOperation.OperationId; + } + else + { + _completeRehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(request.Method, request.Uri.ToUri(), response, finalStateVia); + _operationId = GetOperationId(_completeRehydrationToken); + } + _operation = new OperationInternal(NextLinkOperationImplementation.Create(source, nextLinkOperation), clientDiagnostics, response, "TerraformArmOperation", fallbackStrategy: new SequentialDelayStrategy()); + } + + private string GetOperationId(RehydrationToken? rehydrationToken) + { + if (rehydrationToken is null) + { + return null; + } + var lroDetails = ModelReaderWriter.Write(rehydrationToken, ModelReaderWriterOptions.Json).ToObjectFromJson>(); + return lroDetails["id"]; + } + /// + public override string Id => _operationId ?? NextLinkOperationImplementation.NotSet; + + /// + public override RehydrationToken? GetRehydrationToken() => _nextLinkOperation?.GetRehydrationToken() ?? _completeRehydrationToken; + + /// + public override T Value => _operation.Value; + + /// + public override bool HasValue => _operation.HasValue; + + /// + public override bool HasCompleted => _operation.HasCompleted; + + /// + public override Response GetRawResponse() => _operation.RawResponse; + + /// + public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); + + /// + public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); + + /// + public override Response WaitForCompletion(CancellationToken cancellationToken = default) => _operation.WaitForCompletion(cancellationToken); + + /// + public override Response WaitForCompletion(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletion(pollingInterval, cancellationToken); + + /// + public override ValueTask> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); + + /// + public override ValueTask> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/LongRunningOperation/TerraformOperationStatusOperationSource.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/LongRunningOperation/TerraformOperationStatusOperationSource.cs new file mode 100644 index 0000000000000..47006d98958e1 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/LongRunningOperation/TerraformOperationStatusOperationSource.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.ResourceManager.Terraform.Models; + +namespace Azure.ResourceManager.Terraform +{ + internal class TerraformOperationStatusOperationSource : IOperationSource + { + TerraformOperationStatus IOperationSource.CreateResult(Response response, CancellationToken cancellationToken) + { + using var document = JsonDocument.Parse(response.ContentStream); + return TerraformOperationStatus.DeserializeTerraformOperationStatus(document.RootElement); + } + + async ValueTask IOperationSource.CreateResultAsync(Response response, CancellationToken cancellationToken) + { + using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false); + return TerraformOperationStatus.DeserializeTerraformOperationStatus(document.RootElement); + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/CommonExportProperties.Serialization.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/CommonExportProperties.Serialization.cs new file mode 100644 index 0000000000000..03cdc7db205e9 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/CommonExportProperties.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Terraform.Models +{ + [PersistableModelProxy(typeof(UnknownCommonExportProperties))] + public partial class CommonExportProperties : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CommonExportProperties)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (Optional.IsDefined(TargetProvider)) + { + writer.WritePropertyName("targetProvider"u8); + writer.WriteStringValue(TargetProvider.Value.ToString()); + } + if (Optional.IsDefined(IsOutputFullPropertiesEnabled)) + { + writer.WritePropertyName("fullProperties"u8); + writer.WriteBooleanValue(IsOutputFullPropertiesEnabled.Value); + } + if (Optional.IsDefined(IsMaskSensitiveEnabled)) + { + writer.WritePropertyName("maskSensitive"u8); + writer.WriteBooleanValue(IsMaskSensitiveEnabled.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CommonExportProperties IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CommonExportProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCommonExportProperties(document.RootElement, options); + } + + internal static CommonExportProperties DeserializeCommonExportProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "ExportQuery": return ExportQueryTerraform.DeserializeExportQueryTerraform(element, options); + case "ExportResource": return ExportResourceTerraform.DeserializeExportResourceTerraform(element, options); + case "ExportResourceGroup": return ExportResourceGroupTerraform.DeserializeExportResourceGroupTerraform(element, options); + } + } + return UnknownCommonExportProperties.DeserializeUnknownCommonExportProperties(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CommonExportProperties)} does not support writing '{options.Format}' format."); + } + } + + CommonExportProperties IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeCommonExportProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CommonExportProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/CommonExportProperties.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/CommonExportProperties.cs new file mode 100644 index 0000000000000..54010f3bd17e3 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/CommonExportProperties.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Terraform.Models +{ + /// + /// The base export parameter + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + public abstract partial class CommonExportProperties + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected CommonExportProperties() + { + } + + /// Initializes a new instance of . + /// The parameter type. + /// The target Azure Terraform Provider. + /// Whether to output all non-computed properties in the generated Terraform configuration? This probably needs manual modifications to make it valid. + /// Mask sensitive attributes in the Terraform configuration. + /// Keeps track of any properties unknown to the library. + internal CommonExportProperties(CommonExportType type, TargetTerraformProvider? targetProvider, bool? isOutputFullPropertiesEnabled, bool? isMaskSensitiveEnabled, IDictionary serializedAdditionalRawData) + { + Type = type; + TargetProvider = targetProvider; + IsOutputFullPropertiesEnabled = isOutputFullPropertiesEnabled; + IsMaskSensitiveEnabled = isMaskSensitiveEnabled; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The parameter type. + internal CommonExportType Type { get; set; } + /// The target Azure Terraform Provider. + public TargetTerraformProvider? TargetProvider { get; set; } + /// Whether to output all non-computed properties in the generated Terraform configuration? This probably needs manual modifications to make it valid. + public bool? IsOutputFullPropertiesEnabled { get; set; } + /// Mask sensitive attributes in the Terraform configuration. + public bool? IsMaskSensitiveEnabled { get; set; } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/CommonExportType.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/CommonExportType.cs new file mode 100644 index 0000000000000..e46504cb4119a --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/CommonExportType.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.Terraform.Models +{ + /// The parameter type. + internal readonly partial struct CommonExportType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public CommonExportType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ExportResourceValue = "ExportResource"; + private const string ExportResourceGroupValue = "ExportResourceGroup"; + private const string ExportQueryValue = "ExportQuery"; + + /// ExportResource. + public static CommonExportType ExportResource { get; } = new CommonExportType(ExportResourceValue); + /// ExportResourceGroup. + public static CommonExportType ExportResourceGroup { get; } = new CommonExportType(ExportResourceGroupValue); + /// ExportQuery. + public static CommonExportType ExportQuery { get; } = new CommonExportType(ExportQueryValue); + /// Determines if two values are the same. + public static bool operator ==(CommonExportType left, CommonExportType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(CommonExportType left, CommonExportType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator CommonExportType(string value) => new CommonExportType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is CommonExportType other && Equals(other); + /// + public bool Equals(CommonExportType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportQueryTerraform.Serialization.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportQueryTerraform.Serialization.cs new file mode 100644 index 0000000000000..78e0755004304 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportQueryTerraform.Serialization.cs @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Terraform.Models +{ + public partial class ExportQueryTerraform : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ExportQueryTerraform)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("query"u8); + writer.WriteStringValue(Query); + if (Optional.IsDefined(NamePattern)) + { + writer.WritePropertyName("namePattern"u8); + writer.WriteStringValue(NamePattern); + } + if (Optional.IsDefined(IsRecursive)) + { + writer.WritePropertyName("recursive"u8); + writer.WriteBooleanValue(IsRecursive.Value); + } + } + + ExportQueryTerraform IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ExportQueryTerraform)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeExportQueryTerraform(document.RootElement, options); + } + + internal static ExportQueryTerraform DeserializeExportQueryTerraform(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string query = default; + string namePattern = default; + bool? recursive = default; + CommonExportType type = default; + TargetTerraformProvider? targetProvider = default; + bool? fullProperties = default; + bool? maskSensitive = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("query"u8)) + { + query = property.Value.GetString(); + continue; + } + if (property.NameEquals("namePattern"u8)) + { + namePattern = property.Value.GetString(); + continue; + } + if (property.NameEquals("recursive"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + recursive = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new CommonExportType(property.Value.GetString()); + continue; + } + if (property.NameEquals("targetProvider"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + targetProvider = new TargetTerraformProvider(property.Value.GetString()); + continue; + } + if (property.NameEquals("fullProperties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fullProperties = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("maskSensitive"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maskSensitive = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ExportQueryTerraform( + type, + targetProvider, + fullProperties, + maskSensitive, + serializedAdditionalRawData, + query, + namePattern, + recursive); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ExportQueryTerraform)} does not support writing '{options.Format}' format."); + } + } + + ExportQueryTerraform IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeExportQueryTerraform(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ExportQueryTerraform)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportQueryTerraform.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportQueryTerraform.cs new file mode 100644 index 0000000000000..2d7c71a05d0cb --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportQueryTerraform.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Terraform.Models +{ + /// Export parameter for resources queried by ARG (Azure Resource Graph). + public partial class ExportQueryTerraform : CommonExportProperties + { + /// Initializes a new instance of . + /// 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"`. + /// is null. + public ExportQueryTerraform(string query) + { + Argument.AssertNotNull(query, nameof(query)); + + Query = query; + Type = CommonExportType.ExportQuery; + } + + /// Initializes a new instance of . + /// The parameter type. + /// The target Azure Terraform Provider. + /// Whether to output all non-computed properties in the generated Terraform configuration? This probably needs manual modifications to make it valid. + /// Mask sensitive attributes in the Terraform configuration. + /// Keeps track of any properties unknown to the library. + /// 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"`. + /// The name pattern of the Terraform resources. + /// Whether to recursively list child resources of the query result. + internal ExportQueryTerraform(CommonExportType type, TargetTerraformProvider? targetProvider, bool? isOutputFullPropertiesEnabled, bool? isMaskSensitiveEnabled, IDictionary serializedAdditionalRawData, string query, string namePattern, bool? isRecursive) : base(type, targetProvider, isOutputFullPropertiesEnabled, isMaskSensitiveEnabled, serializedAdditionalRawData) + { + Query = query; + NamePattern = namePattern; + IsRecursive = isRecursive; + Type = type; + } + + /// Initializes a new instance of for deserialization. + internal ExportQueryTerraform() + { + } + + /// 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"`. + public string Query { get; } + /// The name pattern of the Terraform resources. + public string NamePattern { get; set; } + /// Whether to recursively list child resources of the query result. + public bool? IsRecursive { get; set; } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportResourceGroupTerraform.Serialization.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportResourceGroupTerraform.Serialization.cs new file mode 100644 index 0000000000000..427a6a7573866 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportResourceGroupTerraform.Serialization.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Terraform.Models +{ + public partial class ExportResourceGroupTerraform : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ExportResourceGroupTerraform)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("resourceGroupName"u8); + writer.WriteStringValue(ResourceGroupName); + if (Optional.IsDefined(NamePattern)) + { + writer.WritePropertyName("namePattern"u8); + writer.WriteStringValue(NamePattern); + } + } + + ExportResourceGroupTerraform IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ExportResourceGroupTerraform)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeExportResourceGroupTerraform(document.RootElement, options); + } + + internal static ExportResourceGroupTerraform DeserializeExportResourceGroupTerraform(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string resourceGroupName = default; + string namePattern = default; + CommonExportType type = default; + TargetTerraformProvider? targetProvider = default; + bool? fullProperties = default; + bool? maskSensitive = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("resourceGroupName"u8)) + { + resourceGroupName = property.Value.GetString(); + continue; + } + if (property.NameEquals("namePattern"u8)) + { + namePattern = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new CommonExportType(property.Value.GetString()); + continue; + } + if (property.NameEquals("targetProvider"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + targetProvider = new TargetTerraformProvider(property.Value.GetString()); + continue; + } + if (property.NameEquals("fullProperties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fullProperties = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("maskSensitive"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maskSensitive = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ExportResourceGroupTerraform( + type, + targetProvider, + fullProperties, + maskSensitive, + serializedAdditionalRawData, + resourceGroupName, + namePattern); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ExportResourceGroupTerraform)} does not support writing '{options.Format}' format."); + } + } + + ExportResourceGroupTerraform IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeExportResourceGroupTerraform(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ExportResourceGroupTerraform)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportResourceGroupTerraform.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportResourceGroupTerraform.cs new file mode 100644 index 0000000000000..85f983fd38c47 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportResourceGroupTerraform.cs @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Terraform.Models +{ + /// Export parameter for a resource group. + public partial class ExportResourceGroupTerraform : CommonExportProperties + { + /// Initializes a new instance of . + /// The name of the resource group to be exported. + /// is null. + public ExportResourceGroupTerraform(string resourceGroupName) + { + Argument.AssertNotNull(resourceGroupName, nameof(resourceGroupName)); + + ResourceGroupName = resourceGroupName; + Type = CommonExportType.ExportResourceGroup; + } + + /// Initializes a new instance of . + /// The parameter type. + /// The target Azure Terraform Provider. + /// Whether to output all non-computed properties in the generated Terraform configuration? This probably needs manual modifications to make it valid. + /// Mask sensitive attributes in the Terraform configuration. + /// Keeps track of any properties unknown to the library. + /// The name of the resource group to be exported. + /// The name pattern of the Terraform resources. + internal ExportResourceGroupTerraform(CommonExportType type, TargetTerraformProvider? targetProvider, bool? isOutputFullPropertiesEnabled, bool? isMaskSensitiveEnabled, IDictionary serializedAdditionalRawData, string resourceGroupName, string namePattern) : base(type, targetProvider, isOutputFullPropertiesEnabled, isMaskSensitiveEnabled, serializedAdditionalRawData) + { + ResourceGroupName = resourceGroupName; + NamePattern = namePattern; + Type = type; + } + + /// Initializes a new instance of for deserialization. + internal ExportResourceGroupTerraform() + { + } + + /// The name of the resource group to be exported. + public string ResourceGroupName { get; } + /// The name pattern of the Terraform resources. + public string NamePattern { get; set; } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportResourceTerraform.Serialization.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportResourceTerraform.Serialization.cs new file mode 100644 index 0000000000000..20779d9bdedba --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportResourceTerraform.Serialization.cs @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Terraform.Models +{ + public partial class ExportResourceTerraform : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ExportResourceTerraform)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("resourceIds"u8); + writer.WriteStartArray(); + foreach (var item in ResourceIds) + { + if (item == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(ResourceName)) + { + writer.WritePropertyName("resourceName"u8); + writer.WriteStringValue(ResourceName); + } + if (Optional.IsDefined(ResourceType)) + { + writer.WritePropertyName("resourceType"u8); + writer.WriteStringValue(ResourceType); + } + if (Optional.IsDefined(NamePattern)) + { + writer.WritePropertyName("namePattern"u8); + writer.WriteStringValue(NamePattern); + } + } + + ExportResourceTerraform IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ExportResourceTerraform)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeExportResourceTerraform(document.RootElement, options); + } + + internal static ExportResourceTerraform DeserializeExportResourceTerraform(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList resourceIds = default; + string resourceName = default; + string resourceType = default; + string namePattern = default; + CommonExportType type = default; + TargetTerraformProvider? targetProvider = default; + bool? fullProperties = default; + bool? maskSensitive = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("resourceIds"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(new ResourceIdentifier(item.GetString())); + } + } + resourceIds = array; + continue; + } + if (property.NameEquals("resourceName"u8)) + { + resourceName = property.Value.GetString(); + continue; + } + if (property.NameEquals("resourceType"u8)) + { + resourceType = property.Value.GetString(); + continue; + } + if (property.NameEquals("namePattern"u8)) + { + namePattern = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new CommonExportType(property.Value.GetString()); + continue; + } + if (property.NameEquals("targetProvider"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + targetProvider = new TargetTerraformProvider(property.Value.GetString()); + continue; + } + if (property.NameEquals("fullProperties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fullProperties = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("maskSensitive"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maskSensitive = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ExportResourceTerraform( + type, + targetProvider, + fullProperties, + maskSensitive, + serializedAdditionalRawData, + resourceIds, + resourceName, + resourceType, + namePattern); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ExportResourceTerraform)} does not support writing '{options.Format}' format."); + } + } + + ExportResourceTerraform IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeExportResourceTerraform(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ExportResourceTerraform)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportResourceTerraform.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportResourceTerraform.cs new file mode 100644 index 0000000000000..37d65bb28dfd9 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/ExportResourceTerraform.cs @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; +using Azure.Core; + +namespace Azure.ResourceManager.Terraform.Models +{ + /// Export parameter for individual resources. + public partial class ExportResourceTerraform : CommonExportProperties + { + /// Initializes a new instance of . + /// The id of the resource to be exported. + /// is null. + public ExportResourceTerraform(IEnumerable resourceIds) + { + Argument.AssertNotNull(resourceIds, nameof(resourceIds)); + + ResourceIds = resourceIds.ToList(); + Type = CommonExportType.ExportResource; + } + + /// Initializes a new instance of . + /// The parameter type. + /// The target Azure Terraform Provider. + /// Whether to output all non-computed properties in the generated Terraform configuration? This probably needs manual modifications to make it valid. + /// Mask sensitive attributes in the Terraform configuration. + /// Keeps track of any properties unknown to the library. + /// The id of the resource to be exported. + /// The Terraform resource name. Only works when `resourceIds` contains only one item. + /// The Terraform resource type. Only works when `resourceIds` contains only one item. + /// The name pattern of the Terraform resources. + internal ExportResourceTerraform(CommonExportType type, TargetTerraformProvider? targetProvider, bool? isOutputFullPropertiesEnabled, bool? isMaskSensitiveEnabled, IDictionary serializedAdditionalRawData, IList resourceIds, string resourceName, string resourceType, string namePattern) : base(type, targetProvider, isOutputFullPropertiesEnabled, isMaskSensitiveEnabled, serializedAdditionalRawData) + { + ResourceIds = resourceIds; + ResourceName = resourceName; + ResourceType = resourceType; + NamePattern = namePattern; + Type = type; + } + + /// Initializes a new instance of for deserialization. + internal ExportResourceTerraform() + { + } + + /// The id of the resource to be exported. + public IList ResourceIds { get; } + /// The Terraform resource name. Only works when `resourceIds` contains only one item. + public string ResourceName { get; set; } + /// The Terraform resource type. Only works when `resourceIds` contains only one item. + public string ResourceType { get; set; } + /// The name pattern of the Terraform resources. + public string NamePattern { get; set; } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TargetTerraformProvider.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TargetTerraformProvider.cs new file mode 100644 index 0000000000000..7ac7d049825cf --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TargetTerraformProvider.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.Terraform.Models +{ + /// The target Azure Terraform Provider. + public readonly partial struct TargetTerraformProvider : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public TargetTerraformProvider(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AzureRMValue = "azurerm"; + private const string AzApiValue = "azapi"; + + /// https://registry.terraform.io/providers/hashicorp/azurerm/latest. + public static TargetTerraformProvider AzureRM { get; } = new TargetTerraformProvider(AzureRMValue); + /// https://registry.terraform.io/providers/Azure/azapi/latest. + public static TargetTerraformProvider AzApi { get; } = new TargetTerraformProvider(AzApiValue); + /// Determines if two values are the same. + public static bool operator ==(TargetTerraformProvider left, TargetTerraformProvider right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(TargetTerraformProvider left, TargetTerraformProvider right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator TargetTerraformProvider(string value) => new TargetTerraformProvider(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is TargetTerraformProvider other && Equals(other); + /// + public bool Equals(TargetTerraformProvider other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformExportResult.Serialization.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformExportResult.Serialization.cs new file mode 100644 index 0000000000000..e08eb4e6a8c7e --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformExportResult.Serialization.cs @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Terraform.Models +{ + public partial class TerraformExportResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TerraformExportResult)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Configuration)) + { + writer.WritePropertyName("configuration"u8); + writer.WriteStringValue(Configuration); + } + if (Optional.IsCollectionDefined(SkippedResourceIds)) + { + writer.WritePropertyName("skippedResources"u8); + writer.WriteStartArray(); + foreach (var item in SkippedResourceIds) + { + if (item == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Errors)) + { + writer.WritePropertyName("errors"u8); + writer.WriteStartArray(); + foreach (var item in Errors) + { + JsonSerializer.Serialize(writer, item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TerraformExportResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TerraformExportResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTerraformExportResult(document.RootElement, options); + } + + internal static TerraformExportResult DeserializeTerraformExportResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string configuration = default; + IReadOnlyList skippedResources = default; + IReadOnlyList errors = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("configuration"u8)) + { + configuration = property.Value.GetString(); + continue; + } + if (property.NameEquals("skippedResources"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(new ResourceIdentifier(item.GetString())); + } + } + skippedResources = array; + continue; + } + if (property.NameEquals("errors"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(JsonSerializer.Deserialize(item.GetRawText())); + } + errors = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TerraformExportResult(configuration, skippedResources ?? new ChangeTrackingList(), errors ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TerraformExportResult)} does not support writing '{options.Format}' format."); + } + } + + TerraformExportResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeTerraformExportResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TerraformExportResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformExportResult.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformExportResult.cs new file mode 100644 index 0000000000000..68a442fa99f7f --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformExportResult.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure.Core; + +namespace Azure.ResourceManager.Terraform.Models +{ + /// The Terraform export result. + public partial class TerraformExportResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal TerraformExportResult() + { + SkippedResourceIds = new ChangeTrackingList(); + Errors = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The Terraform configuration content. + /// A list of Azure resources which are not exported to Terraform due to there is no corresponding resources in Terraform. + /// A list of errors derived during exporting each resource. + /// Keeps track of any properties unknown to the library. + internal TerraformExportResult(string configuration, IReadOnlyList skippedResourceIds, IReadOnlyList errors, IDictionary serializedAdditionalRawData) + { + Configuration = configuration; + SkippedResourceIds = skippedResourceIds; + Errors = errors; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The Terraform configuration content. + public string Configuration { get; } + /// A list of Azure resources which are not exported to Terraform due to there is no corresponding resources in Terraform. + public IReadOnlyList SkippedResourceIds { get; } + /// A list of errors derived during exporting each resource. + public IReadOnlyList Errors { get; } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformOperationStatus.Serialization.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformOperationStatus.Serialization.cs new file mode 100644 index 0000000000000..8774d65bbf6ae --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformOperationStatus.Serialization.cs @@ -0,0 +1,220 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Terraform.Models +{ + public partial class TerraformOperationStatus : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TerraformOperationStatus)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsDefined(Properties)) + { + writer.WritePropertyName("properties"u8); + writer.WriteObjectValue(Properties, options); + } + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + if (options.Format != "W" && Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (options.Format != "W" && Optional.IsDefined(StartOn)) + { + writer.WritePropertyName("startTime"u8); + writer.WriteStringValue(StartOn.Value, "O"); + } + if (options.Format != "W" && Optional.IsDefined(EndOn)) + { + writer.WritePropertyName("endTime"u8); + writer.WriteStringValue(EndOn.Value, "O"); + } + if (options.Format != "W" && Optional.IsDefined(PercentComplete)) + { + writer.WritePropertyName("percentComplete"u8); + writer.WriteNumberValue(PercentComplete.Value); + } + if (options.Format != "W" && Optional.IsDefined(Error)) + { + writer.WritePropertyName("error"u8); + JsonSerializer.Serialize(writer, Error); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TerraformOperationStatus IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TerraformOperationStatus)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTerraformOperationStatus(document.RootElement, options); + } + + internal static TerraformOperationStatus DeserializeTerraformOperationStatus(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + TerraformExportResult properties = default; + TerraformResourceProvisioningState status = default; + string name = default; + DateTimeOffset? startTime = default; + DateTimeOffset? endTime = default; + double? percentComplete = default; + ResponseError error = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + properties = TerraformExportResult.DeserializeTerraformExportResult(property.Value, options); + continue; + } + if (property.NameEquals("status"u8)) + { + status = new TerraformResourceProvisioningState(property.Value.GetString()); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("startTime"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + startTime = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("endTime"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + endTime = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("percentComplete"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + percentComplete = property.Value.GetDouble(); + continue; + } + if (property.NameEquals("error"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + error = JsonSerializer.Deserialize(property.Value.GetRawText()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TerraformOperationStatus( + properties, + status, + name, + startTime, + endTime, + percentComplete, + error, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TerraformOperationStatus)} does not support writing '{options.Format}' format."); + } + } + + TerraformOperationStatus IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeTerraformOperationStatus(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TerraformOperationStatus)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformOperationStatus.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformOperationStatus.cs new file mode 100644 index 0000000000000..4ae95bbb75d63 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformOperationStatus.cs @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Terraform.Models +{ + /// The status of the LRO operation. + public partial class TerraformOperationStatus + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The operation status. + internal TerraformOperationStatus(TerraformResourceProvisioningState status) + { + Status = status; + } + + /// Initializes a new instance of . + /// RP-specific properties for the operationStatus resource, only appears when operation ended with Succeeded status. + /// The operation status. + /// The name of the operationStatus resource. + /// Operation start time. + /// Operation complete time. + /// The progress made toward completing the operation. + /// Errors that occurred if the operation ended with Canceled or Failed status. + /// Keeps track of any properties unknown to the library. + internal TerraformOperationStatus(TerraformExportResult properties, TerraformResourceProvisioningState status, string name, DateTimeOffset? startOn, DateTimeOffset? endOn, double? percentComplete, ResponseError error, IDictionary serializedAdditionalRawData) + { + Properties = properties; + Status = status; + Name = name; + StartOn = startOn; + EndOn = endOn; + PercentComplete = percentComplete; + Error = error; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal TerraformOperationStatus() + { + } + + /// RP-specific properties for the operationStatus resource, only appears when operation ended with Succeeded status. + public TerraformExportResult Properties { get; } + /// The operation status. + public TerraformResourceProvisioningState Status { get; } + /// The name of the operationStatus resource. + public string Name { get; } + /// Operation start time. + public DateTimeOffset? StartOn { get; } + /// Operation complete time. + public DateTimeOffset? EndOn { get; } + /// The progress made toward completing the operation. + public double? PercentComplete { get; } + /// Errors that occurred if the operation ended with Canceled or Failed status. + public ResponseError Error { get; } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformResourceProvisioningState.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformResourceProvisioningState.cs new file mode 100644 index 0000000000000..9c9f12b2e4b41 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/TerraformResourceProvisioningState.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.Terraform.Models +{ + /// The provisioning state of a resource type. + public readonly partial struct TerraformResourceProvisioningState : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public TerraformResourceProvisioningState(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SucceededValue = "Succeeded"; + private const string FailedValue = "Failed"; + private const string CanceledValue = "Canceled"; + + /// Resource has been created. + public static TerraformResourceProvisioningState Succeeded { get; } = new TerraformResourceProvisioningState(SucceededValue); + /// Resource creation failed. + public static TerraformResourceProvisioningState Failed { get; } = new TerraformResourceProvisioningState(FailedValue); + /// Resource creation was canceled. + public static TerraformResourceProvisioningState Canceled { get; } = new TerraformResourceProvisioningState(CanceledValue); + /// Determines if two values are the same. + public static bool operator ==(TerraformResourceProvisioningState left, TerraformResourceProvisioningState right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(TerraformResourceProvisioningState left, TerraformResourceProvisioningState right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator TerraformResourceProvisioningState(string value) => new TerraformResourceProvisioningState(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is TerraformResourceProvisioningState other && Equals(other); + /// + public bool Equals(TerraformResourceProvisioningState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/UnknownCommonExportProperties.Serialization.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/UnknownCommonExportProperties.Serialization.cs new file mode 100644 index 0000000000000..0d73067c1f588 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/UnknownCommonExportProperties.Serialization.cs @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Terraform.Models +{ + internal partial class UnknownCommonExportProperties : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CommonExportProperties)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + CommonExportProperties IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CommonExportProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCommonExportProperties(document.RootElement, options); + } + + internal static UnknownCommonExportProperties DeserializeUnknownCommonExportProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + CommonExportType type = "Unknown"; + TargetTerraformProvider? targetProvider = default; + bool? fullProperties = default; + bool? maskSensitive = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new CommonExportType(property.Value.GetString()); + continue; + } + if (property.NameEquals("targetProvider"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + targetProvider = new TargetTerraformProvider(property.Value.GetString()); + continue; + } + if (property.NameEquals("fullProperties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fullProperties = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("maskSensitive"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maskSensitive = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownCommonExportProperties(type, targetProvider, fullProperties, maskSensitive, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CommonExportProperties)} does not support writing '{options.Format}' format."); + } + } + + CommonExportProperties IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeCommonExportProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CommonExportProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/UnknownCommonExportProperties.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/UnknownCommonExportProperties.cs new file mode 100644 index 0000000000000..1da2d03b3b7f6 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/Models/UnknownCommonExportProperties.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Terraform.Models +{ + /// Unknown version of CommonExportProperties. + internal partial class UnknownCommonExportProperties : CommonExportProperties + { + /// Initializes a new instance of . + /// The parameter type. + /// The target Azure Terraform Provider. + /// Whether to output all non-computed properties in the generated Terraform configuration? This probably needs manual modifications to make it valid. + /// Mask sensitive attributes in the Terraform configuration. + /// Keeps track of any properties unknown to the library. + internal UnknownCommonExportProperties(CommonExportType type, TargetTerraformProvider? targetProvider, bool? isOutputFullPropertiesEnabled, bool? isMaskSensitiveEnabled, IDictionary serializedAdditionalRawData) : base(type, targetProvider, isOutputFullPropertiesEnabled, isMaskSensitiveEnabled, serializedAdditionalRawData) + { + Type = type; + } + + /// Initializes a new instance of for deserialization. + internal UnknownCommonExportProperties() + { + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/ProviderConstants.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/ProviderConstants.cs new file mode 100644 index 0000000000000..32fce05439869 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/ProviderConstants.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using Azure.Core.Pipeline; + +namespace Azure.ResourceManager.Terraform +{ + internal static class ProviderConstants + { + public static string DefaultProviderNamespace { get; } = ClientDiagnostics.GetResourceProviderNamespace(typeof(ProviderConstants).Assembly); + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/RestOperations/TerraformRestOperations.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/RestOperations/TerraformRestOperations.cs new file mode 100644 index 0000000000000..de54bfe428895 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Generated/RestOperations/TerraformRestOperations.cs @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; +using Azure.ResourceManager.Terraform.Models; + +namespace Azure.ResourceManager.Terraform +{ + internal partial class TerraformRestOperations + { + private readonly TelemetryDetails _userAgent; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// Initializes a new instance of TerraformRestOperations. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The application id to use for user agent. + /// Service host. + /// The API version to use for this operation. + /// or is null. + public TerraformRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) + { + _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); + _endpoint = endpoint ?? new Uri("https://management.azure.com"); + _apiVersion = apiVersion ?? "2023-07-01-preview"; + _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); + } + + internal RequestUriBuilder CreateExportTerraformRequestUri(string subscriptionId, CommonExportProperties body) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/providers/Microsoft.AzureTerraform/exportTerraform", false); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateExportTerraformRequest(string subscriptionId, CommonExportProperties body) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/providers/Microsoft.AzureTerraform/exportTerraform", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(body, ModelSerializationExtensions.WireOptions); + request.Content = content; + _userAgent.Apply(message); + return message; + } + + /// Exports the Terraform configuration of the specified resource(s). + /// The ID of the target subscription. The value must be an UUID. + /// The request body. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public async Task ExportTerraformAsync(string subscriptionId, CommonExportProperties body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNull(body, nameof(body)); + + using var message = CreateExportTerraformRequest(subscriptionId, body); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 202: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + /// Exports the Terraform configuration of the specified resource(s). + /// The ID of the target subscription. The value must be an UUID. + /// The request body. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public Response ExportTerraform(string subscriptionId, CommonExportProperties body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNull(body, nameof(body)); + + using var message = CreateExportTerraformRequest(subscriptionId, body); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 202: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/src/Properties/AssemblyInfo.cs b/sdk/terraform/Azure.ResourceManager.Terraform/src/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000..359c558d61b95 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/src/Properties/AssemblyInfo.cs @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: Azure.Core.AzureResourceProviderNamespace("Microsoft.AzureTerraform")] + +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] +[assembly: InternalsVisibleTo("Azure.ResourceManager.Terraform.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/tests/Azure.ResourceManager.Terraform.Tests.csproj b/sdk/terraform/Azure.ResourceManager.Terraform/tests/Azure.ResourceManager.Terraform.Tests.csproj new file mode 100644 index 0000000000000..76dcb524d7731 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/tests/Azure.ResourceManager.Terraform.Tests.csproj @@ -0,0 +1,5 @@ + + + + + diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/tests/ExportTerraformTests.cs b/sdk/terraform/Azure.ResourceManager.Terraform/tests/ExportTerraformTests.cs new file mode 100644 index 0000000000000..f86e7e6a5f08d --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/tests/ExportTerraformTests.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Threading.Tasks; +using Azure.Core.TestFramework; +using Azure.ResourceManager.Terraform.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.Terraform.Tests +{ + public class ExportTerraformTests : TerraformManagementTestBase + { + public ExportTerraformTests(bool isAsync) : base(isAsync) + { + } + + [TestCase] + [RecordedTest] + public async Task ExportResourceGroupTest() + { + string resourceGroupName = TestEnvironment.ResourceGroup; + string vnetName = TestEnvironment.VNetName; + ExportResourceGroupTerraform exportResourceGroup = new(resourceGroupName); + + ArmOperation operationStatus = await DefaultSubscription.ExportTerraformAsync(WaitUntil.Completed, exportResourceGroup); + string hcl = operationStatus.Value.Properties.Configuration; + + Assert.That(hcl, Does.Contain("azurerm_resource_group")); + Assert.That(hcl, Does.Contain(resourceGroupName)); + + Assert.That(hcl, Does.Contain("azurerm_virtual_network")); + Assert.That(hcl, Does.Contain(vnetName)); + } + + [TestCase] + [RecordedTest] + public async Task ExportQueryTest() + { + string resourceGroupName = TestEnvironment.ResourceGroup; + string vnetName = TestEnvironment.VNetName; + ExportQueryTerraform exportQuery = new($"resourceGroup =~ \"{resourceGroupName}\""); + + ArmOperation operationStatus = await DefaultSubscription.ExportTerraformAsync(WaitUntil.Completed, exportQuery); + string hcl = operationStatus.Value.Properties.Configuration; + + Assert.That(hcl, Does.Contain("azurerm_virtual_network")); + Assert.That(hcl, Does.Contain(vnetName)); + } + + [TestCase] + [RecordedTest] + public async Task ExportResourceTest() + { + string vnetName = TestEnvironment.VNetName; + ExportResourceTerraform exportResource = new(new[] { TestEnvironment.VNetId }); + + ArmOperation operationStatus = await DefaultSubscription.ExportTerraformAsync(WaitUntil.Completed, exportResource); + + string hcl = operationStatus.Value.Properties.Configuration; + + Assert.That(hcl, Does.Contain("azurerm_virtual_network")); + Assert.That(hcl, Does.Contain(vnetName)); + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/tests/InheritanceCheckTests.cs b/sdk/terraform/Azure.ResourceManager.Terraform/tests/InheritanceCheckTests.cs new file mode 100644 index 0000000000000..51ecf6d1dc7e0 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/tests/InheritanceCheckTests.cs @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Azure.ResourceManager.TestFramework +{ + public partial class InheritanceCheckTests + { + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/tests/TerraformManagementTestBase.cs b/sdk/terraform/Azure.ResourceManager.Terraform/tests/TerraformManagementTestBase.cs new file mode 100644 index 0000000000000..db6f28c657627 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/tests/TerraformManagementTestBase.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core; +using Azure.Core.TestFramework; +using Azure.ResourceManager.Resources; +using Azure.ResourceManager.TestFramework; +using NUnit.Framework; +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Terraform.Tests +{ + public class TerraformManagementTestBase : ManagementRecordedTestBase + { + protected ArmClient Client { get; private set; } + protected SubscriptionResource DefaultSubscription { get; private set; } + protected ResourceGroupCollection ResourceGroupCollection { get; private set; } + + protected TerraformManagementTestBase(bool isAsync, RecordedTestMode mode) + : base(isAsync, mode) + { + } + + protected TerraformManagementTestBase(bool isAsync) + : base(isAsync) + { + } + + [SetUp] + public async Task CreateCommonClient() + { + Client = GetArmClient(); + DefaultSubscription = await Client.GetDefaultSubscriptionAsync().ConfigureAwait(false); + ResourceGroupCollection = DefaultSubscription.GetResourceGroups(); + } + + protected async Task CreateResourceGroup(SubscriptionResource subscription, string rgNamePrefix, AzureLocation location) + { + string rgName = Recording.GenerateAssetName(rgNamePrefix); + ResourceGroupData input = new ResourceGroupData(location); + ArmOperation lro = await subscription.GetResourceGroups().CreateOrUpdateAsync(WaitUntil.Completed, rgName, input); + return lro.Value; + } + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/tests/TerraformManagementTestEnvironment.cs b/sdk/terraform/Azure.ResourceManager.Terraform/tests/TerraformManagementTestEnvironment.cs new file mode 100644 index 0000000000000..97a16cba6aec6 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/tests/TerraformManagementTestEnvironment.cs @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core; +using Azure.Core.TestFramework; + +namespace Azure.ResourceManager.Terraform.Tests +{ + public class TerraformManagementTestEnvironment : TestEnvironment + { + public string VNetName => GetRecordedVariable("VNET_NAME"); + public ResourceIdentifier VNetId => new(GetRecordedVariable("VNET_ID")); + } +} diff --git a/sdk/terraform/Azure.ResourceManager.Terraform/tsp-location.yaml b/sdk/terraform/Azure.ResourceManager.Terraform/tsp-location.yaml new file mode 100644 index 0000000000000..d676e0dde7f99 --- /dev/null +++ b/sdk/terraform/Azure.ResourceManager.Terraform/tsp-location.yaml @@ -0,0 +1,3 @@ +directory: specification/terraform/Microsoft.AzureTerraform.Management +commit: a4fc4c6bda9ff2315671bca69f9de40a43e2bd8c +repo: Azure/azure-rest-api-specs diff --git a/sdk/terraform/ci.mgmt.yml b/sdk/terraform/ci.mgmt.yml new file mode 100644 index 0000000000000..82c4c1f05a4c5 --- /dev/null +++ b/sdk/terraform/ci.mgmt.yml @@ -0,0 +1,23 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: none +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/terraform/ci.mgmt.yml + - sdk/terraform/Azure.ResourceManager.Terraform/ + +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: terraform + LimitForPullRequest: true + Artifacts: + - name: Azure.ResourceManager.Terraform + safeName: AzureResourceManagerTerraform diff --git a/sdk/terraform/test-resources.json b/sdk/terraform/test-resources.json new file mode 100644 index 0000000000000..535ef0d042842 --- /dev/null +++ b/sdk/terraform/test-resources.json @@ -0,0 +1,47 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "location": { + "type": "string", + "defaultValue": "[resourceGroup().location]", + "metadata": { + "description": "The location of the resource. By default, this is the same as the resource group." + } + } + }, + "variables": { + "vnetName": "dotnet-sdk-test-vnet" + }, + "resources": [ + { + "type": "Microsoft.Network/virtualNetworks", + "apiVersion": "2024-01-01", + "name": "[variables('vnetName')]", + "location": "[parameters('location')]", + "properties": { + "addressSpace": { + "addressPrefixes": ["10.0.0.0/16"] + }, + "subnets": [ + { + "name": "default", + "properties": { + "addressPrefix": "10.0.0.0/24" + } + } + ] + } + } + ], + "outputs": { + "VNET_NAME": { + "type": "string", + "value": "[variables('vnetName')]" + }, + "VNET_ID": { + "type": "string", + "value": "[resourceId('Microsoft.Network/virtualNetworks', variables('vnetName'))]" + } + } +}