Skip to content

Commit 56d97ab

Browse files
committed
Merge pull request #1052 from chidmdxx/FindResourceGroupCmdlet
Add FindResourceGroupCmdlet
2 parents a5ce138 + f12920e commit 56d97ab

File tree

8 files changed

+2142
-0
lines changed

8 files changed

+2142
-0
lines changed

src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Commands.Resources.Rest.csproj

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@
138138
<Compile Include="Handlers\TracingHandler.cs" />
139139
<Compile Include="Handlers\CmdletInfoHandler.cs" />
140140
<Compile Include="Handlers\UserAgentHandler.cs" />
141+
<Compile Include="Implementation\FindAzureResourceGroupCmdlet.cs" />
141142
<Compile Include="Implementation\GetAzureResourceGroupDeploymentOperationCmdlet.cs" />
142143
<Compile Include="Implementation\Lock\GetAzureResourceLockCmdlet.cs" />
143144
<Compile Include="Implementation\InvokeAzureResourceActionCmdlet.cs" />
@@ -200,6 +201,10 @@
200201
<Project>{3819d8a7-c62c-4c47-8ddd-0332d9ce1252}</Project>
201202
<Name>Commands.ResourceManager.Common</Name>
202203
</ProjectReference>
204+
<ProjectReference Include="..\..\..\Tags\Commands.Tags\Commands.Tags.csproj">
205+
<Project>{2493A8F7-1949-4F29-8D53-9D459046C3B8}</Project>
206+
<Name>Commands.Tags</Name>
207+
</ProjectReference>
203208
</ItemGroup>
204209
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
205210
<Import Project="..\..\..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets" Condition="Exists('..\..\..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" />

src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Components/ResourceIdUtility.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,20 @@ public static string GetResourceId(Guid? subscriptionId, string resourceGroupNam
8484
return resourceId.ToString();
8585
}
8686

87+
/// <summary>
88+
/// Processes the parameters to return a valid resource Id.
89+
/// </summary>
90+
/// <param name="subscriptionId">The subscription.</param>
91+
public static string GetResourceGroupsId(Guid? subscriptionId)
92+
{
93+
if (subscriptionId == null)
94+
{
95+
throw new InvalidOperationException("A resource group cannot be specified without a subscription.");
96+
}
97+
98+
return string.Format("/subscriptions/{0}/resourceGroups", Uri.EscapeDataString(subscriptionId.Value.ToString()));
99+
}
100+
87101
/// <summary>
88102
/// Processes the parameters to return a valid resource Id.
89103
/// </summary>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
// ----------------------------------------------------------------------------------
2+
//
3+
// Copyright Microsoft Corporation
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
// You may obtain a copy of the License at
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
// ----------------------------------------------------------------------------------
14+
15+
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
16+
{
17+
using System;
18+
using System.Collections;
19+
using System.Management.Automation;
20+
using System.Threading.Tasks;
21+
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
22+
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources;
23+
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
24+
using Microsoft.Azure.Commands.Tags.Model;
25+
using Newtonsoft.Json.Linq;
26+
27+
/// <summary>
28+
/// Finds the resource group.
29+
/// </summary>
30+
[Cmdlet(VerbsCommon.Find, "AzureRmResourceGroup"), OutputType(typeof(PSObject))]
31+
public class FindAzureResourceGroupCmdlet : ResourceManagerCmdletBase
32+
{
33+
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The tag filter for the OData query. The expected format is @{Name = 'tagName'} or @{Name = 'tagName'; Value = 'tagValue'}.")]
34+
public Hashtable Tag { get; set; }
35+
36+
/// <summary>
37+
/// Finishes the pipeline execution and runs the cmdlet.
38+
/// </summary>
39+
protected override void OnEndProcessing()
40+
{
41+
base.OnEndProcessing();
42+
43+
this.RunCmdlet();
44+
}
45+
46+
/// <summary>
47+
/// Contains the cmdlet's execution logic.
48+
/// </summary>
49+
private void RunCmdlet()
50+
{
51+
PaginatedResponseHelper.ForEach(
52+
getFirstPage: () => this.GetResourceGroups(),
53+
getNextPage: nextLink => this.GetNextLink<JObject>(nextLink),
54+
cancellationToken: this.CancellationToken,
55+
action: resourceGroups => this.WriteObject(sendToPipeline: resourceGroups.CoalesceEnumerable().SelectArray(resourceGroup => resourceGroup.ToPsObject(ResourceObjectFormat.New)), enumerateCollection: true));
56+
}
57+
58+
/// <summary>
59+
/// Queries the ARM cache and returns the cached resource groups that match the query specified.
60+
/// </summary>
61+
private async Task<ResponseWithContinuation<JObject[]>> GetResourceGroups()
62+
{
63+
var resourceGroupsId = string.Format("/subscriptions/{0}/resourceGroups", Uri.EscapeDataString(this.DefaultContext.Subscription.Id.ToString()));
64+
65+
var apiVersion = await this
66+
.DetermineApiVersion(resourceId: resourceGroupsId)
67+
.ConfigureAwait(continueOnCapturedContext: false);
68+
69+
string queryString = null;
70+
71+
if (this.Tag != null)
72+
{
73+
var tagValuePair = TagsConversionHelper.Create(this.Tag);
74+
75+
if (tagValuePair == null)
76+
{
77+
throw new ArgumentException("Invalid tag format. Expect @{Name = 'tagName'} or @{Name = 'tagName'; Value = 'tagValue'}.");
78+
}
79+
80+
queryString = tagValuePair.Value != null
81+
? string.Format("$filter=tagname eq '{0}' and tagvalue eq '{1}'", tagValuePair.Name, tagValuePair.Value)
82+
: string.Format("$filter=tagname eq '{0}'", tagValuePair.Name);
83+
}
84+
85+
return await this
86+
.GetResourcesClient()
87+
.ListObjectColleciton<JObject>(
88+
resourceCollectionId: resourceGroupsId,
89+
apiVersion: apiVersion,
90+
cancellationToken: this.CancellationToken.Value,
91+
odataQuery: queryString)
92+
.ConfigureAwait(continueOnCapturedContext: false);
93+
}
94+
95+
/// <summary>
96+
/// Gets the next set of resources using the <paramref name="nextLink"/>
97+
/// </summary>
98+
/// <param name="nextLink">The next link.</param>
99+
private Task<ResponseWithContinuation<TType[]>> GetNextLink<TType>(string nextLink)
100+
{
101+
return this
102+
.GetResourcesClient()
103+
.ListNextBatch<TType>(nextLink: nextLink, cancellationToken: this.CancellationToken.Value);
104+
}
105+
}
106+
}

