From e43a1f0c7514e5a962d9d5f1064051c02851372e Mon Sep 17 00:00:00 2001 From: vivsriaus Date: Wed, 16 Sep 2015 14:37:31 -0700 Subject: [PATCH 1/4] Add policy assignment cmdlets --- .../Commands.ResourceManager.Cmdlets.csproj | 12 +- .../Cmdlets/Components/Constants.cs | 5 + .../{PolicyRule.cs => PolicyAssignment.cs} | 10 +- .../Policy/PolicyAssignmentProperties.cs | 42 +++++ .../Policy/PolicyDefinitionProperties.cs | 2 +- .../Policy/GetAzurePolicyAssignment.cs | 176 ++++++++++++++++++ .../Policy/GetAzurePolicyDefinition.cs | 2 +- .../Policy/NewAzurePolicyAssignment.cs | 120 ++++++++++++ .../Policy/NewAzurePolicyDefinition.cs | 13 +- .../Policy/PolicyAssignmentCmdletBase.cs | 58 ++++++ .../Policy/RemoveAzurePolicyAssignment.cs | 124 ++++++++++++ .../Policy/SetAzurePolicyAssignment.cs | 146 +++++++++++++++ .../Policy/SetAzurePolicyDefinition.cs | 24 +-- 13 files changed, 701 insertions(+), 33 deletions(-) rename src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/{PolicyRule.cs => PolicyAssignment.cs} (80%) create mode 100644 src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignmentProperties.cs create mode 100644 src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyAssignment.cs create mode 100644 src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyAssignment.cs create mode 100644 src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/PolicyAssignmentCmdletBase.cs create mode 100644 src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/RemoveAzurePolicyAssignment.cs create mode 100644 src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Commands.ResourceManager.Cmdlets.csproj b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Commands.ResourceManager.Cmdlets.csproj index 15846f735b2c..f1025203891e 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Commands.ResourceManager.Cmdlets.csproj +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Commands.ResourceManager.Cmdlets.csproj @@ -111,9 +111,10 @@ - + + - + @@ -139,10 +140,15 @@ + + - + + + + diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Components/Constants.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Components/Constants.cs index d8bab349daf0..50a78a6f44f4 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Components/Constants.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Components/Constants.cs @@ -74,6 +74,11 @@ public static class Constants /// public static readonly string MicrosoftAuthorizationPolicyDefinitionType = Constants.MicrosoftAuthorizationNamespace + "/policydefinitions"; + /// + /// The policy assignment resource type. + /// + public static readonly string MicrosoftAuthorizationPolicyAssignmentType = Constants.MicrosoftAuthorizationNamespace + "/policyassignments"; + /// /// The type name of the generic resource. /// diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyRule.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignment.cs similarity index 80% rename from src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyRule.cs rename to src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignment.cs index 49856c90125b..b53354f2e47e 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyRule.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignment.cs @@ -17,14 +17,14 @@ namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy using Newtonsoft.Json; /// - /// The policy rule object. + /// The policy assignment object. /// - public class PolicyRule + public class PolicyAssignment { /// - /// The policy rule + /// The policy assignment properties. /// - [JsonProperty(Required = Required.Always)] - public string Rule { get; set; } + [JsonProperty(Required = Required.Default)] + public PolicyAssignmentProperties Properties { get; set; } } } diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignmentProperties.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignmentProperties.cs new file mode 100644 index 000000000000..70c0706862ce --- /dev/null +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignmentProperties.cs @@ -0,0 +1,42 @@ +// ---------------------------------------------------------------------------------- +// +// 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.Policy +{ + using Newtonsoft.Json; + + /// + /// The policy assignment properties. + /// + public class PolicyAssignmentProperties + { + /// + /// The scope. + /// + [JsonProperty(Required = Required.Always)] + public string Scope { get; set; } + + /// + /// The display name. + /// + [JsonProperty(Required = Required.Default)] + public string DisplayName { get; set; } + + /// + /// The policy definition id. + /// + [JsonProperty(Required = Required.Always)] + public string PolicyDefinitionId { get; set; } + } +} diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinitionProperties.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinitionProperties.cs index 833ac0c622f6..3a1e2fd3fe7b 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinitionProperties.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinitionProperties.cs @@ -37,6 +37,6 @@ public class PolicyDefinitionProperties /// The policy rule. /// [JsonProperty(Required = Required.Always)] - public PolicyRule PolicyRule { get; set; } + public string PolicyRule { get; set; } } } diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyAssignment.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyAssignment.cs new file mode 100644 index 000000000000..817c3023eb37 --- /dev/null +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyAssignment.cs @@ -0,0 +1,176 @@ +// ---------------------------------------------------------------------------------- +// +// 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 System.Threading.Tasks; + using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components; + using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions; + using Newtonsoft.Json.Linq; + + /// + /// Gets the policy assignment. + /// + [Cmdlet(VerbsCommon.Get, "AzureRMPolicyAssignment", DefaultParameterSetName = GetAzurePolicyAssignmentCmdlet.ParameterlessSet), OutputType(typeof(PSObject))] + public class GetAzurePolicyAssignmentCmdlet : PolicyAssignmentCmdletBase + { + /// + /// The policy Id parameter set. + /// + internal const string PolicyAssignmentIdParameterSet = "The policy assignment Id parameter set."; + + /// + /// The policy name parameter set. + /// + internal const string PolicyAssignmentNameParameterSet = "The policy assignment name parameter set."; + + /// + /// The list all policy parameter set. + /// + internal const string ParameterlessSet = "The list all policy assignments parameter set."; + + /// + /// Gets or sets the policy assignment name parameter. + /// + [Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] + [ValidateNotNullOrEmpty] + public string Name { get; set; } + + /// + /// Gets or sets the policy assignment scope parameter. + /// + [Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] + [ValidateNotNullOrEmpty] + public string Scope { get; set; } + + /// + /// Gets or sets the policy assignment id parameter + /// + [Alias("ResourceId")] + [Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")] + [ValidateNotNullOrEmpty] + public string Id { get; set; } + + /// + /// Gets or sets the policy assignment policy definition id parameter + /// + [Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentIdParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")] + [Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")] + [ValidateNotNullOrEmpty] + public string PolicyDefinitionId { get; set; } + + /// + /// Executes the cmdlet. + /// + protected override void OnProcessRecord() + { + base.OnProcessRecord(); + + this.RunCmdlet(); + } + + /// + /// Contains the cmdlet's execution logic. + /// + private void RunCmdlet() + { + PaginatedResponseHelper.ForEach( + getFirstPage: () => this.GetResources(), + getNextPage: nextLink => this.GetNextLink(nextLink), + cancellationToken: this.CancellationToken, + action: resources => this.WriteObject(sendToPipeline: this.GetOutputObjects(resources), enumerateCollection: true)); + } + + /// + /// Queries the ARM cache and returns the cached resource that match the query specified. + /// + private async Task> GetResources() + { + string resourceId = this.Id ?? this.GetResourceId(); + + var apiVersion = await this + .DetermineApiVersion(resourceId: resourceId) + .ConfigureAwait(continueOnCapturedContext: false); + + if (!string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.Scope)) + { + var resource = await this + .GetResourcesClient() + .GetResource( + resourceId: resourceId, + apiVersion: apiVersion, + cancellationToken: this.CancellationToken.Value, + odataQuery: null) + .ConfigureAwait(continueOnCapturedContext: false); + ResponseWithContinuation retVal; + return resource.TryConvertTo(out retVal) && retVal.Value != null + ? retVal + : new ResponseWithContinuation { Value = resource.AsArray() }; + } + else if(!string.IsNullOrEmpty(this.Scope) && string.IsNullOrEmpty(this.Name))//If only scope is given, list assignments call + { + string filter = "$filter=atScope()"; + return await this + .GetResourcesClient() + .ListObjectColleciton( + resourceCollectionId: resourceId, + apiVersion: apiVersion, + cancellationToken: this.CancellationToken.Value, + odataQuery: filter) + .ConfigureAwait(continueOnCapturedContext: false); + } + else + { + string filter = string.IsNullOrEmpty(this.PolicyDefinitionId) + ? null + : string.Format("$filter=policydefinitionid eq '{0}'", this.PolicyDefinitionId); + + return await this + .GetResourcesClient() + .ListObjectColleciton( + resourceCollectionId: resourceId, + apiVersion: apiVersion, + cancellationToken: this.CancellationToken.Value, + odataQuery: filter) + .ConfigureAwait(continueOnCapturedContext: false); + } + } + + /// + /// Gets the resource Id + /// + private string GetResourceId() + { + var subscriptionId = DefaultContext.Subscription.Id; + if(string.IsNullOrEmpty(this.Name) && string.IsNullOrEmpty(this.Scope)) + { + return string.Format("/subscriptions/{0}/providers/{1}", + subscriptionId.ToString(), + Constants.MicrosoftAuthorizationPolicyAssignmentType); + } + else if(string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.Scope)) + { + return ResourceIdUtility.GetResourceId( + resourceId: this.Scope, + extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType, + extensionResourceName: null); + } + return ResourceIdUtility.GetResourceId( + resourceId: this.Scope, + extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType, + extensionResourceName: this.Name); + } + } +} diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyDefinition.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyDefinition.cs index 70f819d1b07d..1707fa322816 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyDefinition.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyDefinition.cs @@ -89,7 +89,7 @@ private async Task> GetResources() .DetermineApiVersion(resourceId: resourceId) .ConfigureAwait(continueOnCapturedContext: false); - if (!string.IsNullOrEmpty(ResourceIdUtility.GetResourceGroupName(resourceId))) + if (!string.IsNullOrEmpty(this.Name)) { var resource = await this .GetResourcesClient() diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyAssignment.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyAssignment.cs new file mode 100644 index 000000000000..385b5eed70c9 --- /dev/null +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyAssignment.cs @@ -0,0 +1,120 @@ +// ---------------------------------------------------------------------------------- +// +// 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.IO; + using System.Management.Automation; + using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components; + using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy; + using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources; + using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions; + using Microsoft.Azure.Common.Authentication; + using Microsoft.WindowsAzure.Commands.Utilities.Common; + using Newtonsoft.Json.Linq; + + /// + /// Creates a policy assignment. + /// + [Cmdlet(VerbsCommon.New, "AzureRMPolicyAssignment"), OutputType(typeof(PSObject))] + public class NewAzurePolicyAssignmentCmdlet : PolicyAssignmentCmdletBase + { + /// + /// Gets or sets the policy assignment name parameter. + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] + [ValidateNotNullOrEmpty] + public string Name { get; set; } + + /// + /// Gets or sets the policy assignment scope parameter + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The scope for policy assignment.")] + [ValidateNotNullOrEmpty] + public string Scope { get; set; } + + /// + /// Gets or sets the policy assignment display name parameter + /// + [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The description for policy assignment.")] + [ValidateNotNullOrEmpty] + public string DisplayName { get; set; } + + /// + /// Gets or sets the policy assignment policy definition parameter. + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The pollicy definition object.")] + public PSObject PolicyDefinition { get; set; } + + /// + /// Executes the cmdlet. + /// + protected override void OnProcessRecord() + { + base.OnProcessRecord(); + string resourceId = GetResourceId(); + var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result; + + var operationResult = this.GetResourcesClient() + .PutResource( + resourceId: resourceId, + apiVersion: apiVersion, + resource: this.GetResource(), + cancellationToken: this.CancellationToken.Value, + odataQuery: null) + .Result; + + var managementUri = this.GetResourcesClient() + .GetResourceManagementRequestUri( + resourceId: resourceId, + apiVersion: apiVersion, + odataQuery: null); + + var activity = string.Format("PUT {0}", managementUri.PathAndQuery); + var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true) + .WaitOnOperation(operationResult: operationResult); + + this.WriteObject(this.GetOutputObjects(result.ToJToken()), enumerateCollection: true); + } + + /// + /// Gets the resource Id + /// + private string GetResourceId() + { + return ResourceIdUtility.GetResourceId( + resourceId: this.Scope, + extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType, + extensionResourceName: this.Name); + } + + /// + /// Constructs the resource + /// + private JToken GetResource() + { + var policyassignmentObject = new PolicyAssignment + { + Properties = new PolicyAssignmentProperties + { + DisplayName = this.DisplayName ?? null, + PolicyDefinitionId = this.PolicyDefinition.Properties["PolicyDefinitionId"].Value.ToString(), + Scope = this.Scope + } + }; + + return policyassignmentObject.ToJToken(); + } + } +} diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyDefinition.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyDefinition.cs index ffc9b743e821..8fa17f2ecf18 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyDefinition.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyDefinition.cs @@ -52,11 +52,11 @@ public class NewAzurePolicyDefinitionCmdlet : PolicyDefinitionCmdletBase public string Description { get; set; } /// - /// Gets or sets the policy rule parameter + /// Gets or sets the policy parameter /// [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The rule for policy definition. This can either be a path to a file name containing the rule, or the rule as string.")] [ValidateNotNullOrEmpty] - public string PolicyRule { get; set; } + public string Policy { get; set; } /// /// Executes the cmdlet. @@ -112,12 +112,9 @@ private JToken GetResource() { Description = this.Description ?? null, DisplayName = this.DisplayName ?? null, - PolicyRule = new PolicyRule - { - Rule = File.Exists(this.PolicyRule) - ? FileUtilities.DataStore.ReadFileAsText(this.TryResolvePath(this.PolicyRule)) - : this.PolicyRule - } + PolicyRule = File.Exists(this.Policy) + ? FileUtilities.DataStore.ReadFileAsText(this.TryResolvePath(this.Policy)) + : this.Policy } }; diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/PolicyAssignmentCmdletBase.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/PolicyAssignmentCmdletBase.cs new file mode 100644 index 000000000000..daf0c8232874 --- /dev/null +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/PolicyAssignmentCmdletBase.cs @@ -0,0 +1,58 @@ +// ---------------------------------------------------------------------------------- +// +// 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.Linq; + using System.Management.Automation; + using System.Threading.Tasks; + using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components; + using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources; + using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions; + using Newtonsoft.Json.Linq; + + /// + /// Base class for policy assignment cmdlets. + /// + public abstract class PolicyAssignmentCmdletBase : ResourceManagerCmdletBase + { + /// + /// Gets the next set of resources using the + /// + /// The next link. + protected Task> GetNextLink(string nextLink) + { + return this + .GetResourcesClient() + .ListNextBatch(nextLink: nextLink, cancellationToken: this.CancellationToken.Value); + } + + /// + /// Converts the resource object to policy definition object. + /// + /// The policy definition resource object. + protected PSObject[] GetOutputObjects(params JToken[] resources) + { + return resources + .CoalesceEnumerable() + .Where(resource => resource != null) + .SelectArray(resource => + { + var psobject = resource.ToResource().ToPsObject(ResourceObjectFormat.New); + psobject.Properties.Add(new PSNoteProperty("PolicyAssignmentId", psobject.Properties["ResourceId"].Value)); + return psobject; + }); + } + } +} \ No newline at end of file diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/RemoveAzurePolicyAssignment.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/RemoveAzurePolicyAssignment.cs new file mode 100644 index 000000000000..cef17e8edcd8 --- /dev/null +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/RemoveAzurePolicyAssignment.cs @@ -0,0 +1,124 @@ +// ---------------------------------------------------------------------------------- +// +// 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; + + /// + /// Removes the policy assignment. + /// + [Cmdlet(VerbsCommon.Remove, "AzureRMPolicyAssignment", DefaultParameterSetName = RemoveAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet), OutputType(typeof(bool))] + public class RemoveAzurePolicyAssignmentCmdlet : PolicyAssignmentCmdletBase + { + /// + /// The policy assignment Id parameter set. + /// + internal const string PolicyAssignmentIdParameterSet = "The policy assignment Id parameter set."; + + /// + /// The policy assignment name parameter set. + /// + internal const string PolicyAssignmentNameParameterSet = "The policy assignment name parameter set."; + + /// + /// Gets or sets the policy assignment name parameter. + /// + [Parameter(ParameterSetName = RemoveAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] + [ValidateNotNullOrEmpty] + public string Name { get; set; } + + /// + /// Gets or sets the policy assignment scope parameter. + /// + [Parameter(ParameterSetName = RemoveAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] + [ValidateNotNullOrEmpty] + public string Scope { get; set; } + + /// + /// Gets or sets the policy assignment id parameter + /// + [Alias("ResourceId")] + [Parameter(ParameterSetName = RemoveAzurePolicyAssignmentCmdlet.PolicyAssignmentIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")] + [ValidateNotNullOrEmpty] + public string Id { get; set; } + + /// + /// Gets or sets the force parameter. + /// + [Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")] + public SwitchParameter Force { get; set; } + + /// + /// Executes the cmdlet. + /// + protected override void OnProcessRecord() + { + base.OnProcessRecord(); + + this.RunCmdlet(); + } + + /// + /// Contains the cmdlet's execution logic. + /// + private void RunCmdlet() + { + base.OnProcessRecord(); + string resourceId = this.Id ?? this.GetResourceId(); + this.ConfirmAction( + this.Force, + string.Format("Are you sure you want to delete the following policy assignment: {0}", resourceId), + "Deleting the policy assignment...", + resourceId, + () => + { + var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result; + + var operationResult = this.GetResourcesClient() + .DeleteResource( + resourceId: resourceId, + apiVersion: apiVersion, + cancellationToken: this.CancellationToken.Value, + odataQuery: null) + .Result; + + var managementUri = this.GetResourcesClient() + .GetResourceManagementRequestUri( + resourceId: resourceId, + apiVersion: apiVersion, + odataQuery: null); + + var activity = string.Format("DELETE {0}", managementUri.PathAndQuery); + + this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false) + .WaitOnOperation(operationResult: operationResult); + + this.WriteObject(true); + }); + } + + /// + /// Gets the resource Id from the supplied PowerShell parameters. + /// + protected string GetResourceId() + { + return ResourceIdUtility.GetResourceId( + resourceId: this.Scope, + extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType, + extensionResourceName: this.Name); + } + } +} diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs new file mode 100644 index 000000000000..da15b07d6bae --- /dev/null +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs @@ -0,0 +1,146 @@ +// ---------------------------------------------------------------------------------- +// +// 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.IO; + using System.Management.Automation; + using System.Threading.Tasks; + using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components; + using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy; + using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions; + using Microsoft.Azure.Common.Authentication; + using Microsoft.WindowsAzure.Commands.Utilities.Common; + using Newtonsoft.Json.Linq; + + /// + /// Sets the policy assignment. + /// + [Cmdlet(VerbsCommon.Set, "AzureRMPolicyAssignment", DefaultParameterSetName = SetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet), OutputType(typeof(PSObject))] + public class SetAzurePolicyAssignmentCmdlet : PolicyAssignmentCmdletBase + { + /// + /// The policy Id parameter set. + /// + internal const string PolicyAssignmentIdParameterSet = "The policy assignment Id parameter set."; + + /// + /// The policy name parameter set. + /// + internal const string PolicyAssignmentNameParameterSet = "The policy assignment name parameter set."; + + /// + /// Gets or sets the policy assignment name parameter. + /// + [Parameter(ParameterSetName = SetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] + [ValidateNotNullOrEmpty] + public string Name { get; set; } + + /// + /// Gets or sets the policy assignment scope parameter. + /// + [Parameter(ParameterSetName = SetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] + [ValidateNotNullOrEmpty] + public string Scope { get; set; } + + /// + /// Gets or sets the policy assignment id parameter + /// + [Alias("ResourceId")] + [Parameter(ParameterSetName = SetAzurePolicyAssignmentCmdlet.PolicyAssignmentIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")] + [ValidateNotNullOrEmpty] + public string Id { get; set; } + + /// + /// Gets or sets the policy assignment display name parameter + /// + [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The display name for policy assignment.")] + [ValidateNotNullOrEmpty] + public string DisplayName { get; set; } + + /// + /// Executes the cmdlet. + /// + protected override void OnProcessRecord() + { + base.OnProcessRecord(); + string resourceId = this.Id ?? this.GetResourceId(); + var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result; + + var operationResult = this.GetResourcesClient() + .PutResource( + resourceId: resourceId, + apiVersion: apiVersion, + resource: this.GetResource(resourceId, apiVersion), + cancellationToken: this.CancellationToken.Value, + odataQuery: null) + .Result; + + var managementUri = this.GetResourcesClient() + .GetResourceManagementRequestUri( + resourceId: resourceId, + apiVersion: apiVersion, + odataQuery: null); + + var activity = string.Format("PUT {0}", managementUri.PathAndQuery); + var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true) + .WaitOnOperation(operationResult: operationResult); + + this.WriteObject(this.GetOutputObjects(result.ToJToken()), enumerateCollection: true); + } + + /// + /// Constructs the resource + /// + private JToken GetResource(string resourceId, string apiVersion) + { + var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource(); + + var policyAssignmentObject = new PolicyAssignment + { + Properties = new PolicyAssignmentProperties + { + DisplayName = this.DisplayName ?? resource.Properties["DisplayName"].ToString(), + } + }; + + return policyAssignmentObject.ToJToken(); + } + + /// + /// Gets a resource. + /// + private async Task GetExistingResource(string resourceId, string apiVersion) + { + return await this + .GetResourcesClient() + .GetResource( + resourceId: resourceId, + apiVersion: apiVersion, + cancellationToken: this.CancellationToken.Value) + .ConfigureAwait(continueOnCapturedContext: false); + } + + /// + /// Gets the resource Id from the supplied PowerShell parameters. + /// + protected string GetResourceId() + { + return ResourceIdUtility.GetResourceId( + resourceId: this.Scope, + extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType, + extensionResourceName: this.Name); + } + } +} diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyDefinition.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyDefinition.cs index 66a8d0e9948b..9c773e1cd26f 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyDefinition.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyDefinition.cs @@ -74,7 +74,7 @@ public class SetAzurePolicyDefinitionCmdlet : PolicyDefinitionCmdletBase /// [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The rule for policy definition. This can either be a path to a file name containing the rule, or the rule as string.")] [ValidateNotNullOrEmpty] - public string PolicyRule { get; set; } + public string Policy { get; set; } /// /// Executes the cmdlet. @@ -113,30 +113,24 @@ protected override void OnProcessRecord() private JToken GetResource(string resourceId, string apiVersion) { var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource(); - var policyProperties = JsonUtilities.DeserializeJson(resource.Properties.ToString()); + var policyDefinitionObject = new PolicyDefinition { Properties = new PolicyDefinitionProperties { - Description = this.Description ?? policyProperties["Description"].ToString(), - DisplayName = this.DisplayName ?? policyProperties["DisplayName"].ToString(), - PolicyRule = new PolicyRule - { - Rule = File.Exists(this.PolicyRule) - ? FileUtilities.DataStore.ReadFileAsText(this.TryResolvePath(this.PolicyRule)) - : this.PolicyRule - } + Description = this.Description ?? resource.Properties["Description"].ToString(), + DisplayName = this.DisplayName ?? resource.Properties["DisplayName"].ToString(), } }; - if(!string.IsNullOrEmpty(this.PolicyRule)) + if(!string.IsNullOrEmpty(this.Policy)) { - policyDefinitionObject.Properties.PolicyRule.Rule = File.Exists(this.PolicyRule) - ? FileUtilities.DataStore.ReadFileAsText(this.TryResolvePath(this.PolicyRule)) - : this.PolicyRule; + policyDefinitionObject.Properties.PolicyRule = File.Exists(this.Policy) + ? FileUtilities.DataStore.ReadFileAsText(this.TryResolvePath(this.Policy)) + : this.Policy; } else { - policyDefinitionObject.Properties.PolicyRule.Rule = (policyProperties["PolicyRule"] as PolicyRule).Rule; + policyDefinitionObject.Properties.PolicyRule = resource.Properties["PolicyRule"].ToString(); } return policyDefinitionObject.ToJToken(); From 4951d0cd8e877bd675d633206f8dc007875f1c70 Mon Sep 17 00:00:00 2001 From: vivsriaus Date: Thu, 17 Sep 2015 16:18:41 -0700 Subject: [PATCH 2/4] Fix bugs --- .../Entities/Policy/PolicyAssignment.cs | 6 +++++ .../Entities/Policy/PolicyDefinition.cs | 6 +++++ .../Policy/GetAzurePolicyAssignment.cs | 23 +++++++++++++++++-- .../Policy/GetAzurePolicyDefinition.cs | 2 +- .../Policy/NewAzurePolicyAssignment.cs | 9 ++++++-- .../Policy/NewAzurePolicyDefinition.cs | 4 ++-- .../Policy/SetAzurePolicyAssignment.cs | 7 ++++-- .../Policy/SetAzurePolicyDefinition.cs | 13 +++++++---- 8 files changed, 57 insertions(+), 13 deletions(-) diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignment.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignment.cs index b53354f2e47e..40549f31d07c 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignment.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignment.cs @@ -26,5 +26,11 @@ public class PolicyAssignment /// [JsonProperty(Required = Required.Default)] public PolicyAssignmentProperties Properties { get; set; } + + /// + /// The policy assignment name. + /// + [JsonProperty(Required = Required.Default)] + public string Name { get; set; } } } diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinition.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinition.cs index a911eaba94e4..33f0d39624ad 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinition.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinition.cs @@ -26,5 +26,11 @@ public class PolicyDefinition /// [JsonProperty(Required = Required.Default)] public PolicyDefinitionProperties Properties { get; set; } + + /// + /// The policy definition name. + /// + [JsonProperty(Required = Required.Default)] + public string Name { get; set; } } } diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyAssignment.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyAssignment.cs index 817c3023eb37..e98f1bc1865b 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyAssignment.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyAssignment.cs @@ -104,7 +104,7 @@ private async Task> GetResources() .DetermineApiVersion(resourceId: resourceId) .ConfigureAwait(continueOnCapturedContext: false); - if (!string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.Scope)) + if (IsResourceGet(resourceId)) { var resource = await this .GetResourcesClient() @@ -119,7 +119,7 @@ private async Task> GetResources() ? retVal : new ResponseWithContinuation { Value = resource.AsArray() }; } - else if(!string.IsNullOrEmpty(this.Scope) && string.IsNullOrEmpty(this.Name))//If only scope is given, list assignments call + else if (IsScopeLevelList(resourceId))//If only scope is given, list assignments call { string filter = "$filter=atScope()"; return await this @@ -148,6 +148,25 @@ private async Task> GetResources() } } + /// + /// Returns true if it is scope level policy assignment list call + /// + private bool IsScopeLevelList(string resourceId) + { + return (!string.IsNullOrEmpty(this.Scope) && string.IsNullOrEmpty(this.Name)) + || (!string.IsNullOrEmpty(this.Scope) && string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId))); + } + + /// + /// Returns true if it is a single policy assignment get + /// + /// + private bool IsResourceGet(string resourceId) + { + return (!string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.Scope)) + || !string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId)); + } + /// /// Gets the resource Id /// diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyDefinition.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyDefinition.cs index 1707fa322816..1a9cc3f0fa6b 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyDefinition.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyDefinition.cs @@ -89,7 +89,7 @@ private async Task> GetResources() .DetermineApiVersion(resourceId: resourceId) .ConfigureAwait(continueOnCapturedContext: false); - if (!string.IsNullOrEmpty(this.Name)) + if (!string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId))) { var resource = await this .GetResourcesClient() diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyAssignment.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyAssignment.cs index 385b5eed70c9..d05ebf39f9b0 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyAssignment.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyAssignment.cs @@ -63,6 +63,10 @@ public class NewAzurePolicyAssignmentCmdlet : PolicyAssignmentCmdletBase protected override void OnProcessRecord() { base.OnProcessRecord(); + if(this.PolicyDefinition.Properties["policyDefinitionId"] == null) + { + throw new PSInvalidOperationException("The supplied PolicyDefinition object is invalid."); + } string resourceId = GetResourceId(); var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result; @@ -85,7 +89,7 @@ protected override void OnProcessRecord() var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true) .WaitOnOperation(operationResult: operationResult); - this.WriteObject(this.GetOutputObjects(result.ToJToken()), enumerateCollection: true); + this.WriteObject(this.GetOutputObjects(JObject.Parse(result)), enumerateCollection: true); } /// @@ -106,10 +110,11 @@ private JToken GetResource() { var policyassignmentObject = new PolicyAssignment { + Name = this.Name, Properties = new PolicyAssignmentProperties { DisplayName = this.DisplayName ?? null, - PolicyDefinitionId = this.PolicyDefinition.Properties["PolicyDefinitionId"].Value.ToString(), + PolicyDefinitionId = this.PolicyDefinition.Properties["policyDefinitionId"].Value.ToString(), Scope = this.Scope } }; diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyDefinition.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyDefinition.cs index 8fa17f2ecf18..c6c70f1819d0 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyDefinition.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyDefinition.cs @@ -85,8 +85,7 @@ protected override void OnProcessRecord() var activity = string.Format("PUT {0}", managementUri.PathAndQuery); var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true) .WaitOnOperation(operationResult: operationResult); - - this.WriteObject(this.GetOutputObjects(result.ToJToken()), enumerateCollection: true); + this.WriteObject(this.GetOutputObjects(JObject.Parse(result)), enumerateCollection: true); } /// @@ -108,6 +107,7 @@ private JToken GetResource() { var policyDefinitionObject = new PolicyDefinition { + Name = this.Name, Properties = new PolicyDefinitionProperties { Description = this.Description ?? null, diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs index da15b07d6bae..c45486c157c9 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs @@ -97,7 +97,7 @@ protected override void OnProcessRecord() var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true) .WaitOnOperation(operationResult: operationResult); - this.WriteObject(this.GetOutputObjects(result.ToJToken()), enumerateCollection: true); + this.WriteObject(this.GetOutputObjects(JObject.Parse(result)), enumerateCollection: true); } /// @@ -109,9 +109,12 @@ private JToken GetResource(string resourceId, string apiVersion) var policyAssignmentObject = new PolicyAssignment { + Name = this.Name ?? ResourceIdUtility.GetResourceName(this.Id), Properties = new PolicyAssignmentProperties { - DisplayName = this.DisplayName ?? resource.Properties["DisplayName"].ToString(), + DisplayName = this.DisplayName ?? (resource.Properties["displayName"] != null + ? resource.Properties["displayName"].ToString() + : null) } }; diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyDefinition.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyDefinition.cs index 9c773e1cd26f..d4c7663e3433 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyDefinition.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyDefinition.cs @@ -104,7 +104,7 @@ protected override void OnProcessRecord() var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true) .WaitOnOperation(operationResult: operationResult); - this.WriteObject(this.GetOutputObjects(result.ToJToken()), enumerateCollection: true); + this.WriteObject(this.GetOutputObjects(JObject.Parse(result)), enumerateCollection: true); } /// @@ -116,10 +116,15 @@ private JToken GetResource(string resourceId, string apiVersion) var policyDefinitionObject = new PolicyDefinition { + Name = this.Name ?? ResourceIdUtility.GetResourceName(this.Id), Properties = new PolicyDefinitionProperties { - Description = this.Description ?? resource.Properties["Description"].ToString(), - DisplayName = this.DisplayName ?? resource.Properties["DisplayName"].ToString(), + Description = this.Description ?? (resource.Properties["description"] != null + ? resource.Properties["description"].ToString() + : null), + DisplayName = this.DisplayName ?? (resource.Properties["displayName"] != null + ? resource.Properties["displayName"].ToString() + : null) } }; if(!string.IsNullOrEmpty(this.Policy)) @@ -130,7 +135,7 @@ private JToken GetResource(string resourceId, string apiVersion) } else { - policyDefinitionObject.Properties.PolicyRule = resource.Properties["PolicyRule"].ToString(); + policyDefinitionObject.Properties.PolicyRule = resource.Properties["policyRule"].ToString(); } return policyDefinitionObject.ToJToken(); From 358dadbf6f62032114b0314f2b615f11755a816d Mon Sep 17 00:00:00 2001 From: vivsriaus Date: Fri, 18 Sep 2015 10:08:59 -0700 Subject: [PATCH 3/4] Fix set-azurermpolicyassignment --- .../Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs index c45486c157c9..67480edc5923 100644 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs +++ b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs @@ -114,7 +114,9 @@ private JToken GetResource(string resourceId, string apiVersion) { DisplayName = this.DisplayName ?? (resource.Properties["displayName"] != null ? resource.Properties["displayName"].ToString() - : null) + : null), + Scope = resource.Properties["scope"].ToString(), + PolicyDefinitionId = resource.Properties["policyDefinitionId"].ToString() } }; From 3c19c295ba7415593a29864f02ce11644bcbd88f Mon Sep 17 00:00:00 2001 From: stankovski Date: Wed, 30 Sep 2015 09:53:29 -0700 Subject: [PATCH 4/4] Revert of change SHA-1: beef46eec21f8a583fe05ec5ccb940a1158cbb9b --- .../Policy/PolicyAssignmentProperties.cs | 42 ---- .../Policy/GetAzurePolicyAssignment.cs | 195 ------------------ .../Policy/NewAzurePolicyAssignment.cs | 125 ----------- .../Policy/PolicyAssignmentCmdletBase.cs | 58 ------ .../Policy/RemoveAzurePolicyAssignment.cs | 124 ----------- .../Policy/SetAzurePolicyAssignment.cs | 151 -------------- .../Cmdlets/Commands.Resources.Rest.csproj | 12 +- .../Cmdlets/Components/Constants.cs | 5 - .../Entities/Policy/PolicyDefinition.cs | 6 - .../Policy/PolicyDefinitionProperties.cs | 2 +- .../Policy/GetAzurePolicyDefinition.cs | 2 +- .../Policy/NewAzurePolicyDefinition.cs | 17 +- .../Policy/SetAzurePolicyDefinition.cs | 31 +-- 13 files changed, 31 insertions(+), 739 deletions(-) delete mode 100644 src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignmentProperties.cs delete mode 100644 src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyAssignment.cs delete mode 100644 src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyAssignment.cs delete mode 100644 src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/PolicyAssignmentCmdletBase.cs delete mode 100644 src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/RemoveAzurePolicyAssignment.cs delete mode 100644 src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignmentProperties.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignmentProperties.cs deleted file mode 100644 index 70c0706862ce..000000000000 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyAssignmentProperties.cs +++ /dev/null @@ -1,42 +0,0 @@ -// ---------------------------------------------------------------------------------- -// -// 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.Policy -{ - using Newtonsoft.Json; - - /// - /// The policy assignment properties. - /// - public class PolicyAssignmentProperties - { - /// - /// The scope. - /// - [JsonProperty(Required = Required.Always)] - public string Scope { get; set; } - - /// - /// The display name. - /// - [JsonProperty(Required = Required.Default)] - public string DisplayName { get; set; } - - /// - /// The policy definition id. - /// - [JsonProperty(Required = Required.Always)] - public string PolicyDefinitionId { get; set; } - } -} diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyAssignment.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyAssignment.cs deleted file mode 100644 index e98f1bc1865b..000000000000 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyAssignment.cs +++ /dev/null @@ -1,195 +0,0 @@ -// ---------------------------------------------------------------------------------- -// -// 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 System.Threading.Tasks; - using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components; - using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions; - using Newtonsoft.Json.Linq; - - /// - /// Gets the policy assignment. - /// - [Cmdlet(VerbsCommon.Get, "AzureRMPolicyAssignment", DefaultParameterSetName = GetAzurePolicyAssignmentCmdlet.ParameterlessSet), OutputType(typeof(PSObject))] - public class GetAzurePolicyAssignmentCmdlet : PolicyAssignmentCmdletBase - { - /// - /// The policy Id parameter set. - /// - internal const string PolicyAssignmentIdParameterSet = "The policy assignment Id parameter set."; - - /// - /// The policy name parameter set. - /// - internal const string PolicyAssignmentNameParameterSet = "The policy assignment name parameter set."; - - /// - /// The list all policy parameter set. - /// - internal const string ParameterlessSet = "The list all policy assignments parameter set."; - - /// - /// Gets or sets the policy assignment name parameter. - /// - [Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] - [ValidateNotNullOrEmpty] - public string Name { get; set; } - - /// - /// Gets or sets the policy assignment scope parameter. - /// - [Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] - [ValidateNotNullOrEmpty] - public string Scope { get; set; } - - /// - /// Gets or sets the policy assignment id parameter - /// - [Alias("ResourceId")] - [Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")] - [ValidateNotNullOrEmpty] - public string Id { get; set; } - - /// - /// Gets or sets the policy assignment policy definition id parameter - /// - [Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentIdParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")] - [Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")] - [ValidateNotNullOrEmpty] - public string PolicyDefinitionId { get; set; } - - /// - /// Executes the cmdlet. - /// - protected override void OnProcessRecord() - { - base.OnProcessRecord(); - - this.RunCmdlet(); - } - - /// - /// Contains the cmdlet's execution logic. - /// - private void RunCmdlet() - { - PaginatedResponseHelper.ForEach( - getFirstPage: () => this.GetResources(), - getNextPage: nextLink => this.GetNextLink(nextLink), - cancellationToken: this.CancellationToken, - action: resources => this.WriteObject(sendToPipeline: this.GetOutputObjects(resources), enumerateCollection: true)); - } - - /// - /// Queries the ARM cache and returns the cached resource that match the query specified. - /// - private async Task> GetResources() - { - string resourceId = this.Id ?? this.GetResourceId(); - - var apiVersion = await this - .DetermineApiVersion(resourceId: resourceId) - .ConfigureAwait(continueOnCapturedContext: false); - - if (IsResourceGet(resourceId)) - { - var resource = await this - .GetResourcesClient() - .GetResource( - resourceId: resourceId, - apiVersion: apiVersion, - cancellationToken: this.CancellationToken.Value, - odataQuery: null) - .ConfigureAwait(continueOnCapturedContext: false); - ResponseWithContinuation retVal; - return resource.TryConvertTo(out retVal) && retVal.Value != null - ? retVal - : new ResponseWithContinuation { Value = resource.AsArray() }; - } - else if (IsScopeLevelList(resourceId))//If only scope is given, list assignments call - { - string filter = "$filter=atScope()"; - return await this - .GetResourcesClient() - .ListObjectColleciton( - resourceCollectionId: resourceId, - apiVersion: apiVersion, - cancellationToken: this.CancellationToken.Value, - odataQuery: filter) - .ConfigureAwait(continueOnCapturedContext: false); - } - else - { - string filter = string.IsNullOrEmpty(this.PolicyDefinitionId) - ? null - : string.Format("$filter=policydefinitionid eq '{0}'", this.PolicyDefinitionId); - - return await this - .GetResourcesClient() - .ListObjectColleciton( - resourceCollectionId: resourceId, - apiVersion: apiVersion, - cancellationToken: this.CancellationToken.Value, - odataQuery: filter) - .ConfigureAwait(continueOnCapturedContext: false); - } - } - - /// - /// Returns true if it is scope level policy assignment list call - /// - private bool IsScopeLevelList(string resourceId) - { - return (!string.IsNullOrEmpty(this.Scope) && string.IsNullOrEmpty(this.Name)) - || (!string.IsNullOrEmpty(this.Scope) && string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId))); - } - - /// - /// Returns true if it is a single policy assignment get - /// - /// - private bool IsResourceGet(string resourceId) - { - return (!string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.Scope)) - || !string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId)); - } - - /// - /// Gets the resource Id - /// - private string GetResourceId() - { - var subscriptionId = DefaultContext.Subscription.Id; - if(string.IsNullOrEmpty(this.Name) && string.IsNullOrEmpty(this.Scope)) - { - return string.Format("/subscriptions/{0}/providers/{1}", - subscriptionId.ToString(), - Constants.MicrosoftAuthorizationPolicyAssignmentType); - } - else if(string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.Scope)) - { - return ResourceIdUtility.GetResourceId( - resourceId: this.Scope, - extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType, - extensionResourceName: null); - } - return ResourceIdUtility.GetResourceId( - resourceId: this.Scope, - extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType, - extensionResourceName: this.Name); - } - } -} diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyAssignment.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyAssignment.cs deleted file mode 100644 index d05ebf39f9b0..000000000000 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyAssignment.cs +++ /dev/null @@ -1,125 +0,0 @@ -// ---------------------------------------------------------------------------------- -// -// 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.IO; - using System.Management.Automation; - using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components; - using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy; - using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources; - using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions; - using Microsoft.Azure.Common.Authentication; - using Microsoft.WindowsAzure.Commands.Utilities.Common; - using Newtonsoft.Json.Linq; - - /// - /// Creates a policy assignment. - /// - [Cmdlet(VerbsCommon.New, "AzureRMPolicyAssignment"), OutputType(typeof(PSObject))] - public class NewAzurePolicyAssignmentCmdlet : PolicyAssignmentCmdletBase - { - /// - /// Gets or sets the policy assignment name parameter. - /// - [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] - [ValidateNotNullOrEmpty] - public string Name { get; set; } - - /// - /// Gets or sets the policy assignment scope parameter - /// - [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The scope for policy assignment.")] - [ValidateNotNullOrEmpty] - public string Scope { get; set; } - - /// - /// Gets or sets the policy assignment display name parameter - /// - [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The description for policy assignment.")] - [ValidateNotNullOrEmpty] - public string DisplayName { get; set; } - - /// - /// Gets or sets the policy assignment policy definition parameter. - /// - [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The pollicy definition object.")] - public PSObject PolicyDefinition { get; set; } - - /// - /// Executes the cmdlet. - /// - protected override void OnProcessRecord() - { - base.OnProcessRecord(); - if(this.PolicyDefinition.Properties["policyDefinitionId"] == null) - { - throw new PSInvalidOperationException("The supplied PolicyDefinition object is invalid."); - } - string resourceId = GetResourceId(); - var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result; - - var operationResult = this.GetResourcesClient() - .PutResource( - resourceId: resourceId, - apiVersion: apiVersion, - resource: this.GetResource(), - cancellationToken: this.CancellationToken.Value, - odataQuery: null) - .Result; - - var managementUri = this.GetResourcesClient() - .GetResourceManagementRequestUri( - resourceId: resourceId, - apiVersion: apiVersion, - odataQuery: null); - - var activity = string.Format("PUT {0}", managementUri.PathAndQuery); - var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true) - .WaitOnOperation(operationResult: operationResult); - - this.WriteObject(this.GetOutputObjects(JObject.Parse(result)), enumerateCollection: true); - } - - /// - /// Gets the resource Id - /// - private string GetResourceId() - { - return ResourceIdUtility.GetResourceId( - resourceId: this.Scope, - extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType, - extensionResourceName: this.Name); - } - - /// - /// Constructs the resource - /// - private JToken GetResource() - { - var policyassignmentObject = new PolicyAssignment - { - Name = this.Name, - Properties = new PolicyAssignmentProperties - { - DisplayName = this.DisplayName ?? null, - PolicyDefinitionId = this.PolicyDefinition.Properties["policyDefinitionId"].Value.ToString(), - Scope = this.Scope - } - }; - - return policyassignmentObject.ToJToken(); - } - } -} diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/PolicyAssignmentCmdletBase.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/PolicyAssignmentCmdletBase.cs deleted file mode 100644 index daf0c8232874..000000000000 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/PolicyAssignmentCmdletBase.cs +++ /dev/null @@ -1,58 +0,0 @@ -// ---------------------------------------------------------------------------------- -// -// 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.Linq; - using System.Management.Automation; - using System.Threading.Tasks; - using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components; - using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources; - using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions; - using Newtonsoft.Json.Linq; - - /// - /// Base class for policy assignment cmdlets. - /// - public abstract class PolicyAssignmentCmdletBase : ResourceManagerCmdletBase - { - /// - /// Gets the next set of resources using the - /// - /// The next link. - protected Task> GetNextLink(string nextLink) - { - return this - .GetResourcesClient() - .ListNextBatch(nextLink: nextLink, cancellationToken: this.CancellationToken.Value); - } - - /// - /// Converts the resource object to policy definition object. - /// - /// The policy definition resource object. - protected PSObject[] GetOutputObjects(params JToken[] resources) - { - return resources - .CoalesceEnumerable() - .Where(resource => resource != null) - .SelectArray(resource => - { - var psobject = resource.ToResource().ToPsObject(ResourceObjectFormat.New); - psobject.Properties.Add(new PSNoteProperty("PolicyAssignmentId", psobject.Properties["ResourceId"].Value)); - return psobject; - }); - } - } -} \ No newline at end of file diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/RemoveAzurePolicyAssignment.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/RemoveAzurePolicyAssignment.cs deleted file mode 100644 index cef17e8edcd8..000000000000 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/RemoveAzurePolicyAssignment.cs +++ /dev/null @@ -1,124 +0,0 @@ -// ---------------------------------------------------------------------------------- -// -// 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; - - /// - /// Removes the policy assignment. - /// - [Cmdlet(VerbsCommon.Remove, "AzureRMPolicyAssignment", DefaultParameterSetName = RemoveAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet), OutputType(typeof(bool))] - public class RemoveAzurePolicyAssignmentCmdlet : PolicyAssignmentCmdletBase - { - /// - /// The policy assignment Id parameter set. - /// - internal const string PolicyAssignmentIdParameterSet = "The policy assignment Id parameter set."; - - /// - /// The policy assignment name parameter set. - /// - internal const string PolicyAssignmentNameParameterSet = "The policy assignment name parameter set."; - - /// - /// Gets or sets the policy assignment name parameter. - /// - [Parameter(ParameterSetName = RemoveAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] - [ValidateNotNullOrEmpty] - public string Name { get; set; } - - /// - /// Gets or sets the policy assignment scope parameter. - /// - [Parameter(ParameterSetName = RemoveAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] - [ValidateNotNullOrEmpty] - public string Scope { get; set; } - - /// - /// Gets or sets the policy assignment id parameter - /// - [Alias("ResourceId")] - [Parameter(ParameterSetName = RemoveAzurePolicyAssignmentCmdlet.PolicyAssignmentIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")] - [ValidateNotNullOrEmpty] - public string Id { get; set; } - - /// - /// Gets or sets the force parameter. - /// - [Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")] - public SwitchParameter Force { get; set; } - - /// - /// Executes the cmdlet. - /// - protected override void OnProcessRecord() - { - base.OnProcessRecord(); - - this.RunCmdlet(); - } - - /// - /// Contains the cmdlet's execution logic. - /// - private void RunCmdlet() - { - base.OnProcessRecord(); - string resourceId = this.Id ?? this.GetResourceId(); - this.ConfirmAction( - this.Force, - string.Format("Are you sure you want to delete the following policy assignment: {0}", resourceId), - "Deleting the policy assignment...", - resourceId, - () => - { - var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result; - - var operationResult = this.GetResourcesClient() - .DeleteResource( - resourceId: resourceId, - apiVersion: apiVersion, - cancellationToken: this.CancellationToken.Value, - odataQuery: null) - .Result; - - var managementUri = this.GetResourcesClient() - .GetResourceManagementRequestUri( - resourceId: resourceId, - apiVersion: apiVersion, - odataQuery: null); - - var activity = string.Format("DELETE {0}", managementUri.PathAndQuery); - - this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false) - .WaitOnOperation(operationResult: operationResult); - - this.WriteObject(true); - }); - } - - /// - /// Gets the resource Id from the supplied PowerShell parameters. - /// - protected string GetResourceId() - { - return ResourceIdUtility.GetResourceId( - resourceId: this.Scope, - extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType, - extensionResourceName: this.Name); - } - } -} diff --git a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs b/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs deleted file mode 100644 index 67480edc5923..000000000000 --- a/src/ResourceManager/ResourceManager/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyAssignment.cs +++ /dev/null @@ -1,151 +0,0 @@ -// ---------------------------------------------------------------------------------- -// -// 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.IO; - using System.Management.Automation; - using System.Threading.Tasks; - using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components; - using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy; - using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions; - using Microsoft.Azure.Common.Authentication; - using Microsoft.WindowsAzure.Commands.Utilities.Common; - using Newtonsoft.Json.Linq; - - /// - /// Sets the policy assignment. - /// - [Cmdlet(VerbsCommon.Set, "AzureRMPolicyAssignment", DefaultParameterSetName = SetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet), OutputType(typeof(PSObject))] - public class SetAzurePolicyAssignmentCmdlet : PolicyAssignmentCmdletBase - { - /// - /// The policy Id parameter set. - /// - internal const string PolicyAssignmentIdParameterSet = "The policy assignment Id parameter set."; - - /// - /// The policy name parameter set. - /// - internal const string PolicyAssignmentNameParameterSet = "The policy assignment name parameter set."; - - /// - /// Gets or sets the policy assignment name parameter. - /// - [Parameter(ParameterSetName = SetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] - [ValidateNotNullOrEmpty] - public string Name { get; set; } - - /// - /// Gets or sets the policy assignment scope parameter. - /// - [Parameter(ParameterSetName = SetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")] - [ValidateNotNullOrEmpty] - public string Scope { get; set; } - - /// - /// Gets or sets the policy assignment id parameter - /// - [Alias("ResourceId")] - [Parameter(ParameterSetName = SetAzurePolicyAssignmentCmdlet.PolicyAssignmentIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")] - [ValidateNotNullOrEmpty] - public string Id { get; set; } - - /// - /// Gets or sets the policy assignment display name parameter - /// - [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The display name for policy assignment.")] - [ValidateNotNullOrEmpty] - public string DisplayName { get; set; } - - /// - /// Executes the cmdlet. - /// - protected override void OnProcessRecord() - { - base.OnProcessRecord(); - string resourceId = this.Id ?? this.GetResourceId(); - var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result; - - var operationResult = this.GetResourcesClient() - .PutResource( - resourceId: resourceId, - apiVersion: apiVersion, - resource: this.GetResource(resourceId, apiVersion), - cancellationToken: this.CancellationToken.Value, - odataQuery: null) - .Result; - - var managementUri = this.GetResourcesClient() - .GetResourceManagementRequestUri( - resourceId: resourceId, - apiVersion: apiVersion, - odataQuery: null); - - var activity = string.Format("PUT {0}", managementUri.PathAndQuery); - var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true) - .WaitOnOperation(operationResult: operationResult); - - this.WriteObject(this.GetOutputObjects(JObject.Parse(result)), enumerateCollection: true); - } - - /// - /// Constructs the resource - /// - private JToken GetResource(string resourceId, string apiVersion) - { - var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource(); - - var policyAssignmentObject = new PolicyAssignment - { - Name = this.Name ?? ResourceIdUtility.GetResourceName(this.Id), - Properties = new PolicyAssignmentProperties - { - DisplayName = this.DisplayName ?? (resource.Properties["displayName"] != null - ? resource.Properties["displayName"].ToString() - : null), - Scope = resource.Properties["scope"].ToString(), - PolicyDefinitionId = resource.Properties["policyDefinitionId"].ToString() - } - }; - - return policyAssignmentObject.ToJToken(); - } - - /// - /// Gets a resource. - /// - private async Task GetExistingResource(string resourceId, string apiVersion) - { - return await this - .GetResourcesClient() - .GetResource( - resourceId: resourceId, - apiVersion: apiVersion, - cancellationToken: this.CancellationToken.Value) - .ConfigureAwait(continueOnCapturedContext: false); - } - - /// - /// Gets the resource Id from the supplied PowerShell parameters. - /// - protected string GetResourceId() - { - return ResourceIdUtility.GetResourceId( - resourceId: this.Scope, - extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType, - extensionResourceName: this.Name); - } - } -} diff --git a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Commands.Resources.Rest.csproj b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Commands.Resources.Rest.csproj index 7e3f5f2d945d..5b002cf6738b 100644 --- a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Commands.Resources.Rest.csproj +++ b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Commands.Resources.Rest.csproj @@ -111,10 +111,9 @@ - - - + + @@ -141,15 +140,10 @@ - - - - - - + diff --git a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Components/Constants.cs b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Components/Constants.cs index 50a78a6f44f4..d8bab349daf0 100644 --- a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Components/Constants.cs +++ b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Components/Constants.cs @@ -74,11 +74,6 @@ public static class Constants /// public static readonly string MicrosoftAuthorizationPolicyDefinitionType = Constants.MicrosoftAuthorizationNamespace + "/policydefinitions"; - /// - /// The policy assignment resource type. - /// - public static readonly string MicrosoftAuthorizationPolicyAssignmentType = Constants.MicrosoftAuthorizationNamespace + "/policyassignments"; - /// /// The type name of the generic resource. /// diff --git a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinition.cs b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinition.cs index 33f0d39624ad..a911eaba94e4 100644 --- a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinition.cs +++ b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinition.cs @@ -26,11 +26,5 @@ public class PolicyDefinition /// [JsonProperty(Required = Required.Default)] public PolicyDefinitionProperties Properties { get; set; } - - /// - /// The policy definition name. - /// - [JsonProperty(Required = Required.Default)] - public string Name { get; set; } } } diff --git a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinitionProperties.cs b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinitionProperties.cs index 3a1e2fd3fe7b..833ac0c622f6 100644 --- a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinitionProperties.cs +++ b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Entities/Policy/PolicyDefinitionProperties.cs @@ -37,6 +37,6 @@ public class PolicyDefinitionProperties /// The policy rule. /// [JsonProperty(Required = Required.Always)] - public string PolicyRule { get; set; } + public PolicyRule PolicyRule { get; set; } } } diff --git a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyDefinition.cs b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyDefinition.cs index b9e286285e6d..a861805494d0 100644 --- a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyDefinition.cs +++ b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/Policy/GetAzurePolicyDefinition.cs @@ -89,7 +89,7 @@ private async Task> GetResources() .DetermineApiVersion(resourceId: resourceId) .ConfigureAwait(continueOnCapturedContext: false); - if (!string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId))) + if (!string.IsNullOrEmpty(ResourceIdUtility.GetResourceGroupName(resourceId))) { var resource = await this .GetResourcesClient() diff --git a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyDefinition.cs b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyDefinition.cs index 99e2eba91695..63cd2a756c49 100644 --- a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyDefinition.cs +++ b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/Policy/NewAzurePolicyDefinition.cs @@ -52,11 +52,11 @@ public class NewAzurePolicyDefinitionCmdlet : PolicyDefinitionCmdletBase public string Description { get; set; } /// - /// Gets or sets the policy parameter + /// Gets or sets the policy rule parameter /// [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The rule for policy definition. This can either be a path to a file name containing the rule, or the rule as string.")] [ValidateNotNullOrEmpty] - public string Policy { get; set; } + public string PolicyRule { get; set; } /// /// Executes the cmdlet. @@ -85,7 +85,8 @@ protected override void OnProcessRecord() var activity = string.Format("PUT {0}", managementUri.PathAndQuery); var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true) .WaitOnOperation(operationResult: operationResult); - this.WriteObject(this.GetOutputObjects(JObject.Parse(result)), enumerateCollection: true); + + this.WriteObject(this.GetOutputObjects(result.ToJToken()), enumerateCollection: true); } /// @@ -107,14 +108,16 @@ private JToken GetResource() { var policyDefinitionObject = new PolicyDefinition { - Name = this.Name, Properties = new PolicyDefinitionProperties { Description = this.Description ?? null, DisplayName = this.DisplayName ?? null, - PolicyRule = File.Exists(this.Policy) - ? FileUtilities.DataStore.ReadFileAsText(this.TryResolvePath(this.Policy)) - : this.Policy + PolicyRule = new PolicyRule + { + Rule = File.Exists(this.PolicyRule) + ? FileUtilities.DataStore.ReadFileAsText(this.TryResolvePath(this.PolicyRule)) + : this.PolicyRule + } } }; diff --git a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyDefinition.cs b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyDefinition.cs index 113782132b45..911f3d21eb7f 100644 --- a/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyDefinition.cs +++ b/src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/Policy/SetAzurePolicyDefinition.cs @@ -74,7 +74,7 @@ public class SetAzurePolicyDefinitionCmdlet : PolicyDefinitionCmdletBase /// [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The rule for policy definition. This can either be a path to a file name containing the rule, or the rule as string.")] [ValidateNotNullOrEmpty] - public string Policy { get; set; } + public string PolicyRule { get; set; } /// /// Executes the cmdlet. @@ -104,7 +104,7 @@ protected override void OnProcessRecord() var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true) .WaitOnOperation(operationResult: operationResult); - this.WriteObject(this.GetOutputObjects(JObject.Parse(result)), enumerateCollection: true); + this.WriteObject(this.GetOutputObjects(result.ToJToken()), enumerateCollection: true); } /// @@ -113,29 +113,30 @@ protected override void OnProcessRecord() private JToken GetResource(string resourceId, string apiVersion) { var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource(); - + var policyProperties = JsonUtilities.DeserializeJson(resource.Properties.ToString()); var policyDefinitionObject = new PolicyDefinition { - Name = this.Name ?? ResourceIdUtility.GetResourceName(this.Id), Properties = new PolicyDefinitionProperties { - Description = this.Description ?? (resource.Properties["description"] != null - ? resource.Properties["description"].ToString() - : null), - DisplayName = this.DisplayName ?? (resource.Properties["displayName"] != null - ? resource.Properties["displayName"].ToString() - : null) + Description = this.Description ?? policyProperties["Description"].ToString(), + DisplayName = this.DisplayName ?? policyProperties["DisplayName"].ToString(), + PolicyRule = new PolicyRule + { + Rule = File.Exists(this.PolicyRule) + ? FileUtilities.DataStore.ReadFileAsText(this.TryResolvePath(this.PolicyRule)) + : this.PolicyRule + } } }; - if(!string.IsNullOrEmpty(this.Policy)) + if(!string.IsNullOrEmpty(this.PolicyRule)) { - policyDefinitionObject.Properties.PolicyRule = File.Exists(this.Policy) - ? FileUtilities.DataStore.ReadFileAsText(this.TryResolvePath(this.Policy)) - : this.Policy; + policyDefinitionObject.Properties.PolicyRule.Rule = File.Exists(this.PolicyRule) + ? FileUtilities.DataStore.ReadFileAsText(this.TryResolvePath(this.PolicyRule)) + : this.PolicyRule; } else { - policyDefinitionObject.Properties.PolicyRule = resource.Properties["policyRule"].ToString(); + policyDefinitionObject.Properties.PolicyRule.Rule = (policyProperties["PolicyRule"] as PolicyRule).Rule; } return policyDefinitionObject.ToJToken();