Skip to content
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

Add DSC class-based resource BootstrapPSResourceGet #14

Merged
merged 21 commits into from
Feb 18, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- DSC class-based resource `BootstrapPSResourceGet'.

### Fixed

- Reverted resolve dependency logic so that GitHub actions works.
Expand Down
2 changes: 2 additions & 0 deletions RequiredModules.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,15 @@
#xDscResourceDesigner = 'latest'

# Build dependencies needed for using the module
'DscResource.Base' = 'latest'
#'DscResource.Common' = 'latest'
'DscResource.Common' = @{
Version = 'latest'
Parameters = @{
AllowPrerelease = $true
}
}

# Analyzer rules
'DscResource.AnalyzerRules' = 'latest'
'Indented.ScriptAnalyzerRules' = 'latest'
Expand Down
8 changes: 8 additions & 0 deletions build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,12 @@ NestedModule:
AddToManifest: false
Exclude: PSGetModuleInfo.xml

DscResource.Base:
CopyOnly: true
Path: ./output/RequiredModules/DscResource.Base
AddToManifest: false
Exclude: PSGetModuleInfo.xml

####################################################
# Pester Configuration (Sampler) #
####################################################
Expand All @@ -143,6 +149,7 @@ Pester:
OutputEncoding: ascii
ExcludeFromCodeCoverage:
- Modules/DscResource.Common
- Modules/DscResource.Base

####################################################
# Pester Configuration (DscResource.Test) #
Expand All @@ -166,6 +173,7 @@ DscTest:
- output
ExcludeModuleFile:
- Modules/DscResource.Common
- Modules/DscResource.Base
# Must exclude built module file because it should not be tested like MOF-based resources
- PSResourceGet.Bootstrap.psm1
MainGitBranch: main
Expand Down
265 changes: 265 additions & 0 deletions source/Classes/020.BootstrapPSResourceGet.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
<#
.SYNOPSIS
The `BootstrapPSResourceGet` DSC resource is used to bootstrap the module
Microsoft.PowerShell.PSResourceGet to the specified location.

.DESCRIPTION
The `BootstrapPSResourceGet` DSC resource is used to bootstrap the module
Microsoft.PowerShell.PSResourceGet to the specified location.

It supports two parameter sets: 'Destination' and 'Scope'. The 'Destination'
parameter set allows you to specify a specific location to save the module,
while the 'Scope' parameter set saves the module to the appropriate `$env:PSModulePath`
location based on the specified scope ('CurrentUser' or 'AllUsers').

The built-in parameter **PSDscRunAsCredential** can be used to run the resource
as another user.

## Requirements

* Target machine must be running a operating system supporting running
class-based DSC resources.
* Target machine must support running Microsoft.PowerShell.PSResourceGet.

## Known issues

All issues are not listed here, see [here for all open issues](https://github.com/viscalyx/PSResourceGet.Bootstrap/issues?q=is%3Aissue+is%3Aopen+in%3Atitle+BootstrapPSResourceGet).

### Property **Reasons** does not work with **PSDscRunAsCredential**

When using the built-in parameter **PSDscRunAsCredential** the read-only
property **Reasons** will return empty values for the properties **Code**
and **Phrase. The built-in property **PSDscRunAsCredential** does not work
together with class-based resources that using advanced type like the parameter
**Reasons** have.

.PARAMETER IsSingleInstance
Specifies that only a single instance of the resource can exist in one and
the same configuration. Must always be set to the value `Yes`.

.PARAMETER Destination
Specifies the destination path where the module should be saved. This parameter
is mandatory when using the 'Destination' parameter set. The path must be a valid
container. This parameter may not be used at the same time as the parameter Scope.

.PARAMETER Scope
Specifies the scope for saving the module. This parameter is used when using the
'Scope' parameter set. The valid values are 'CurrentUser' and 'AllUsers'. The
default value is 'CurrentUser'. This parameter may not be used at the same time
as the parameter Destination.

.PARAMETER Version
Specifies the version of the Microsoft.PowerShell.PSResourceGet module to download.
If not specified, the latest version will be downloaded.

.EXAMPLE
Invoke-DscResource -ModuleName PSResourceGet.Bootstrap -Name BootstrapPSResourceGet -Method Get -Property @{
IsSingleInstance = 'Yes'
Scope = 'CurrentUser'
}

This example shows how to call the resource using Invoke-DscResource. This
example bootstraps the Microsoft.PowerShell.PSResourceGet module, saving
it to the appropriate location based on the default scope ('CurrentUser').
It will also save the compatibility module to the same location.
#>
[DscResource(RunAsCredential = 'Optional')]
class BootstrapPSResourceGet : ResourceBase
{
[DscProperty(Key)]
Dismissed Show dismissed Hide dismissed
[SingleInstance]
$IsSingleInstance

# [DscProperty(Key)]
# [ValidateSet('Yes')]
# [System.String]
# $IsSingleInstance

# The Destination is evaluated if exist in AssertProperties().
[DscProperty()]
[System.String]
$Destination

# The Scope is evaluated if exist in AssertProperties().
[DscProperty()]
[ValidateSet('CurrentUser', 'AllUsers')]
[System.String]
$Scope

# The Version is evaluated if exist in AssertProperties().
[DscProperty()]
[System.String]
$Version

BootstrapPSResourceGet () : base ()
{
# These properties will not be enforced.
$this.ExcludeDscProperties = @(
'IsSingleInstance'
)
}

[BootstrapPSResourceGet] Get()
{
# Call the base method to return the properties.
return ([ResourceBase] $this).Get()
}

[System.Boolean] Test()
{
# Call the base method to test all of the properties that should be enforced.
return ([ResourceBase] $this).Test()
}

[void] Set()
{
# Call the base method to enforce the properties.
([ResourceBase] $this).Set()
}

<#
Base method Get() call this method to get the current state as a hashtable.
The parameter keyProperty will contain the key properties.
#>
hidden [System.Collections.Hashtable] GetCurrentState([System.Collections.Hashtable] $keyProperty)
{
Write-Verbose -Message $this.localizedData.EvaluateModule

$currentState = @{}

# Need to find out how to evaluate state since there are no key properties for that.
$assignedDscProperties = $this | Get-DscProperty -HasValue -Attribute @(
'Mandatory'
'Optional'
)

$testModuleExistParameters = @{
Name = 'Microsoft.PowerShell.PSResourceGet'
}

if ($assignedDscProperties.Keys -contains 'Version')
{
$testModuleExistParameters.Version = $assignedDscProperties.Version

$currentState.Version = ''
}

# If it is scope wasn't specified, then destination was specified.
if ($assignedDscProperties.Keys -contains 'Scope')
{
Write-Verbose -Message (
$this.localizedData.EvaluatingScope -f $assignedDscProperties.Scope
)

$currentState.Scope = ''

$testModuleExistParameters.Scope = $assignedDscProperties.Scope

if ((Test-ModuleExist @testModuleExistParameters -ErrorAction 'Stop'))
{
$currentState.Scope = $assignedDscProperties.Scope

if ($assignedDscProperties.Keys -contains 'Version')
{
$currentState.Version = $assignedDscProperties.Version
}
}
}
else
{
Write-Verbose -Message (
$this.localizedData.EvaluatingDestination -f $assignedDscProperties.Destination
)

$currentState.Destination = ''

$testModuleExistParameters.Destination = $assignedDscProperties.Destination

if ((Test-ModuleExist @testModuleExistParameters -ErrorAction 'Stop'))
{
$currentState.Destination = $assignedDscProperties.Destination

if ($assignedDscProperties.Keys -contains 'Version')
{
$currentState.Version = $assignedDscProperties.Version
}
}
}

return $currentState
}

<#
Base method Set() call this method with the properties that should be
enforced are not in desired state. It is not called if all properties
are in desired state. The variable $property contain the properties
that are not in desired state.
#>
hidden [void] Modify([System.Collections.Hashtable] $property)
{
Write-Verbose -Message $this.localizedData.Bootstrapping

Write-Debug -Message "Start-PSResourceGetBootstrap Parameters:`n$($property | Out-String)"