src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Microsoft.Azure.Commands.ResourceManager.Cmdlets.dll-Help.xml

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7538,4 +7538,146 @@
75387538
<maml:relatedLinks>
75397539
</maml:relatedLinks>
75407540
</command:command>
7541+
<command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10" xmlns:MSHelp="http://msdn.microsoft.com/mshelp">
7542+
<!--Generated by PS Cmdlet Help Editor-->
7543+
<command:details>
7544+
<command:name>Find-AzureRmResourceGroup</command:name>
7545+
<maml:description>
7546+
<maml:para>Searches for resource group using the specified parameters.</maml:para>
7547+
</maml:description>
7548+
<maml:copyright>
7549+
<maml:para />
7550+
</maml:copyright>
7551+
<command:verb>Find</command:verb>
7552+
<command:noun>AzureRmResourceGroup</command:noun>
7553+
<dev:version />
7554+
</command:details>
7555+
<maml:description>
7556+
<maml:para>Searches for resource group using the specified parameters.</maml:para>
7557+
</maml:description>
7558+
<command:syntax>
7559+
<command:syntaxItem>
7560+
<maml:name>Find-AzureRmResourceGroup</maml:name>
7561+
<command:parameter required="false" variableLength="false" globbing="false" pipelineInput="true (ByPropertyName)" position="named">
7562+
<maml:name>Tag</maml:name>
7563+
<maml:description>
7564+
<maml:para>The tag filter for the OData query. The expected format is @{Name = 'tagName'} or @{Name = 'tagName'; Value = 'tagValue'}.</maml:para>
7565+
</maml:description>
7566+
<command:parameterValue required="true" variableLength="false">Hashtable</command:parameterValue>
7567+
</command:parameter>
7568+
</command:syntaxItem>
7569+
</command:syntax>
7570+
<command:parameters>
7571+
<command:parameter required="false" variableLength="false" globbing="false" pipelineInput="true (ByPropertyName)" position="named">
7572+
<maml:name>Tag</maml:name>
7573+
<maml:description>
7574+
<maml:para>The tag filter for the OData query. The expected format is @{Name = 'tagName'} or @{Name = 'tagName'; Value = 'tagValue'}.</maml:para>
7575+
</maml:description>
7576+
<command:parameterValue required="true" variableLength="false">Hashtable</command:parameterValue>
7577+
<dev:type>
7578+
<maml:name>Hashtable</maml:name>
7579+
<maml:uri/>
7580+
</dev:type>
7581+
<dev:defaultValue></dev:defaultValue>
7582+
</command:parameter>
7583+
</command:parameters>
7584+
<command:inputTypes>
7585+
<command:inputType>
7586+
<dev:type>
7587+
<maml:name></maml:name>
7588+
<maml:uri></maml:uri>
7589+
<maml:description/>
7590+
</dev:type>
7591+
<maml:description>
7592+
<maml:para>
7593+
</maml:para>
7594+
</maml:description>
7595+
</command:inputType>
7596+
</command:inputTypes>
7597+
<command:returnValues>
7598+
<command:returnValue>
7599+
<dev:type>
7600+
<maml:name></maml:name>
7601+
<maml:uri></maml:uri>
7602+
<maml:description/>
7603+
</dev:type>
7604+
<maml:description>
7605+
<maml:para>
7606+
</maml:para>
7607+
</maml:description>
7608+
</command:returnValue>
7609+
</command:returnValues>
7610+
<command:terminatingErrors></command:terminatingErrors>
7611+
<command:nonTerminatingErrors></command:nonTerminatingErrors>
7612+
<maml:alertSet>
7613+
<maml:title></maml:title>
7614+
<maml:alert>
7615+
<maml:para />
7616+
</maml:alert>
7617+
</maml:alertSet>
7618+
<command:examples>
7619+
<command:example>
7620+
<maml:title>-------------------------- FindAllResourceGroups --------------------------</maml:title>
7621+
<maml:introduction>
7622+
<maml:paragraph>PS C:\&gt;</maml:paragraph>
7623+
</maml:introduction>
7624+
<dev:code>Find-AzureRmResourceGroup</dev:code>
7625+
<dev:remarks>
7626+
<maml:para>Finds all resource group.</maml:para>
7627+
<maml:para />
7628+
<maml:para />
7629+
<maml:para></maml:para>
7630+
</dev:remarks>
7631+
<command:commandLines>
7632+
<command:commandLine>
7633+
<command:commandText>
7634+
<maml:para />
7635+
</command:commandText>
7636+
</command:commandLine>
7637+
</command:commandLines>
7638+
</command:example>
7639+
<command:example>
7640+
<maml:title>-------------------------- FindByTagName --------------------------</maml:title>
7641+
<maml:introduction>
7642+
<maml:paragraph>PS C:\&gt;</maml:paragraph>
7643+
</maml:introduction>
7644+
<dev:code>Find-AzureRmResourceGroup -Tag @{ Name = "testtag" }</dev:code>
7645+
<dev:remarks>
7646+
<maml:para>Finds all resource group with a tag with name 'testtag'.</maml:para>
7647+
<maml:para />
7648+
<maml:para />
7649+
<maml:para></maml:para>
7650+
</dev:remarks>
7651+
<command:commandLines>
7652+
<command:commandLine>
7653+
<command:commandText>
7654+
<maml:para />
7655+
</command:commandText>
7656+
</command:commandLine>
7657+
</command:commandLines>
7658+
</command:example>
7659+
<command:example>
7660+
<maml:title>-------------------------- FindByTagNameAndValue --------------------------</maml:title>
7661+
<maml:introduction>
7662+
<maml:paragraph>PS C:\&gt;</maml:paragraph>
7663+
</maml:introduction>
7664+
<dev:code>Find-AzureRmResourceGroup -Tag @{ Name = "testtag"; Value = "testval" }</dev:code>
7665+
<dev:remarks>
7666+
<maml:para>Finds all resource group with a tag with name 'testtag' and value 'testval'.</maml:para>
7667+
<maml:para />
7668+
<maml:para />
7669+
<maml:para></maml:para>
7670+
</dev:remarks>
7671+
<command:commandLines>
7672+
<command:commandLine>
7673+
<command:commandText>
7674+
<maml:para />
7675+
</command:commandText>
7676+
</command:commandLine>
7677+
</command:commandLines>
7678+
</command:example>
7679+
</command:examples>
7680+
<maml:relatedLinks>
7681+
</maml:relatedLinks>
7682+
</command:command>
75417683
</helpItems>

