Skip to content

New cmdlet Invoke-AzVmPatchAssessment #12658

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 11 commits into from
Aug 14, 2020
Merged
21 changes: 20 additions & 1 deletion src/Compute/Compute.Test/ScenarioTests/ComputeTestCommon.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -670,7 +670,9 @@ function Get-ResourceProviderLocation

function Get-ComputeVMLocation
{
Get-Location "Microsoft.Compute" "virtualMachines" "East US";
$result = Get-Location "Microsoft.Compute" "virtualMachines" "East US";
$result = $result.Replace(' ', '');
return $result
}

function Get-ComputeAvailabilitySetLocation
Expand Down Expand Up @@ -777,3 +779,20 @@ function Get-VMImageVersion {
-Offer $offer `
-Skus $sku | Sort-Object -Descending Version | select -First 1).Version
}


<#
.SYNOPSIS
Gets a sku that is available for the location, subscription, and resourceType
#>
function Get-AvailableSku
{
param([string] $location, [string] $resourceType)

$res = get-azcomputeresourcesku $location | where-object ResourceType -match $resourceType
$res = $res.where({$_.restrictions.count -eq 0})
if ($resourceType -match "virtualmachine"){
$res = $res.where({$_.Name -notmatch "Standard_B"})
}
return $res[0].Name
}
21 changes: 21 additions & 0 deletions src/Compute/Compute.Test/ScenarioTests/VirtualMachinePatchTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;


namespace Microsoft.Azure.Commands.Compute.Test.ScenarioTests
{
public class VirtualMachinePatchTests : ComputeTestRunner
{
public VirtualMachinePatchTests(Xunit.Abstractions.ITestOutputHelper output)
: base(output)
{
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestInvokeAzVmPatchAssessment()
{
TestRunner.RunTestScript("Test-InvokeAzVmPatchAssessment");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# ----------------------------------------------------------------------------------
#
# 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.
# ----------------------------------------------------------------------------------

<#
.SYNOPSIS
Test Invoke-AzVmPatchAssessment cmdlet
#>
function Test-InvokeAzVmPatchAssessment
{
# Setup
$rgname = Get-ComputeTestResourceName

try
{
# Common
$loc = Get-ComputeVMLocation;
$loc = $loc.Replace(' ', '');

New-AzResourceGroup -Name $rgname -Location $loc -Force;

# VM Profile & Hardware
$vmsize = Get-AvailableSku $loc "virtualMachine"
$vmname = 'vm' + $rgname;

$p = New-AzVMConfig -VMName $vmname -VMSize $vmsize -Priority 'Low' -MaxPrice 0.1538;

# NRP
$subnet = New-AzVirtualNetworkSubnetConfig -Name ('subnet' + $rgname) -AddressPrefix "10.0.0.0/24";
$vnet = New-AzVirtualNetwork -Force -Name ('vnet' + $rgname) -ResourceGroupName $rgname -Location $loc -AddressPrefix "10.0.0.0/16" -Subnet $subnet;
$vnet = Get-AzVirtualNetwork -Name ('vnet' + $rgname) -ResourceGroupName $rgname;
$subnetId = $vnet.Subnets[0].Id;
$nic = New-AzNetworkInterface -Force -Name ('nic' + $rgname) -ResourceGroupName $rgname -Location $loc -SubnetId $subnetId
$nic = Get-AzNetworkInterface -Name ('nic' + $rgname) -ResourceGroupName $rgname;
$nicId = $nic.Id;

$p = Add-AzVMNetworkInterface -VM $p -Id $nicId;

# OS & Image
$user = "Foo2";
$password = $PLACEHOLDER;
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force;
$cred = New-Object System.Management.Automation.PSCredential ($user, $securePassword);
$computerName = 'test';

$p = Set-AzVMOperatingSystem -VM $p -Windows -ComputerName $computerName -Credential $cred;

$imgRef = Get-DefaultCRPImage -loc $loc;
$p = ($imgRef | Set-AzVMSourceImage -VM $p);

# Create a Virtual Machine
New-AzVM -ResourceGroupName $rgname -Location $loc -VM $p;

$patchResult = invoke-azvmpatchAssessment -resourcegroupname $rgname -vmname $vmname

Assert-NotNull $patchResult;
Assert-AreEqual "Succeeded" $patchResult.Status;
Assert-NotNull $patchResult.StartDateTime;

}
finally
{
# Cleanup
Clean-ResourceGroup $rgname
}
}

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/Compute/Compute/Az.Compute.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -168,14 +168,14 @@ CmdletsToExport = 'Remove-AzAvailabilitySet', 'Get-AzAvailabilitySet',
'Remove-AzHost', 'New-AzDiskEncryptionSetConfig',
'New-AzDiskEncryptionSet', 'Get-AzDiskEncryptionSet',
'Remove-AzDiskEncryptionSet', 'Update-AzDiskEncryptionSet',
'Set-AzVmssOrchestrationServiceState'
'Set-AzVmssOrchestrationServiceState', 'Invoke-AzVmPatchAssessment'

# Variables to export from this module
# VariablesToExport = @()

# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = 'Get-AzVmssDiskEncryptionStatus',
'Get-AzVmssVMDiskEncryptionStatus', 'Repair-AzVmssServiceFabricUD'
'Get-AzVmssVMDiskEncryptionStatus', 'Repair-AzVmssServiceFabricUD', 'Invoke-AzVmAssessPatch', 'Invoke-AzVmPatchAssess'

# DSC resources to export from this module
# DscResourcesToExport = @()
Expand Down
1 change: 1 addition & 0 deletions src/Compute/Compute/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
* Added '-EncryptionAtHost' parameter to New-AzVm, New-AzVmss, New-AzVMConfig, New-AzVmssConfig, Update-AzVM, and Update-AzVmss
* Added 'SecurityProfile' to Get-AzVM and Get-AzVmss return object
* Added the '-InstanceView' switch as optional parameter to Get-AzHostGroup
* New cmdlet 'Invoke-AzVmPatchAssessment'

## Version 4.2.1
* Added warning when using `New-AzVmss` without "latest" image version
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,8 @@ private static void Initialize()
.ForMember(c => c.Type, o => o.MapFrom(r => r.Type1));
cfg.CreateMap<TO.PSVirtualMachineScaleSetExtension, FROM.VirtualMachineScaleSetExtension>()
.ForMember(c => c.Type1, o => o.MapFrom(r => r.Type));
cfg.CreateMap<FROM.VirtualMachineAssessPatchesResult, TO.PSVirtualMachinePatchAssessmentResult>();
cfg.CreateMap<TO.PSVirtualMachinePatchAssessmentResult, FROM.VirtualMachineAssessPatchesResult>();
});
_mapper = config.CreateMapper();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// ----------------------------------------------------------------------------------
//
// 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.
// ----------------------------------------------------------------------------------


using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Commands.Compute.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.Azure.Management.Compute;

namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet(VerbsLifecycle.Invoke, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VMPatchAssessment", SupportsShouldProcess = true, DefaultParameterSetName = DefaultParameterSet )]
[OutputType(typeof(PSVirtualMachinePatchAssessmentResult))]
[Alias("Invoke-" + ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VMPatchAssess", "Invoke-" + ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VMAssessPatch")]

public partial class InvokeAzureVMPatchAssessmentCommand : ComputeAutomationBaseCmdlet
{
private const string DefaultParameterSet = "DefaultParameterSet";
private const string InputObjectParameterSet = "InputObjectParameterSet";
private const string ResourceIDParameterSet = "ResourceIDParameterSet";

[Parameter(
Mandatory = true,
Position = 0,
ParameterSetName = DefaultParameterSet,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ResourceGroupCompleter]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }

[Parameter(
Mandatory = true,
Position = 1,
ParameterSetName = DefaultParameterSet,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Virtual Machine name")]
[ResourceNameCompleter("Microsoft.Compute/VirtualMachines", "ResourceGroupName")]
public string VMName { get; set; }

[Parameter(
Mandatory = true,
Position = 0,
ParameterSetName = ResourceIDParameterSet,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Resource ID for your virtual machine.")]
[ResourceIdCompleter("Microsoft.Compute/virtualMachines")]
public string ResourceId { get; set; }

[Alias("VMProfile")]
[Parameter(
Mandatory = true,
Position = 0,
ParameterSetName = InputObjectParameterSet,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "PowerShell Virtual Machine Object")]
[ValidateNotNullOrEmpty]
public PSVirtualMachine VM { get; set; }

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

public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ExecuteClientAction(() =>
{
if (ShouldProcess(this.VMName, VerbsLifecycle.Invoke))
{
string resourceGroupName;
string vmName;
switch (this.ParameterSetName)
{
case ResourceIDParameterSet:
resourceGroupName = GetResourceGroupName(this.ResourceId);
vmName = GetResourceName(this.ResourceId, "Microsoft.Compute/virtualmachines");
break;
case InputObjectParameterSet:
resourceGroupName = GetResourceGroupName(this.VM.Id);
vmName = GetResourceName(this.VM.Id, "Microsoft.Compute/virtualmachines");
break;
default:
resourceGroupName = this.ResourceGroupName;
vmName = this.VMName;
break;
}


var result = VirtualMachinesClient.AssessPatches(resourceGroupName, vmName);
var psObject = new PSVirtualMachinePatchAssessmentResult();
ComputeAutomationAutoMapperProfile.Mapper.Map<VirtualMachineAssessPatchesResult, PSVirtualMachinePatchAssessmentResult>(result, psObject);
WriteObject(psObject);
}
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// 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.
//

using System;
using System.Collections.Generic;
using Microsoft.Azure.Management.Compute.Models;


namespace Microsoft.Azure.Commands.Compute.Automation.Models
{
public class PSVirtualMachinePatchAssessmentResult
{
public string Status { get; set; }
public string AssessmentActivityId { get; set; }
public bool? RebootPending { get; set; }
public int? CriticalAndSecurityPatchCount { get; set; }
public int? OtherPatchCount { get; set; }
public DateTime? StartDateTime { get; set; }
public IList<VirtualMachineSoftwarePatchProperties> Patches { get; set; }
public ApiError Error { get; set; }
}
}
3 changes: 3 additions & 0 deletions src/Compute/Compute/help/Az.Compute.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,9 @@ Grants an access to a disk.
### [Grant-AzSnapshotAccess](Grant-AzSnapshotAccess.md)
Grants an access to a snapshot.

### [Invoke-AzVMPatchAssessment](Invoke-AzVMPatchAssessment.md)
Assess patch state of a virtual machine.

### [Invoke-AzVMReimage](Invoke-AzVMReimage.md)
Reimage an Azure virtual machine.

Expand Down
Loading