Skip to content

Availability Set for VM simple parameter set #5307

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 7 commits into from
Feb 2, 2018
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 @@ -34,6 +34,10 @@ public static TValue GetOrNull<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary, TKey key)
where TValue : class
{
if (key == null)
{
return null;
}
TValue result;
dictionary.TryGetValue(key, out result);
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,20 @@ static async Task GetStateAsync<TModel>(
this StateOperationContext context, ResourceConfig<TModel> config)
where TModel : class
=> await context.GetOrAdd(
config,
async () =>
config,
async () =>
{
var info = await config.GetAsync(context.Client, context.CancellationToken);
// Get state of dependencies if the resource doesn't exist
if (info == null)
{
var info = await config.GetAsync(context.Client, context.CancellationToken);
// Get state of dependencies if the resource doesn't exist
if (info == null)
{
var tasks = config
.GetResourceDependencies()
.Select(context.GetStateAsyncDispatch);
await Task.WhenAll(tasks);
}
return info;
});
var tasks = config
.GetResourceDependencies()
.Select(context.GetStateAsyncDispatch);
await Task.WhenAll(tasks);
}
return info;
});

sealed class GetStateAsyncVisitor : IResourceConfigVisitor<StateOperationContext, Task>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ readonly ConcurrentDictionary<string, object> _Map

public TModel Get<TModel>(ResourceConfig<TModel> config)
where TModel : class
=> _Map.GetOrNull(config.DefaultIdStr()) as TModel;
=> _Map.GetOrNull(config?.DefaultIdStr()) as TModel;

public TModel GetOrAdd<TModel>(ResourceConfig<TModel> config, Func<TModel> f)
where TModel : class
Expand Down
5 changes: 3 additions & 2 deletions src/ResourceManager/Compute/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
- Additional information about change #1
-->
## Current Release
* Added `AvailabilitySetName` parameter to the simplified parameterset of `New-AzureRmVm`.
* Corrected usage of `Login-AzureRmAccount` to use `Connect-AzureRmAccount`

## Version 4.2.0
Expand Down Expand Up @@ -71,7 +72,7 @@
- New cmdelt: 'Get-AzureRmVmssVMDiskEncryptionStatus' shows the disk encryption status of VMs in a VM scale set

## Version 3.3.1
*
*
## Version 3.3.0
* Set-AzureRmVMAEMExtension: Add support for new Premium Disk sizes
* Set-AzureRmVMAEMExtension: Add support for M series
Expand All @@ -88,7 +89,7 @@
- New-AzureRmSnapshot
- Update-AzureRmDisk
- Update-AzureRmSnapshot

## Version 3.2.0
* Storage account type support for Image disk:
- 'StorageAccountType' parameter is added to Set-AzureRmImageOsDisk and Add-AzureRmImageDataDisk
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@
<Compile Include="StorageServices\StorageCredentialsFactory.cs" />
<Compile Include="Strategies\AsyncCmdletExtensions.cs" />
<Compile Include="Strategies\Client.cs" />
<Compile Include="Strategies\Compute\AvailabilitySetStrategy.cs" />
<Compile Include="Strategies\Compute\ComputeStrategy.cs" />
<Compile Include="Strategies\Compute\Image.cs" />
<Compile Include="Strategies\Compute\Images.cs" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Microsoft.Azure.Commands.Common.Strategies;
using Microsoft.Azure.Commands.Common.Strategies.Compute;
using Microsoft.Azure.Commands.Compute.Strategies.ResourceManager;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.Internal.Resources.Models;

