Skip to content

Add Export-AzureRmResourceGroup cmdlet #1983

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Mar 24, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions setup/azurecmdfiles.wxi

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@
<Compile Include="Entities\Policy\PolicyRule.cs" />
<Compile Include="Entities\Providers\ResourceProviderDefinition.cs" />
<Compile Include="Entities\Providers\ResourceTypeDefinition.cs" />
<Compile Include="Entities\ResourceGroup\ExportTemplateParameters.cs" />
<Compile Include="Entities\ResourceGroup\ResourceBatchMoveParameters.cs" />
<Compile Include="Entities\Resources\Resource.cs" />
<Compile Include="Entities\Resources\ResourcePlan.cs" />
Expand All @@ -136,6 +137,7 @@
<Compile Include="Handlers\CmdletInfoHandler.cs" />
<Compile Include="Handlers\UserAgentHandler.cs" />
<Compile Include="Implementation\FindAzureResourceGroupCmdlet.cs" />
<Compile Include="Implementation\ExportAzureResourceGroupCmdlet.cs" />
<Compile Include="Implementation\SaveAzureResourceGroupDeploymentTemplateCmdlet.cs" />
<Compile Include="Implementation\GetAzureResourceGroupDeploymentOperationCmdlet.cs" />
<Compile Include="Implementation\Lock\GetAzureResourceLockCmdlet.cs" />
Expand Down Expand Up @@ -191,6 +193,14 @@
<Link>AzureRM.Resources.psd1</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<Content Include="Microsoft.Azure.Commands.ResourceManager.Cmdlets.format.ps1xml">
<SubType>Designer</SubType>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Microsoft.Azure.Commands.ResourceManager.Cmdlets.Types.ps1xml">
<SubType>Designer</SubType>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<None Include="MSSharedLibKey.snk" />
<None Include="packages.config">
<SubType>Designer</SubType>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.ResourceGroups
{
using Newtonsoft.Json;

/// <summary>
/// The export template request definition object.
/// </summary>
public class ExportTemplateParameters
{
/// <summary>
/// Gets or sets the target resource group.
/// </summary>
[JsonProperty(Required = Required.Default)]
public string Options { get; set; }

/// <summary>
/// Gets or sets the list of resources in the resource group.
/// </summary>
[JsonProperty(Required = Required.Always)]
public string[] Resources { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
{
using System.Management.Automation;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.ErrorResponses;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.ResourceGroups;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Utilities;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Newtonsoft.Json.Linq;

/// <summary>
/// Captures the specifies resource group as a template and saves it to a file on disk.
/// </summary>
[Cmdlet(VerbsData.Export, "AzureRmResourceGroup"), OutputType(typeof(PSObject))]
public class ExportAzureResourceGroupCmdlet : ResourceManagerCmdletBase
{
/// <summary>
/// Gets or sets the resource group name parameter.
/// </summary>
[Alias("ResourceGroup")]
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }

/// <summary>
/// Gets or sets the file path.
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The output path of the template file.")]
[ValidateNotNullOrEmpty]
public string Path { get; set; }

/// <summary>
/// Export template parameter with default value.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "Export template parameter with default value.")]
public SwitchParameter IncludeParameterDefaultValue { get; set; }

/// <summary>
/// Export template with comments.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "Export template with comments.")]
public SwitchParameter IncludeComments { get; set; }

/// <summary>
/// Gets or sets the force parameter.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")]
public SwitchParameter Force { get; set; }

/// <summary>
/// Executes the cmdlet.
/// </summary>
protected override void OnProcessRecord()
{
base.OnProcessRecord();

var resourceId = this.GetResourceId();

var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result;

var parameters = new ExportTemplateParameters
{
Resources = new string [] {"*"},
Options = this.GetExportOptions() ?? null
};

var operationResult = this.GetResourcesClient()
.InvokeActionOnResource<JObject>(
resourceId: resourceId,
action: Constants.ExportTemplate,
parameters: parameters.ToJToken(),
apiVersion: apiVersion,
cancellationToken: this.CancellationToken.Value)
.Result;

var managementUri = this.GetResourcesClient()
.GetResourceManagementRequestUri(
resourceId: resourceId,
apiVersion: apiVersion,
action: Constants.ExportTemplate);

var activity = string.Format("POST {0}", managementUri.PathAndQuery);
var resultString = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false)
.WaitOnOperation(operationResult: operationResult);

var template = JToken.FromObject(JObject.Parse(resultString)["template"]);

if(JObject.Parse(resultString)["error"] != null)
{
ExtendedErrorInfo error;
if(JObject.Parse(resultString)["error"].TryConvertTo(out error))
{
WriteWarning(string.Format("{0} : {1}", error.Code, error.Message));
foreach(var detail in error.Details)
{
WriteWarning(string.Format("{0} : {1}", detail.Code, detail.Message));
}
}
}

string path = FileUtility.SaveTemplateFile(
templateName: this.ResourceGroupName,
contents: template.ToString(),
outputPath: string.IsNullOrEmpty(this.Path) ? System.IO.Path.Combine(CurrentPath(), this.ResourceGroupName) : this.TryResolvePath(this.Path),
overwrite: this.Force,
confirmAction: ConfirmAction);

WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", path));
}

/// <summary>
/// Gets the export template options
/// </summary>
private string GetExportOptions()
{
string options = string.Empty;
if(this.IncludeComments.IsPresent)
{
options += "IncludeComments";
}
if(this.IncludeParameterDefaultValue.IsPresent)
{
options = string.IsNullOrEmpty(options) ? "IncludeParameterDefaultValue" : options + ",IncludeParameterDefaultValue";
}
return string.IsNullOrEmpty(options) ? null : options;
}

/// <summary>
/// Gets the resource Id from the supplied PowerShell parameters.
/// </summary>
protected string GetResourceId()
{
return ResourceIdUtility.GetResourceId(
subscriptionId: DefaultContext.Subscription.Id,
resourceGroupName: this.ResourceGroupName,
resourceType: null,
resourceName: null);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ private void RunCmdlet()
getFirstPage: () => this.GetResources(),
getNextPage: nextLink => this.GetNextLink<JObject>(nextLink),
cancellationToken: this.CancellationToken,
action: resources => this.WriteObject(sendToPipeline: resources.CoalesceEnumerable().SelectArray(resource => resource.ToPsObject()), enumerateCollection: true));
action: resources => this.WriteObject(sendToPipeline: resources.CoalesceEnumerable().SelectArray(resource => resource.ToPsObject("System.Management.Automation.PSCustomObject#DeploymentOperation")), enumerateCollection: true));
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,15 @@ private async Task<ResponseWithContinuation<JObject[]>> GetResources()
{
string resourceId = this.Id ?? this.GetResourceId();

var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.PolicyApiVersion : this.ApiVersion;

if (IsResourceGet(resourceId))
{
var resource = await this
.GetResourcesClient()
.GetResource<JObject>(
resourceId: resourceId,
apiVersion: Constants.PolicyApiVersion,
apiVersion: apiVersion,
cancellationToken: this.CancellationToken.Value,
odataQuery: null)
.ConfigureAwait(continueOnCapturedContext: false);
Expand All @@ -122,7 +124,7 @@ private async Task<ResponseWithContinuation<JObject[]>> GetResources()
.GetResourcesClient()
.ListObjectColleciton<JObject>(
resourceCollectionId: resourceId,
apiVersion: Constants.PolicyApiVersion,
apiVersion: apiVersion,
cancellationToken: this.CancellationToken.Value,
odataQuery: filter)
.ConfigureAwait(continueOnCapturedContext: false);
Expand All @@ -137,7 +139,7 @@ private async Task<ResponseWithContinuation<JObject[]>> GetResources()
.GetResourcesClient()
.ListObjectColleciton<JObject>(
resourceCollectionId: resourceId,
apiVersion: Constants.PolicyApiVersion,
apiVersion: apiVersion,
cancellationToken: this.CancellationToken.Value,
odataQuery: filter)
.ConfigureAwait(continueOnCapturedContext: false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,15 @@ private async Task<ResponseWithContinuation<JObject[]>> GetResources()
{
string resourceId = this.Id ?? this.GetResourceId();

var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.PolicyApiVersion : this.ApiVersion;

if (!string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId)))
{
var resource = await this
.GetResourcesClient()
.GetResource<JObject>(
resourceId: resourceId,
apiVersion: Constants.PolicyApiVersion,
apiVersion: apiVersion,
cancellationToken: this.CancellationToken.Value)
.ConfigureAwait(continueOnCapturedContext: false);
ResponseWithContinuation<JObject[]> retVal;
Expand All @@ -105,7 +107,7 @@ private async Task<ResponseWithContinuation<JObject[]>> GetResources()
.GetResourcesClient()
.ListObjectColleciton<JObject>(
resourceCollectionId: resourceId,
apiVersion: Constants.PolicyApiVersion,
apiVersion: apiVersion,
cancellationToken: this.CancellationToken.Value)
.ConfigureAwait(continueOnCapturedContext: false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,13 @@ protected override void OnProcessRecord()
throw new PSInvalidOperationException("The supplied PolicyDefinition object is invalid.");
}
string resourceId = GetResourceId();

var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.PolicyApiVersion : this.ApiVersion;

var operationResult = this.GetResourcesClient()
.PutResource(
resourceId: resourceId,
apiVersion: Constants.PolicyApiVersion,
apiVersion: apiVersion,
resource: this.GetResource(),
cancellationToken: this.CancellationToken.Value,
odataQuery: null)
Expand All @@ -81,7 +83,7 @@ protected override void OnProcessRecord()
var managementUri = this.GetResourcesClient()
.GetResourceManagementRequestUri(
resourceId: resourceId,
apiVersion: Constants.PolicyApiVersion,
apiVersion: apiVersion,
odataQuery: null);

var activity = string.Format("PUT {0}", managementUri.PathAndQuery);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,13 @@ protected override void OnProcessRecord()
{
base.OnProcessRecord();
string resourceId = GetResourceId();


var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.PolicyApiVersion : this.ApiVersion;

var operationResult = this.GetResourcesClient()
.PutResource(
resourceId: resourceId,
apiVersion: Constants.PolicyApiVersion,
apiVersion: apiVersion,
resource: this.GetResource(),
cancellationToken: this.CancellationToken.Value,
odataQuery: null)
Expand All @@ -79,7 +81,7 @@ protected override void OnProcessRecord()
var managementUri = this.GetResourcesClient()
.GetResourceManagementRequestUri(
resourceId: resourceId,
apiVersion: Constants.PolicyApiVersion,
apiVersion: apiVersion,
odataQuery: null);

var activity = string.Format("PUT {0}", managementUri.PathAndQuery);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ private void RunCmdlet()
{
base.OnProcessRecord();
string resourceId = this.Id ?? this.GetResourceId();
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.PolicyApiVersion : this.ApiVersion;

this.ConfirmAction(
this.Force,
string.Format("Are you sure you want to delete the following policy assignment: {0}", resourceId),
Expand All @@ -88,15 +90,15 @@ private void RunCmdlet()
var operationResult = this.GetResourcesClient()
.DeleteResource(
resourceId: resourceId,
apiVersion: Constants.PolicyApiVersion,
apiVersion: apiVersion,
cancellationToken: this.CancellationToken.Value,
odataQuery: null)
.Result;

var managementUri = this.GetResourcesClient()
.GetResourceManagementRequestUri(
resourceId: resourceId,
apiVersion: Constants.PolicyApiVersion,
apiVersion: apiVersion,
odataQuery: null);

var activity = string.Format("DELETE {0}", managementUri.PathAndQuery);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ private void RunCmdlet()
{
base.OnProcessRecord();
string resourceId = this.Id ?? this.GetResourceId();
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.PolicyApiVersion : this.ApiVersion;

this.ConfirmAction(
this.Force,
string.Format("Are you sure you want to delete the following policy definition: {0}", resourceId),
Expand All @@ -81,15 +83,15 @@ private void RunCmdlet()
var operationResult = this.GetResourcesClient()
.DeleteResource(
resourceId: resourceId,
apiVersion: Constants.PolicyApiVersion,
apiVersion: apiVersion,
cancellationToken: this.CancellationToken.Value,
odataQuery: null)
.Result;

var managementUri = this.GetResourcesClient()
.GetResourceManagementRequestUri(
resourceId: resourceId,
apiVersion: Constants.PolicyApiVersion,
apiVersion: apiVersion,
odataQuery: null);

var activity = string.Format("DELETE {0}", managementUri.PathAndQuery);
Expand Down
Loading