Start-PSResourceGetBootstrap @property -Force -ErrorAction 'Stop'
}

<#
Base method Assert() call this method with the properties that was assigned
a value.
#>
hidden [void] AssertProperties([System.Collections.Hashtable] $property)
{
# The properties Scope and Destination are mutually exclusive.
$assertBoundParameterParameters = @{
BoundParameterList = $property
MutuallyExclusiveList1 = @(
'Scope'
)
MutuallyExclusiveList2 = @(
'Destination'
)
}

Assert-BoundParameter @assertBoundParameterParameters

if ($property.Keys -contains 'Scope')
{
$scopeModulePath = Get-PSModulePath -Scope $property.Scope

if (-not (Test-Path -Path $scopeModulePath))
{
$errorMessage = $this.localizedData.ScopePathInvalid -f $property.Scope, $scopeModulePath

New-InvalidArgumentException -ArgumentName 'Scope' -Message $errorMessage
}
}

if ($property.Keys -contains 'Destination')
{
if (-not (Test-Path -Path $property.Destination))
{
$errorMessage = $this.localizedData.DestinationInvalid -f $property.Destination

New-InvalidArgumentException -ArgumentName 'Destination' -Message $errorMessage
}
}

if ($property.Keys -contains 'Version')
{
$isValidVersion = (
# From https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
$property.Version -match '^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$' -or
# Need to support the Nuget range syntax as well.
$property.Version -match '^[\[(][0-9\.\,]*[\])]$'
)

if (-not $isValidVersion)
{
$errorMessage = $this.localizedData.VersionInvalid -f $property.Version

New-InvalidArgumentException -ArgumentName 'Version' -Message $errorMessage
}
}
}
}
4 changes: 4 additions & 0 deletions source/Enum/SingleInstance.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
enum SingleInstance
{
Yes
}
20 changes: 20 additions & 0 deletions source/en-US/BootstrapPSResourceGet.strings.psd1
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<#
.SYNOPSIS
The localized resource strings in English (en-US) for the
resource BootstrapPSResourceGet.
#>

# cSpell: ignore BPSRG
ConvertFrom-StringData @'
## Strings overrides for the ResourceBase's default strings.
# None

## Strings directly used by the derived class BootstrapPSResourceGet.
EvaluateModule = Evaluate if the module Microsoft.PowerShell.PSResourceGet is present. (BPSRG0001)
DestinationInvalid = The destination path '{0}' does not exist. (BPSRG0002)
ScopePathInvalid = The path '{1}' that was returned for the scope '{0}' does not exist. (BPSRG0003)
EvaluatingScope = Evaluation if module is present in the scope '{0}'. (BPSRG0004)
EvaluatingDestination = Evaluating if module is present in the destination path '{0}'. (BPSRG0006)
VersionInvalid = The version '{0}' is not a valid semantic version or one of the supported NuGet version ranges. (BPSRG0007)
Bootstrapping = Bootstrapping the module Microsoft.PowerShell.PSResourceGet. (BPSRG0008)
'@
2 changes: 2 additions & 0 deletions source/prefix.ps1
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using module .\Modules\DscResource.Base

$script:dscResourceCommonModulePath = Join-Path -Path $PSScriptRoot -ChildPath 'Modules/DscResource.Common'
Import-Module -Name $script:dscResourceCommonModulePath

Expand Down
Loading