src/ResourceManager/Resources/Commands.Resources.Test/Commands.Resources.Test.csproj

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,9 @@
337337
<None Include="SessionRecords\Microsoft.Azure.Commands.Resources.Test.ScenarioTests.ProviderTests\TestAzureProviderOperation.json">
338338
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
339339
</None>
340+
<None Include="SessionRecords\Microsoft.Azure.Commands.Resources.Test.ScenarioTests.ResourceGroupTests\TestFindResourceGroup.json">
341+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
342+
</None>
340343
<None Include="SessionRecords\Microsoft.Azure.Commands.Resources.Test.ScenarioTests.ResourceGroupTests\TestNewDeploymentAndProviderRegistration.json">
341344
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
342345
</None>

src/ResourceManager/Resources/Commands.Resources.Test/ScenarioTests/ResourceGroupTests.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,13 @@ public void TestRemoveNonExistingResourceGroup()
6262
ResourcesController.NewInstance.RunPsTest("Test-RemoveNonExistingResourceGroup");
6363
}
6464

65+
[Fact]
66+
[Trait(Category.AcceptanceType, Category.CheckIn)]
67+
public void TestFindResourceGroup()
68+
{
69+
ResourcesController.NewInstance.RunPsTest("Test-FindResourceGroup");
70+
}
71+
6572
[Fact (Skip = "TODO: Fix the broken test.")]
6673
public void TestAzureTagsEndToEnd()
6774
{

src/ResourceManager/Resources/Commands.Resources.Test/ScenarioTests/ResourceGroupTests.ps1

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,4 +251,58 @@ function Test-RemoveDeployment
251251
# Cleanup
252252
Clean-ResourceGroup $rgName
253253
}
254+
}
255+
256+
<#
257+
.SYNOPSIS
258+
Tests find resource group command
259+
#>
260+
function Test-FindResourceGroup
261+
{
262+
# Setup
263+
$rgname = Get-ResourceGroupName
264+
$rgname2 = Get-ResourceGroupName
265+
$location = Get-ProviderLocation ResourceManagement
266+
$originalResorcrGroups = Find-AzureRmResourceGroup
267+
$originalCount = @($originalResorcrGroups).Count
268+
269+
try
270+
{
271+
# Test
272+
$actual = New-AzureRmResourceGroup -Name $rgname -Location $location -Tag @{ Name = "testtag"; Value = "testval" }
273+
$actual2 = New-AzureRmResourceGroup -Name $rgname2 -Location $location -Tag @{ Name = "testtag"; Value = "testval2" }
274+
275+
$expected1 = Get-AzureRmResourceGroup -Name $rgname
276+
# Assert
277+
Assert-AreEqual $expected1.ResourceGroupName $actual.ResourceGroupName
278+
Assert-AreEqual $expected1.Tags[0]["Name"] $actual.Tags[0]["Name"]
279+
280+
$expected2 = Get-AzureRmResourceGroup -Name $rgname2
281+
# Assert
282+
Assert-AreEqual $expected2.ResourceGroupName $actual2.ResourceGroupName
283+
Assert-AreEqual $expected2.Tags[0]["Name"] $actual2.Tags[0]["Name"]
284+
285+
$expected3 = Find-AzureRmResourceGroup
286+
$expectedCount = $originalCount + 2
287+
# Assert
288+
Assert-AreEqual @($expected3).Count $expectedCount
289+
290+
$expected4 = Find-AzureRmResourceGroup -Tag @{ Name = "testtag";}
291+
# Assert
292+
Assert-AreEqual @($expected4).Count 2
293+
294+
$expected5 = Find-AzureRmResourceGroup -Tag @{ Name = "testtag"; Value = "testval" }
295+
# Assert
296+
Assert-AreEqual @($expected5).Count 1
297+
298+
$expected6 = Find-AzureRmResourceGroup -Tag @{ Name = "testtag2"}
299+
# Assert
300+
Assert-AreEqual @($expected6).Count 0
301+
}
302+
finally
303+
{
304+
# Cleanup
305+
Clean-ResourceGroup $rgname
306+
Clean-ResourceGroup $rgname2
307+
}
254308
}

src/ResourceManager/Resources/Commands.Resources.Test/SessionRecords/Microsoft.Azure.Commands.Resources.Test.ScenarioTests.ResourceGroupTests/TestFindResourceGroup.json

Lines changed: 1811 additions & 0 deletions
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)