namespace Microsoft.Azure.Commands.Compute.Strategies.Compute
{
static class AvailabilitySetStrategy
{
public static ResourceStrategy<AvailabilitySet> Strategy { get; }
= ComputePolicy.Create(
type: "availability set",
provider: "availabilitySets",
getOperations: client => client.AvailabilitySets,
getAsync: (o, p) => o.GetAsync(
p.ResourceGroupName, p.Name, p.CancellationToken),
createOrUpdateAsync: (o, p) => o.CreateOrUpdateAsync(
p.ResourceGroupName, p.Name, p.Model, p.CancellationToken),
createTime: c => 1);

public static ResourceConfig<AvailabilitySet> CreateAvailabilitySetConfig(
this ResourceConfig<ResourceGroup> resourceGroup, string name)
=> Strategy.CreateResourceConfig(
resourceGroup: resourceGroup,
name: name,
createModel: subscription => new AvailabilitySet
{
Sku = new Azure.Management.Compute.Models.Sku { Name = "Aligned" },
PlatformFaultDomainCount = 2,
PlatformUpdateDomainCount = 2,
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ static class VirtualMachineStrategy
p.ResourceGroupName, p.Name, null, p.CancellationToken),
createOrUpdateAsync: (o, p) => o.CreateOrUpdateAsync(
p.ResourceGroupName, p.Name, p.Model, p.CancellationToken),
createTime: c => c != null && c.OsProfile != null && c.OsProfile.WindowsConfiguration != null ? 240 : 120);
createTime: c =>
c != null && c.OsProfile != null && c.OsProfile.WindowsConfiguration != null
? 240
: 120);

public static ResourceConfig<VirtualMachine> CreateVirtualMachineConfig(
this ResourceConfig<ResourceGroup> resourceGroup,
Expand All @@ -41,7 +44,8 @@ public static ResourceConfig<VirtualMachine> CreateVirtualMachineConfig(
string adminUsername,
string adminPassword,
Image image,
string size)
string size,
ResourceConfig<AvailabilitySet> availabilitySet)
=> Strategy.CreateResourceConfig(
resourceGroup: resourceGroup,
name: name,
Expand Down Expand Up @@ -78,17 +82,24 @@ public static ResourceConfig<VirtualMachine> CreateVirtualMachineConfig(
Sku = image.sku,
Version = image.version
}
}
},
AvailabilitySet = availabilitySet == null
? null
: new Azure.Management.Compute.Models.SubResource
{
Id = availabilitySet.GetId(subscription).IdToString()
}
},
dependencies: new[] { networkInterface });
dependencies: new IResourceConfig[] { networkInterface, availabilitySet });

public static ResourceConfig<VirtualMachine> CreateVirtualMachineConfig(
this ResourceConfig<ResourceGroup> resourceGroup,
string name,
ResourceConfig<NetworkInterface> networkInterface,
bool isWindows,
ResourceConfig<Disk> disk,
string size)
string size,
ResourceConfig<AvailabilitySet> availabilitySet)
=> Strategy.CreateResourceConfig(
resourceGroup: resourceGroup,
name: name,
Expand Down Expand Up @@ -123,7 +134,13 @@ public static ResourceConfig<VirtualMachine> CreateVirtualMachineConfig(
}
}
},
AvailabilitySet = availabilitySet == null
? null
: new Azure.Management.Compute.Models.SubResource
{
Id = availabilitySet.GetId(subscription).IdToString()
}
},
dependencies: new IEntityConfig[] { networkInterface, disk });
dependencies: new IEntityConfig[] { networkInterface, disk, availabilitySet });
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@
using Microsoft.Azure.Commands.Compute.Models;
using Microsoft.Azure.Commands.Compute.StorageServices;
using Microsoft.Azure.Commands.Compute.Strategies;
using Microsoft.Azure.Commands.Compute.Strategies.Compute;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.Storage;
using Microsoft.Azure.Management.Storage.Models;
using Microsoft.Rest.Azure;
using Microsoft.WindowsAzure.Commands.Sync.Download;
using Microsoft.WindowsAzure.Commands.Tools.Vhd;
using Microsoft.WindowsAzure.Commands.Tools.Vhd.Model;
Expand Down Expand Up @@ -201,6 +203,10 @@ public class NewAzureVMCommand : VirtualMachineBaseCmdlet
[Parameter(ParameterSetName = DiskFileParameterSet, Mandatory = false)]
public string Size { get; set; } = "Standard_DS1_v2";

