Skip to content

Add policy assignments cmdlets #1014

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
Oct 1, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@
<Compile Include="Entities\Locks\LockLevel.cs" />
<Compile Include="Entities\Locks\LockProperties.cs" />
<Compile Include="Entities\Operations\AzureAsyncOperationResource.cs" />
<Compile Include="Entities\Policy\PolicyAssignment.cs" />
<Compile Include="Entities\Policy\PolicyAssignmentProperties.cs" />
<Compile Include="Entities\Policy\PolicyDefinition.cs" />
<Compile Include="Entities\Policy\PolicyDefinitionProperties.cs" />
<Compile Include="Entities\Policy\PolicyRule.cs" />
Expand Down Expand Up @@ -140,10 +142,15 @@
<Compile Include="Implementation\InvokeAzureResourceActionCmdlet.cs" />
<Compile Include="Implementation\MoveAzureResourceCmdlet.cs" />
<Compile Include="Implementation\NewAzureResourceLockCmdlet.cs" />
<Compile Include="Implementation\Policy\GetAzurePolicyAssignment.cs" />
<Compile Include="Implementation\Policy\GetAzurePolicyDefinition.cs" />
<Compile Include="Implementation\Policy\NewAzurePolicyAssignment.cs" />
<Compile Include="Implementation\Policy\NewAzurePolicyDefinition.cs" />
<Compile Include="Implementation\Policy\PolicyAssignmentCmdletBase.cs" />
<Compile Include="Implementation\Policy\PolicyDefinitionCmdletBase.cs" />
<Compile Include="Implementation\Policy\RemoveAzurePolicyAssignment.cs" />
<Compile Include="Implementation\Policy\RemoveAzurePolicyDefinition.cs" />
<Compile Include="Implementation\Policy\SetAzurePolicyAssignment.cs" />
<Compile Include="Implementation\Policy\SetAzurePolicyDefinition.cs" />
<Compile Include="Implementation\RemoveAzureResourceCmdlet.cs" />
<Compile Include="Implementation\RemoveAzureResourceLockCmdlet.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ public static class Constants
/// </summary>
public static readonly string MicrosoftAuthorizationPolicyDefinitionType = Constants.MicrosoftAuthorizationNamespace + "/policydefinitions";

/// <summary>
/// The policy definition resource type.
/// </summary>
public static readonly string MicrosoftAuthorizationPolicyAssignmentType = Constants.MicrosoftAuthorizationNamespace + "/policyassignments";

