Skip to content

Commit

Permalink
Support for PowerShell 7 added (#156)
Browse files Browse the repository at this point in the history
* Removed PS5 check

* Fixed test when there is no 'TestRsopReference' folder

* Adding `Sampler.DscPipeline`

* Exceptions inside `Get-FilteredConfigurationData` have not been catched

* Should stop then `Get-DatumNodesRecursive` does not return anything.

* Improved error handling

* Added 'PSDesiredStateConfiguration' and removed temporarily 'Sampler.DscPipeline'

* Added init task to remove PSDesiredStateConfiguration > 2 if PS5 is used

* Another improvement to error handling on PS7

* Where extension method always returns a collection

* Added JeaDsc as current version does not work with PS7

* b640ba3: Added JeaDsc as current version does not work with PS7 #2

* Added `JeaDsc` back to the requirements, otherwise tests will fail

* Work in progress

* work in progress

* Work in progress

* Work in progress

* Work in progress

* Removed Init task

* Added 'PSDesiredStateConfiguration'

* Added 'JeaDsc' and 'Sampler.DscPipeline'

* Fixed version of 'PSDesiredStateConfiguration'

* Removed reference configs and fixed test

* Removed 'CmdletsToExport'

* Exclude 'JeaDsc' for now as it is not fully compatible with PowerShell 7

* Skipping test as `JeaDsc` is removed from `RequiredModules.psd1`

* Added task `PowerShell5Compatibility`

* PowerShell7 compatibility

* Removed PSModulePath manipulation

* Improved error handling to work on PowerShell 7

* Removed `Sampler.DscPipeline` from `RequiredModules.psd1`

* Adding ProtectedData dependency to this repo

* Updated ProtectedData for PowerShell 7

* Changed version of ProtectedData

* Added task 'PowerShell5Compatibility' to 'pack'

* Added a job for testing build on PowerShell 7

* Fixed artefact name collision

* Removed JeaDsc files

* Added JeaDsc back as a dependency

* Updated changelog

* Removed JeaDsc as v4.0.0+ is PowerShell 7 compatible
  • Loading branch information
raandree authored May 23, 2023
1 parent 61aa962 commit f4c9311
Show file tree
Hide file tree
Showing 50 changed files with 5,122 additions and 45 deletions.
7 changes: 7 additions & 0 deletions .build/PowerShell5Compatibility.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
task PowerShell5Compatibility -if ($PSVersionTable.PSEdition -eq 'Desktop') {

Remove-Item -Path $requiredModulesPath\PSDesiredStateConfiguration -ErrorAction SilentlyContinue -Recurse -Force
Write-Warning "'PSDesiredStateConfiguration' > 2.0 module is not supported on Windows PowerShell and not required for DSC compilation."
Write-Warning "'PSDesiredStateConfiguration' was removed from the 'RequiredModules' folder."

}
131 changes: 131 additions & 0 deletions .build/gcTasks.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
param
(
[Parameter()]
[System.String]
$ProjectName = (property ProjectName ''),

[Parameter()]
[System.String]
$SourcePath = (property SourcePath ''),

[Parameter()]
[System.String]
$GCPackagesPath = (property GCPackagesPath 'GCPackages'),

[Parameter()]
[System.String]
$GCPackagesOutputPath = (property GCPackagesOutputPath 'GCPackages'),

[Parameter()]
[System.String]
$GCPoliciesPath = (property GCPoliciesPath 'GCPolicies'),

[Parameter()]
[System.String]
$OutputDirectory = (property OutputDirectory (Join-Path $BuildRoot 'output')),

[Parameter()]
[System.String]
$BuiltModuleSubdirectory = (property BuiltModuleSubdirectory ''),

[Parameter()]
[System.String]
$BuildModuleOutput = (property BuildModuleOutput (Join-Path $OutputDirectory $BuiltModuleSubdirectory)),

[Parameter()]
[System.String]
$ModuleVersion = (property ModuleVersion ''),

[Parameter()]
[System.Collections.Hashtable]
$BuildInfo = (property BuildInfo @{ })
)

# SYNOPSIS: Building the Azure Policy Guest Configuration Packages
task build_guestconfiguration_packages_from_MOF {
# Get the vales for task variables, see https://github.com/gaelcolas/Sampler#task-variables.
. Set-SamplerTaskVariable -AsNewBuild

if (-not (Split-Path -IsAbsolute $GCPackagesPath))
{
$GCPackagesPath = Join-Path -Path $SourcePath -ChildPath $GCPackagesPath
}

if (-not (Split-Path -IsAbsolute $GCPoliciesPath))
{
$GCPoliciesPath = Join-Path -Path $SourcePath -ChildPath $GCPoliciesPath
}

"`tBuild Module Output = $BuildModuleOutput"
"`tGC Packages Path = $GCPackagesPath"
"`tGC Policies Path = $GCPoliciesPath"
"`t------------------------------------------------`r`n"

$mofPath = Join-Path -Path $OutputDirectory -ChildPath $MofOutputFolder
$mofFiles = Get-ChildItem -Path $mofPath -Filter '*.mof' -Recurse

$moduleVersion = '2.0.0'

foreach ($mofFile in $mofFiles)
{
$GCPackageName = $mofFile.BaseName
Write-Build DarkGray "Package Name '$GCPackageName' with Configuration '$MOFFile', OutputDirectory $OutputDirectory, GCPackagesOutputPath '$GCPackagesOutputPath'."
$GCPackageOutput = Get-SamplerAbsolutePath -Path $GCPackagesOutputPath -RelativeTo $OutputDirectory

$NewGCPackageParams = @{
Configuration = $mofFile.FullName
Name = $mofFile.BaseName
Path = $GCPackageOutput
Force = $true
Version = $ModuleVersion
Type = 'AuditAndSet'
}

foreach ($paramName in (Get-Command -Name 'New-GuestConfigurationPackage' -ErrorAction Stop).Parameters.Keys.Where({ $_ -in $newPackageExtraParams.Keys }))
{
Write-Verbose -Message "`t Testing for parameter '$paramName'."
Write-Build DarkGray "`t`t Using configured parameter '$paramName' with value '$($newPackageExtraParams[$paramName])'."
# Override the Parameters from the $GCPackageName.psd1
$NewGCPackageParams[$paramName] = $newPackageExtraParams[$paramName]
}

$ZippedGCPackage = (& {
New-GuestConfigurationPackage @NewGCPackageParams
} 2>&1).Where{
if ($_ -isnot [System.Management.Automation.ErrorRecord])
{
# Filter out the Error records from New-GuestConfigurationPackage
$true
}
elseif ($_.Exception.Message -notmatch '^A second CIM class definition')
{
# Write non-terminating errors that are not "A second CIM class definition for .... was found..."
$false
Write-Error $_ -ErrorAction Continue
}
else
{
$false
}
}

Write-Build DarkGray "`t Zips created, you may want to delete the unzipped folders under '$GCPackagesOutputPath'..."

if ($ModuleVersion)
{
$GCPackageWithVersionZipName = ('{0}_{1}.zip' -f $GCPackageName, $ModuleVersion)
$GCPackageOutputPath = Get-SamplerAbsolutePath -Path $GCPackagesOutputPath -RelativeTo $OutputDirectory
$versionedGCPackageName = Join-Path -Path $GCPackageOutputPath -ChildPath $GCPackageWithVersionZipName
Write-Build DarkGray "`t Renaming Zip as '$versionedGCPackageName'."
$ZippedGCPackagePath = Move-Item -Path $ZippedGCPackage.Path -Destination $versionedGCPackageName -Force -PassThru
$ZippedGCPackage = @{
Name = $ZippedGCPackage.Name
Path = $ZippedGCPackagePath.FullName
}
}

Write-Build Green "`tZipped Guest Config Package: $($ZippedGCPackage.Path)"
}
}

task gcpack clean, build, build_guestconfiguration_packages
10 changes: 9 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
output/
!output/

output/*
!output/RequiredModules

output/RequiredModules/*

!output/RequiredModules/Sampler.DscPipeline
!output/RequiredModules/ProtectedData
63 changes: 63 additions & 0 deletions .work/GcTest1.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
Set-AzContext -SubscriptionName 'S1 Contoso3'
$subscriptionId = (Get-AzContext).Subscription.Id

$resourceGroupName = 'GCLab1'
$storageAccountName = "$($resourceGroupName)sa1".ToLower()
$resourceGroup = Get-AzResourceGroup -Name $resourceGroupName
$guestConfigurationContainerName = 'guestconfiguration'

New-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName -Location $resourceGroup.Location -SkuName Standard_LRS -Kind StorageV2 -ErrorAction SilentlyContinue | Out-Null
$storageAccountKeys = Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName
$storageContext = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKeys[0].Value
New-AzStorageContainer -Context $storageContext -Name guestconfiguration -Permission Blob -ErrorAction SilentlyContinue
$moduleVersion = '2.0.0'

$managedIdentity = Get-AzUserAssignedIdentity -ResourceGroupName $resourceGroupName -Name GCLab1_Remediation

$gpPackages = Get-ChildItem -Path 'D:\DscWorkshop\output\GCPackages' -Filter '*.zip' -Recurse
foreach ($gpPackage in $gpPackages)
{
$policyName = $gpPackage.BaseName.Split('_')[0]

Set-AzStorageBlobContent -Container $guestConfigurationContainerName -File $gpPackage.FullName -Blob $gpPackage.Name -Context $storageContext -Force

$contentUri = New-AzStorageBlobSASToken -Context $storageContext -FullUri -Container $guestConfigurationContainerName -Blob $gpPackage.Name -Permission rwd

$params = @{
PolicyId = New-Guid
ContentUri = $contentUri
DisplayName = $policyName
Description = 'none'
Path = 'd:\dscworkshop\output\GPPolicies'
Platform = 'Windows'
PolicyVersion = $moduleVersion
Mode = 'ApplyAndAutoCorrect'
Verbose = $true
}

$policy = New-GuestConfigurationPolicy @params

$policyDefinition = New-AzPolicyDefinition -Name $policyName -Policy $Policy.Path

$vm = Get-AzVM -Name $policyName -ResourceGroupName $resourceGroupName

$param = @{
Name = $policyName
DisplayName = $policyDefinition.Properties.DisplayName
Scope = $vm.Id
PolicyDefinition = $policyDefinition
Location = 'uksouth'
IdentityType = 'UserAssigned'
IdentityId = $managedIdentity.Id
}
$assignment = New-AzPolicyAssignment @param

$param = @{
Name = "$($policyName)Remediation"
PolicyAssignmentId = $assignment.PolicyAssignmentId
Scope = $vm.Id
ResourceDiscoveryMode = 'ReEvaluateCompliance'
}
Start-AzPolicyRemediation @param

}
14 changes: 14 additions & 0 deletions .work/temp.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#Get-AzPolicyAssignment -Scope $resourceGroup.ResourceId

$uri = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Compute/virtualMachines/$machineName/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments?api-version=2022-01-25"
$uri = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments?api-version=2022-01-25"
Invoke-AzRestMethod -Method GET -Uri $uri | Select-Object -ExpandProperty content | ConvertFrom-Json |
Select-Object -ExpandProperty value |
Format-Table name, @{n = 'assignmentType'; e = { $PSItem.properties.guestConfiguration.assignmentType } }, @{n = 'lastComplianceStatusChecked'; e = { $PSItem.properties.lastComplianceStatusChecked } }#,@{n='configurationSetting';e={$PSItem.properties.guestConfiguration.configurationSetting}}

# Assign policy to resource group containing Azure Arc lab servers
$ResourceGroup = Get-AzResourceGroup -Name 'azure-jumpstart-arcbox-rg'
$Policy = Get-AzPolicyDefinition | Where-Object { $PSItem.Properties.DisplayName -eq '[Windows]Ensure 7-Zip is installed' }
$PolicyParameterObject = @{'IncludeArcMachines' = 'True' } # <- IncludeArcMachines is important - given you want to target Arc as well as Azure VMs

New-AzPolicyAssignment -Name '[Windows]Ensure 7-Zip is installed' -PolicyDefinition $Policy -Scope $ResourceGroup.ResourceId -PolicyParameterObject $PolicyParameterObject -IdentityType SystemAssigned -Location westeurope -DisplayName '[Windows]Ensure7-Zip is installed'
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Migration to 'Sampler' and 'Sampler.DscPipeline'.
- Migration to Pester 5+.
- Changed from 'CommonTasks' to 'DscConfig.Demo' for faster build time.
- Added support for PowerShell 7.

### Fixed

Expand Down
7 changes: 4 additions & 3 deletions RequiredModules.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@
'Sampler.GitHubTasks' = '0.3.5-preview0002'
'Sampler.AzureDevOpsTasks' = '0.1.2'
PowerShellForGitHub = '0.16.1'
'Sampler.DscPipeline' = '0.2.0-preview0015'
#'Sampler.DscPipeline' = '0.2.0-preview0015'
MarkdownLinkCheck = '0.2.0'
'DscResource.AnalyzerRules' = '0.2.0'
DscBuildHelpers = '0.2.1'
Datum = '0.40.1-preview0001'
ProtectedData = '4.1.3'
#ProtectedData = '4.1.3'
'Datum.ProtectedData' = '0.0.1'
'Datum.InvokeCommand' = '0.3.0'
ReverseDSC = '2.0.0.14'
Expand All @@ -33,6 +33,7 @@
xDscResourceDesigner = '1.13.0.0'
'DscResource.Test' = '0.16.1'
'DscResource.DocGenerator' = '0.11.2'
PSDesiredStateConfiguration = '2.0.6'

# Composites
'DscConfig.Demo' = '0.8.3'
Expand All @@ -41,7 +42,7 @@
xPSDesiredStateConfiguration = '9.1.0'
ComputerManagementDsc = '9.0.0'
NetworkingDsc = '9.0.0'
JeaDsc = '0.7.2'
JeaDsc = '4.0.0-preview0005'
WebAdministrationDsc = '4.1.0'
FileSystemDsc = '1.1.1'
SecurityPolicyDsc = '2.10.0.0'
Expand Down
Loading

0 comments on commit f4c9311

Please sign in to comment.