[Parameter(ParameterSetName = SimpleParameterSet, Mandatory = false)]
[Parameter(ParameterSetName = DiskFileParameterSet, Mandatory = false)]
public string AvailabilitySetName { get; set; }

[Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")]
public SwitchParameter AsJob { get; set; }

Expand Down Expand Up @@ -285,8 +291,12 @@ async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet)
openPorts: OpenPorts);
var networkInterface = resourceGroup.CreateNetworkInterfaceConfig(
Name, subnet, publicIpAddress, networkSecurityGroup);
ResourceConfig<VirtualMachine> virtualMachine = null;

var availabilitySet = AvailabilitySetName == null
? null
: resourceGroup.CreateAvailabilitySetConfig(name: Name);

ResourceConfig<VirtualMachine> virtualMachine = null;
if (image != null)
{
virtualMachine = resourceGroup.CreateVirtualMachineConfig(
Expand All @@ -296,7 +306,8 @@ async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet)
adminUsername: Credential.UserName,
adminPassword: new NetworkCredential(string.Empty, Credential.Password).Password,
image: image,
size: Size);
size: Size,
availabilitySet: availabilitySet);
}
else
{
Expand Down Expand Up @@ -325,24 +336,35 @@ async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet)
Math.DivRem(filePath.Length, divisor, out rem);
if (rem != 0)
{
throw new ArgumentOutOfRangeException("filePath", string.Format("Given vhd file '{0}' is a corrupted fixed vhd", filePath));
throw new ArgumentOutOfRangeException(
"filePath",
string.Format("Given vhd file '{0}' is a corrupted fixed vhd", filePath));
}
}
}
var storageAccount = storageClient.StorageAccounts.GetProperties(ResourceGroupName, Name);
BlobUri destinationUri = null;
BlobUri.TryParseUri(new Uri(string.Format("{0}{1}/{2}{3}", storageAccount.PrimaryEndpoints.Blob, Name.ToLower(), Name.ToLower(), ".vhd")), out destinationUri);
BlobUri.TryParseUri(
new Uri(string.Format(
"{0}{1}/{2}{3}",
storageAccount.PrimaryEndpoints.Blob,
Name.ToLower(),
Name.ToLower(),
".vhd")),
out destinationUri);
if (destinationUri == null || destinationUri.Uri == null)
{
throw new ArgumentNullException("destinationUri");
}
var storageCredentialsFactory = new StorageCredentialsFactory(this.ResourceGroupName, storageClient, DefaultContext.Subscription);
var storageCredentialsFactory = new StorageCredentialsFactory(
this.ResourceGroupName, storageClient, DefaultContext.Subscription);
var parameters = new UploadParameters(destinationUri, null, filePath, true, 2)
{
Cmdlet = this,
BlobObjectFactory = new CloudPageBlobObjectFactory(storageCredentialsFactory, TimeSpan.FromMinutes(1))
};
if (!string.Equals(Environment.GetEnvironmentVariable("AZURE_TEST_MODE"), "Playback", StringComparison.OrdinalIgnoreCase))
if (!string.Equals(
Environment.GetEnvironmentVariable("AZURE_TEST_MODE"), "Playback", StringComparison.OrdinalIgnoreCase))
{
var st2 = VhdUploaderModel.Upload(parameters);
}
Expand All @@ -355,7 +377,8 @@ async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet)
networkInterface: networkInterface,
isWindows: isWindows,
disk: disk,
size: Size);
size: Size,
availabilitySet: availabilitySet);
}

var client = new Client(DefaultProfile.DefaultContext);
Expand All @@ -375,7 +398,12 @@ async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet)
var fqdn = DomainNameLabel + "." + Location + ".cloudapp.azure.com";

// create target state
var target = virtualMachine.GetTargetState(current, client.SubscriptionId, Location);
var target = virtualMachine.GetTargetState(current, client.SubscriptionId, Location);

if (target.Get(availabilitySet) != null)
{
throw new InvalidOperationException("Availability set doesn't exist.");
}

// apply target state
var newState = await virtualMachine
Expand Down