├── .gitignore ├── .vscode ├── launch.json └── tasks.json ├── CONTRIBUTING.md ├── LICENSE ├── Program.cs ├── README.md └── project.json /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | *.VC.VC.opendb 85 | 86 | # Visual Studio profiler 87 | *.psess 88 | *.vsp 89 | *.vspx 90 | *.sap 91 | 92 | # TFS 2012 Local Workspace 93 | $tf/ 94 | 95 | # Guidance Automation Toolkit 96 | *.gpState 97 | 98 | # ReSharper is a .NET coding add-in 99 | _ReSharper*/ 100 | *.[Rr]e[Ss]harper 101 | *.DotSettings.user 102 | 103 | # JustCode is a .NET coding add-in 104 | .JustCode 105 | 106 | # TeamCity is a build add-in 107 | _TeamCity* 108 | 109 | # DotCover is a Code Coverage Tool 110 | *.dotCover 111 | 112 | # NCrunch 113 | _NCrunch_* 114 | .*crunch*.local.xml 115 | nCrunchTemp_* 116 | 117 | # MightyMoose 118 | *.mm.* 119 | AutoTest.Net/ 120 | 121 | # Web workbench (sass) 122 | .sass-cache/ 123 | 124 | # Installshield output folder 125 | [Ee]xpress/ 126 | 127 | # DocProject is a documentation generator add-in 128 | DocProject/buildhelp/ 129 | DocProject/Help/*.HxT 130 | DocProject/Help/*.HxC 131 | DocProject/Help/*.hhc 132 | DocProject/Help/*.hhk 133 | DocProject/Help/*.hhp 134 | DocProject/Help/Html2 135 | DocProject/Help/html 136 | 137 | # Click-Once directory 138 | publish/ 139 | 140 | # Publish Web Output 141 | *.[Pp]ublish.xml 142 | *.azurePubxml 143 | # TODO: Comment the next line if you want to checkin your web deploy settings 144 | # but database connection strings (with potential passwords) will be unencrypted 145 | *.pubxml 146 | *.publishproj 147 | 148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 149 | # checkin your Azure Web App publish settings, but sensitive information contained 150 | # in these scripts will be unencrypted 151 | PublishScripts/ 152 | 153 | # NuGet Packages 154 | *.nupkg 155 | # The packages folder can be ignored because of Package Restore 156 | **/packages/* 157 | # except build/, which is used as an MSBuild target. 158 | !**/packages/build/ 159 | # Uncomment if necessary however generally it will be regenerated when needed 160 | #!**/packages/repositories.config 161 | # NuGet v3's project.json files produces more ignoreable files 162 | *.nuget.props 163 | *.nuget.targets 164 | 165 | # Microsoft Azure Build Output 166 | csx/ 167 | *.build.csdef 168 | 169 | # Microsoft Azure Emulator 170 | ecf/ 171 | rcf/ 172 | 173 | # Windows Store app package directories and files 174 | AppPackages/ 175 | BundleArtifacts/ 176 | Package.StoreAssociation.xml 177 | _pkginfo.txt 178 | 179 | # Visual Studio cache files 180 | # files ending in .cache can be ignored 181 | *.[Cc]ache 182 | # but keep track of directories ending in .cache 183 | !*.[Cc]ache/ 184 | 185 | # Others 186 | ClientBin/ 187 | ~$* 188 | *~ 189 | *.dbmdl 190 | *.dbproj.schemaview 191 | *.pfx 192 | *.publishsettings 193 | node_modules/ 194 | orleans.codegen.cs 195 | 196 | # Since there are multiple workflows, uncomment next line to ignore bower_components 197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 198 | #bower_components/ 199 | 200 | # RIA/Silverlight projects 201 | Generated_Code/ 202 | 203 | # Backup & report files from converting an old project file 204 | # to a newer Visual Studio version. Backup files are not needed, 205 | # because we have git ;-) 206 | _UpgradeReport_Files/ 207 | Backup*/ 208 | UpgradeLog*.XML 209 | UpgradeLog*.htm 210 | 211 | # SQL Server files 212 | *.mdf 213 | *.ldf 214 | 215 | # Business Intelligence projects 216 | *.rdl.data 217 | *.bim.layout 218 | *.bim_*.settings 219 | 220 | # Microsoft Fakes 221 | FakesAssemblies/ 222 | 223 | # GhostDoc plugin setting file 224 | *.GhostDoc.xml 225 | 226 | # Node.js Tools for Visual Studio 227 | .ntvs_analysis.dat 228 | 229 | # Visual Studio 6 build log 230 | *.plg 231 | 232 | # Visual Studio 6 workspace options file 233 | *.opt 234 | 235 | # Visual Studio LightSwitch build output 236 | **/*.HTMLClient/GeneratedArtifacts 237 | **/*.DesktopClient/GeneratedArtifacts 238 | **/*.DesktopClient/ModelManifest.xml 239 | **/*.Server/GeneratedArtifacts 240 | **/*.Server/ModelManifest.xml 241 | _Pvt_Extensions 242 | 243 | # Paket dependency manager 244 | .paket/paket.exe 245 | paket-files/ 246 | 247 | # FAKE - F# Make 248 | .fake/ 249 | 250 | # JetBrains Rider 251 | .idea/ 252 | *.sln.iml 253 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": ".NET Core Launch (console)", 6 | "type": "coreclr", 7 | "request": "launch", 8 | "preLaunchTask": "build", 9 | "program": "${workspaceRoot}/bin/Debug/netcoreapp1.0/resource-manager-dotnet-resources-and-groups.dll", 10 | "args": [], 11 | "cwd": "${workspaceRoot}", 12 | "externalConsole": false, 13 | "stopAtEntry": false 14 | }, 15 | { 16 | "name": ".NET Core Attach", 17 | "type": "coreclr", 18 | "request": "attach", 19 | "processId": 0 20 | } 21 | ] 22 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.1.0", 3 | "command": "dotnet", 4 | "isShellCommand": true, 5 | "args": [], 6 | "tasks": [ 7 | { 8 | "taskName": "build", 9 | "args": [], 10 | "isBuildCommand": true, 11 | "problemMatcher": "$msCompile" 12 | } 13 | ] 14 | } -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Azure samples 2 | 3 | Thank you for your interest in contributing to Azure samples! 4 | 5 | ## Ways to contribute 6 | 7 | You can contribute to [Azure samples](https://azure.microsoft.com/documentation/samples/) in a few different ways: 8 | 9 | - Submit feedback on [this sample page](https://azure.microsoft.com/documentation/samples/resource-manager-dotnet-resources-and-groups/) whether it was helpful or not. 10 | - Submit issues through [issue tracker](https://github.com/Azure-Samples/resource-manager-dotnet-resources-and-groups/issues) on GitHub. We are actively monitoring the issues and improving our samples. 11 | - If you wish to make code changes to samples, or contribute something new, please follow the [GitHub Forks / Pull requests model](https://help.github.com/articles/fork-a-repo/): Fork the sample repo, make the change and propose it back by submitting a pull request. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Microsoft Corporation 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.IO; 6 | 7 | // Azure Management dependencies 8 | using Microsoft.Rest.Azure.Authentication; 9 | using Microsoft.Azure.Management.ResourceManager; 10 | using Microsoft.Azure.Management.ResourceManager.Models; 11 | 12 | namespace ConsoleApplication 13 | { 14 | public class Program 15 | { 16 | public static void Main(string[] args) 17 | { 18 | var tenantId = Environment.GetEnvironmentVariable("AZURE_TENANT_ID"); 19 | var clientId = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID"); 20 | var secret = Environment.GetEnvironmentVariable("AZURE_SECRET"); 21 | var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID"); 22 | if(new List{ tenantId, clientId, secret, subscriptionId }.Any(i => String.IsNullOrEmpty(i))) { 23 | Console.WriteLine("Please provide ENV vars for AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_SECRET and AZURE_SUBSCRIPTION_ID."); 24 | } 25 | else 26 | { 27 | RunSample(tenantId, clientId, secret, subscriptionId).Wait(); 28 | } 29 | } 30 | 31 | public static async Task RunSample(string tenantId, string clientId, string secret, string subscriptionId) 32 | { 33 | // Build the service credentials and Azure Resource Manager clients 34 | var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret); 35 | var resourceClient = new ResourceManagementClient(serviceCreds); 36 | resourceClient.SubscriptionId = subscriptionId; 37 | 38 | Random r = new Random(); 39 | int postfix = r.Next(0, 1000000); 40 | 41 | var resourceGroupName = "sample-dotnet-group-mgmt"; 42 | var westus = "westus"; 43 | 44 | Write("Listing resource groups:"); 45 | resourceClient.ResourceGroups.List().ToList().ForEach(rg => { 46 | Write("\tName: {0}, Id: {1}", rg.Name, rg.Id); 47 | }); 48 | Write(Environment.NewLine); 49 | 50 | Write("Creating resource group named {0} in {1}", resourceGroupName, westus); 51 | var groupParams = new ResourceGroup { Location = westus}; 52 | resourceClient.ResourceGroups.CreateOrUpdate(resourceGroupName, groupParams); 53 | Write(Environment.NewLine); 54 | 55 | Write("Adding tags to the resource group"); 56 | groupParams.Tags = new Dictionary{{"Hello", "World"}}; 57 | resourceClient.ResourceGroups.CreateOrUpdate(resourceGroupName, groupParams); 58 | Write(Environment.NewLine); 59 | 60 | Write("Listing resource groups:"); 61 | resourceClient.ResourceGroups.List().ToList().ForEach(rg => { 62 | Write("\tName: {0}, Id: {1}", rg.Name, rg.Id); 63 | }); 64 | Write(Environment.NewLine); 65 | 66 | Write("Create a Key Vault resource with a generic PUT"); 67 | var keyVaultParams = new GenericResource{ 68 | Location = westus, 69 | Properties = new Dictionary{ 70 | {"tenantId", tenantId}, 71 | {"sku", new Dictionary{{"family", "A"}, {"name", "standard"}}}, 72 | {"accessPolicies", Array.Empty()}, 73 | {"enabledForDeployment", true}, 74 | {"enabledForTemplateDeployment", true}, 75 | {"enabledForDiskEncryption", true} 76 | } 77 | }; 78 | var keyVault = resourceClient.Resources.CreateOrUpdate( 79 | resourceGroupName, 80 | "Microsoft.KeyVault", 81 | "", 82 | "vaults", 83 | "azureSampleVault", 84 | "2015-06-01", 85 | keyVaultParams); 86 | Write("\tKey Vault Name: {0} and Id: {1}", keyVault.Name, keyVault.Id); 87 | Write(Environment.NewLine); 88 | 89 | Write("Listing resources within group {0}", resourceGroupName); 90 | resourceClient.ResourceGroups.ListResources(resourceGroupName).ToList().ForEach(resource => { 91 | Write("\tName: {0}, Id: {1}", resource.Name, resource.Id); 92 | }); 93 | Write(Environment.NewLine); 94 | 95 | Write("Exporting the resource group template for {0}", resourceGroupName); 96 | Write(Environment.NewLine); 97 | var exportResult = resourceClient.ResourceGroups.ExportTemplate( 98 | resourceGroupName, 99 | new ExportTemplateRequest{ 100 | Resources = new List{"*"} 101 | }); 102 | Write("{0}", exportResult.Template); 103 | Write(Environment.NewLine); 104 | 105 | Write("Press any key to continue and delete the sample resources"); 106 | Console.ReadLine(); 107 | Write(Environment.NewLine); 108 | 109 | Write("deleting resource group {0} and all resources within it", resourceGroupName); 110 | resourceClient.ResourceGroups.Delete(resourceGroupName); 111 | } 112 | 113 | private static void Write(string format, params object[] items) 114 | { 115 | Console.WriteLine(String.Format(format, items)); 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | services: azure-resource-manager 3 | platforms: dotnet 4 | author: devigned 5 | --- 6 | 7 | # Manage Azure resources and resource groups with .NET 8 | 9 | This sample explains how to manage your 10 | [resources and resource groups in Azure](https://azure.microsoft.com/en-us/documentation/articles/resource-group-overview/#resource-groups) 11 | using the Azure .NET SDK. 12 | 13 | **On this page** 14 | 15 | - [Run this sample](#run) 16 | - [What is program.cs doing?](#example) 17 | - [List resource groups](#list-groups) 18 | - [Create a key vault in the resource group](#create-resource) 19 | - [List resources within the group](#list-resources) 20 | - [Export the resource group template](#export) 21 | - [Delete a resource group](#delete-group) 22 | 23 | 24 | ## Run this sample 25 | 26 | 1. If you don't have it, install the [.NET Core SDK](https://www.microsoft.com/net/core). 27 | 28 | 1. Clone the repository. 29 | 30 | ``` 31 | git clone https://github.com/Azure-Samples/resource-manager-dotnet-resources-and-groups.git 32 | ``` 33 | 34 | 1. Install the dependencies. 35 | 36 | ``` 37 | dotnet restore 38 | ``` 39 | 40 | 1. Create an Azure service principal either through 41 | [Azure CLI](https://azure.microsoft.com/documentation/articles/resource-group-authenticate-service-principal-cli/), 42 | [PowerShell](https://azure.microsoft.com/documentation/articles/resource-group-authenticate-service-principal/) 43 | or [the portal](https://azure.microsoft.com/documentation/articles/resource-group-create-service-principal-portal/). 44 | 45 | 1. Export these environment variables using your subscription id and the tenant id, client id and client secret from the service principle that you created. 46 | 47 | ``` 48 | export AZURE_TENANT_ID={your tenant id} 49 | export AZURE_CLIENT_ID={your client id} 50 | export AZURE_CLIENT_SECRET={your client secret} 51 | export AZURE_SUBSCRIPTION_ID={your subscription id} 52 | ``` 53 | 54 | 1. Run the sample. 55 | 56 | ``` 57 | dotnet run 58 | ``` 59 | 60 | 61 | ## What is program.cs doing? 62 | 63 | The sample walks you through several resource and resource group management operations. 64 | It starts by setting up a ResourceManagementClient object using your subscription and credentials. 65 | 66 | ```csharp 67 | // Build the service credentials and Azure Resource Manager clients 68 | var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret); 69 | var resourceClient = new ResourceManagementClient(serviceCreds); 70 | resourceClient.SubscriptionId = subscriptionId; 71 | ``` 72 | 73 | 74 | ### List resource groups 75 | 76 | List the resource groups in your subscription. 77 | 78 | ```csharp 79 | resourceClient.ResourceGroups.List(); 80 | ``` 81 | 82 | 83 | ### Create a key vault in the resource group 84 | 85 | ```csharp 86 | var keyVaultParams = new GenericResource{ 87 | Location = westus, 88 | Properties = new Dictionary{ 89 | {"tenantId", tenantId}, 90 | {"sku", new Dictionary{{"family", "A"}, {"name", "standard"}}}, 91 | {"accessPolicies", Array.Empty()}, 92 | {"enabledForDeployment", true}, 93 | {"enabledForTemplateDeployment", true}, 94 | {"enabledForDiskEncryption", true} 95 | } 96 | }; 97 | var keyVault = resourceClient.Resources.CreateOrUpdate( 98 | resourceGroupName, 99 | "Microsoft.KeyVault", 100 | "", 101 | "vaults", 102 | "azureSampleVault", 103 | "2015-06-01", 104 | keyVaultParams); 105 | ``` 106 | 107 | 108 | ### List resources within the group 109 | 110 | ```csharp 111 | resourceClient.ResourceGroups.ListResources(resourceGroupName); 112 | ``` 113 | 114 | 115 | ### Export the resource group template 116 | 117 | You can export the resource group as a template and then use that 118 | to [deploy your resources to Azure](https://azure.microsoft.com/documentation/samples/resource-manager-dotnet-template-deployment/). 119 | 120 | ```csharp 121 | var exportResult = resourceClient.ResourceGroups.ExportTemplate( 122 | resourceGroupName, 123 | new ExportTemplateRequest{ 124 | Resources = new List{"*"} 125 | }); 126 | ``` 127 | 128 | 129 | ### Delete a resource group 130 | 131 | ```csharp 132 | resourceClient.ResourceGroups.Delete(resourceGroupName); 133 | ``` 134 | -------------------------------------------------------------------------------- /project.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.0-*", 3 | "buildOptions": { 4 | "debugType": "portable", 5 | "emitEntryPoint": true 6 | }, 7 | "dependencies": { 8 | "Microsoft.Azure.Management.ResourceManager": "1.1.3-preview", 9 | "Microsoft.Rest.ClientRuntime.Azure.Authentication": "2.2.4-preview" 10 | }, 11 | "frameworks": { 12 | "netcoreapp1.0": { 13 | "dependencies": { 14 | "Microsoft.NETCore.App": { 15 | "type": "platform", 16 | "version": "1.0.0" 17 | } 18 | }, 19 | "imports": "dnxcore50" 20 | } 21 | } 22 | } 23 | --------------------------------------------------------------------------------