/// <summary>
/// The type name of the generic resource.
/// </summary>
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.Policy
{
using Newtonsoft.Json;

/// <summary>
/// The policy assignment object.
/// </summary>
public class PolicyAssignment
{
/// <summary>
/// The policy assignment properties.
/// </summary>
[JsonProperty(Required = Required.Default)]
public PolicyAssignmentProperties Properties { get; set; }

/// <summary>
/// The policy assignment name.
/// </summary>
[JsonProperty(Required = Required.Default)]
public string Name { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// The policy assignment properties.
/// </summary>
public class PolicyAssignmentProperties
{
/// <summary>
/// The scope.
/// </summary>
[JsonProperty(Required = Required.Always)]
public string Scope { get; set; }

/// <summary>
/// The display name.
/// </summary>
[JsonProperty(Required = Required.Default)]
public string DisplayName { get; set; }

/// <summary>
/// The policy definition id.
/// </summary>
[JsonProperty(Required = Required.Always)]
public string PolicyDefinitionId { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy
/// </summary>
public class PolicyDefinition
{
/// <summary>
/// The policy definition name.
/// </summary>
[JsonProperty(Required = Required.Default)]
public string Name { get; set; }

/// <summary>
/// The policy definition properties.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy
{
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

/// <summary>
/// The policy definition properties.
Expand All @@ -37,6 +38,6 @@ public class PolicyDefinitionProperties
/// The policy rule.
/// </summary>
[JsonProperty(Required = Required.Always)]
public PolicyRule PolicyRule { get; set; }
public JObject PolicyRule { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
// ----------------------------------------------------------------------------------
//
// 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;

/// <summary>
/// Gets the policy assignment.
/// </summary>
[Cmdlet(VerbsCommon.Get, "AzureRmPolicyAssignment", DefaultParameterSetName = GetAzurePolicyAssignmentCmdlet.ParameterlessSet), OutputType(typeof(PSObject))]
public class GetAzurePolicyAssignmentCmdlet : PolicyAssignmentCmdletBase
{
/// <summary>
/// The policy Id parameter set.
/// </summary>
internal const string PolicyAssignmentIdParameterSet = "The policy assignment Id parameter set.";

/// <summary>
/// The policy name parameter set.
/// </summary>
internal const string PolicyAssignmentNameParameterSet = "The policy assignment name parameter set.";

/// <summary>
/// The list all policy parameter set.
/// </summary>
internal const string ParameterlessSet = "The list all policy assignments parameter set.";

/// <summary>
/// Gets or sets the policy assignment name parameter.
/// </summary>
[Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }

/// <summary>
/// Gets or sets the policy assignment scope parameter.
/// </summary>
[Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")]
[ValidateNotNullOrEmpty]
public string Scope { get; set; }

/// <summary>
/// Gets or sets the policy assignment id parameter
/// </summary>
[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; }

/// <summary>
/// Gets or sets the policy assignment policy definition id parameter
/// </summary>
[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; }

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

this.RunCmdlet();
}

/// <summary>
/// Contains the cmdlet's execution logic.
/// </summary>
private void RunCmdlet()
{
PaginatedResponseHelper.ForEach(
getFirstPage: () => this.GetResources(),
getNextPage: nextLink => this.GetNextLink<JObject>(nextLink),
cancellationToken: this.CancellationToken,
action: resources => this.WriteObject(sendToPipeline: this.GetOutputObjects(resources), enumerateCollection: true));
}

/// <summary>
/// Queries the ARM cache and returns the cached resource that match the query specified.
/// </summary>
private async Task<ResponseWithContinuation<JObject[]>> 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<JObject>(
resourceId: resourceId,
apiVersion: apiVersion,
cancellationToken: this.CancellationToken.Value,
odataQuery: null)
.ConfigureAwait(continueOnCapturedContext: false);
ResponseWithContinuation<JObject[]> retVal;
return resource.TryConvertTo(out retVal) && retVal.Value != null
? retVal
: new ResponseWithContinuation<JObject[]> { Value = resource.AsArray() };
}
else if (IsScopeLevelList(resourceId))//If only scope is given, list assignments call
{
string filter = "$filter=atScope()";
return await this
.GetResourcesClient()
.ListObjectColleciton<JObject>(
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<JObject>(
resourceCollectionId: resourceId,
apiVersion: apiVersion,
cancellationToken: this.CancellationToken.Value,
odataQuery: filter)
.ConfigureAwait(continueOnCapturedContext: false);
}
}

/// <summary>
/// Returns true if it is scope level policy assignment list call
/// </summary>
private bool IsScopeLevelList(string resourceId)
{
return (!string.IsNullOrEmpty(this.Scope) && string.IsNullOrEmpty(this.Name))
|| (!string.IsNullOrEmpty(this.Scope) && string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId)));
}

/// <summary>
/// Returns true if it is a single policy assignment get
/// </summary>
/// <param name="resourceId"></param>
private bool IsResourceGet(string resourceId)
{
return (!string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.Scope))
|| !string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId));
}

/// <summary>
/// Gets the resource Id
/// </summary>
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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ private async Task<ResponseWithContinuation<JObject[]>> GetResources()
.DetermineApiVersion(resourceId: resourceId)
.ConfigureAwait(continueOnCapturedContext: false);

if (!string.IsNullOrEmpty(ResourceIdUtility.GetResourceGroupName(resourceId)))
if (!string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId)))
{
var resource = await this
.GetResourcesClient()
Expand Down
Loading