This repository has been archived by the owner on Dec 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
261 lines (227 loc) · 12.4 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.Locks.Fluent;
using Microsoft.Azure.Management.Locks.Fluent.Models;
using Microsoft.Azure.Management.Network.Fluent;
using Microsoft.Azure.Management.Network.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Samples.Common;
using Microsoft.Azure.Management.Storage.Fluent;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace ManageLocks
{
public class Program
{
/**
* Azure sample for applying locks to resources
*
* Summary ...
*
* This sample shows examples of management locks usage on various resources.
*
* Details ...
*
* 1. Create a number of various resources to apply locks to...
* 2. Apply various locks to the resources
* 3. Retrieve and show lock information
* 4. Remove the locks and clean up
*/
public static void RunSample(IAzure azure)
{
string password = SdkContext.RandomResourceName("P@s", 14);
string rgName = SdkContext.RandomResourceName("rg", 15);
string vmName = SdkContext.RandomResourceName("vm", 15);
string storageName = SdkContext.RandomResourceName("st", 15);
string diskName = SdkContext.RandomResourceName("dsk", 15);
string netName = SdkContext.RandomResourceName("net", 15);
Region region = Region.USEast;
IResourceGroup resourceGroup = null;
IManagementLock lockGroup = null,
lockVM = null,
lockStorage = null,
lockDiskRO = null,
lockDiskDel = null,
lockSubnet = null;
try
{
//=============================================================
// Create a shared resource group for all the resources so they can all be deleted together
//
resourceGroup = azure.ResourceGroups.Define(rgName)
.WithRegion(region)
.Create();
Utilities.Log("Created a new resource group - " + resourceGroup.Id);
//============================================================
// Create various resources for demonstrating locks
//
// Define a network to apply a lock to
ICreatable<INetwork> netDefinition = azure.Networks.Define(netName)
.WithRegion(region)
.WithExistingResourceGroup(resourceGroup)
.WithAddressSpace("10.0.0.0/28");
// Define a managed disk for testing locks on that
ICreatable<IDisk> diskDefinition = azure.Disks.Define(diskName)
.WithRegion(region)
.WithExistingResourceGroup(resourceGroup)
.WithData()
.WithSizeInGB(100);
// Define a VM to apply a lock to
ICreatable<IVirtualMachine> vmDefinition = azure.VirtualMachines.Define(vmName)
.WithRegion(region)
.WithExistingResourceGroup(resourceGroup)
.WithNewPrimaryNetwork(netDefinition)
.WithPrimaryPrivateIPAddressDynamic()
.WithoutPrimaryPublicIPAddress()
.WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012Datacenter)
.WithAdminUsername("tester")
.WithAdminPassword(password)
.WithNewDataDisk(diskDefinition, 1, CachingTypes.None)
.WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"));
// Define a storage account to apply a lock to
ICreatable<IStorageAccount> storageDefinition = azure.StorageAccounts.Define(storageName)
.WithRegion(region)
.WithExistingResourceGroup(resourceGroup);
// Create resources in parallel to save time
Utilities.Log("Creating the needed resources...");
Task.WaitAll(
storageDefinition.CreateAsync(),
vmDefinition.CreateAsync());
Utilities.Log("Resources created.");
IVirtualMachine vm = (IVirtualMachine)vmDefinition;
IStorageAccount storage = (IStorageAccount)storageDefinition;
IDisk disk = (IDisk)diskDefinition;
INetwork network = vm.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork();
ISubnet subnet = network.Subnets.Values.FirstOrDefault();
//============================================================
// Create various locks for the created resources
//
// Locks can be created serially, and multiple can be applied to the same resource:
Utilities.Log("Creating locks sequentially...");
// Apply a ReadOnly lock to the disk
lockDiskRO = azure.ManagementLocks.Define("diskLockRO")
.WithLockedResource(disk)
.WithLevel(LockLevel.ReadOnly)
.Create();
// Apply a lock preventing the disk from being deleted
lockDiskDel = azure.ManagementLocks.Define("diskLockDel")
.WithLockedResource(disk)
.WithLevel(LockLevel.CanNotDelete)
.Create();
// Locks can also be created in parallel, for better overall performance:
Utilities.Log("Creating locks in parallel...");
// Define a subnet lock
ICreatable<IManagementLock> lockSubnetDef = azure.ManagementLocks.Define("subnetLock")
.WithLockedResource(subnet.Inner.Id)
.WithLevel(LockLevel.ReadOnly);
// Define a VM lock
ICreatable<IManagementLock> lockVMDef = azure.ManagementLocks.Define("vmlock")
.WithLockedResource(vm)
.WithLevel(LockLevel.ReadOnly)
.WithNotes("vm readonly lock");
// Define a resource group lock
ICreatable<IManagementLock> lockGroupDef = azure.ManagementLocks.Define("rglock")
.WithLockedResource(resourceGroup.Id)
.WithLevel(LockLevel.CanNotDelete);
// Define a storage lock
ICreatable<IManagementLock> lockStorageDef = azure.ManagementLocks.Define("stLock")
.WithLockedResource(storage)
.WithLevel(LockLevel.CanNotDelete);
var created = azure.ManagementLocks.Create(
lockVMDef,
lockGroupDef,
lockStorageDef,
lockSubnetDef);
lockVM = created.FirstOrDefault(o => o.Key.Equals(lockVMDef.Key, StringComparison.OrdinalIgnoreCase));
lockStorage = created.FirstOrDefault(o => o.Key.Equals(lockStorageDef.Key, StringComparison.OrdinalIgnoreCase));
lockGroup = created.FirstOrDefault(o => o.Key.Equals(lockGroupDef.Key, StringComparison.OrdinalIgnoreCase));
lockSubnet = created.FirstOrDefault(o => o.Key.Equals(lockSubnetDef.Key, StringComparison.OrdinalIgnoreCase));
Utilities.Log("Locks created.");
//============================================================
// Retrieve and show lock information
//
// Count and show locks (Note: locks returned for a resource include the locks for its resource group and child resources)
int lockCount = azure.ManagementLocks.ListForResource(vm.Id).Count();
Utilities.Log("Number of locks applied to the virtual machine: " + lockCount);
lockCount = azure.ManagementLocks.ListByResourceGroup(resourceGroup.Name).Count();
Utilities.Log("Number of locks applied to the resource group (includes locks on resources in the group): " + lockCount);
lockCount = azure.ManagementLocks.ListForResource(storage.Id).Count();
Utilities.Log("Number of locks applied to the storage account: " + lockCount);
lockCount = azure.ManagementLocks.ListForResource(disk.Id).Count();
Utilities.Log("Number of locks applied to the managed disk: " + lockCount);
lockCount = azure.ManagementLocks.ListForResource(network.Id).Count();
Utilities.Log("Number of locks applied to the network (including its subnets): " + lockCount);
// Locks can be retrieved using their ID
lockVM = azure.ManagementLocks.GetById(lockVM.Id);
lockGroup = azure.ManagementLocks.GetByResourceGroup(resourceGroup.Name, "rglock");
lockStorage = azure.ManagementLocks.GetById(lockStorage.Id);
lockDiskRO = azure.ManagementLocks.GetById(lockDiskRO.Id);
lockDiskDel = azure.ManagementLocks.GetById(lockDiskDel.Id);
lockSubnet = azure.ManagementLocks.GetById(lockSubnet.Id);
// Show the locks
Utilities.Print(lockGroup);
Utilities.Print(lockVM);
Utilities.Print(lockDiskDel);
Utilities.Print(lockDiskRO);
Utilities.Print(lockStorage);
Utilities.Print(lockSubnet);
// List all locks within a subscription
var locksSubscription = azure.ManagementLocks.List();
Utilities.Log("Total number of locks within this subscription: " + locksSubscription.Count());
}
finally
{
try
{
// Clean up (remember to unlock resources before deleting the resource group)
azure.ManagementLocks.DeleteByIds(
lockGroup.Id,
lockVM.Id,
lockDiskRO.Id,
lockDiskDel.Id,
lockStorage.Id,
lockSubnet.Id);
Utilities.Log("Starting the deletion of the resource group: " + rgName);
azure.ResourceGroups.BeginDeleteByName(rgName);
}
catch (NullReferenceException)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure);
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
}