forked from PowerShell/DSC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpowershell.resource.ps1
206 lines (182 loc) · 8.09 KB
/
powershell.resource.ps1
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
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0, HelpMessage = 'Operation to perform. Choose from List, Get, Set, Test, Export, Validate.')]
[ValidateSet('List', 'Get', 'Set', 'Test', 'Export', 'Validate', 'ClearCache')]
[string]$Operation,
[Parameter(Mandatory = $false, Position = 1, ValueFromPipeline = $true, HelpMessage = 'Configuration or resource input in JSON format.')]
[string]$jsonInput = '@{}'
)
function Write-DscTrace {
param(
[Parameter(Mandatory = $false)]
[ValidateSet('Error', 'Warn', 'Info', 'Debug', 'Trace')]
[string]$Operation = 'Debug',
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$Message
)
$trace = @{$Operation = $Message } | ConvertTo-Json -Compress
$host.ui.WriteErrorLine($trace)
}
# Adding some debug info to STDERR
'PSVersion=' + $PSVersionTable.PSVersion.ToString() | Write-DscTrace
'PSPath=' + $PSHome | Write-DscTrace
'PSModulePath=' + $env:PSModulePath | Write-DscTrace
if ($Operation -eq 'ClearCache') {
$cacheFilePath = if ($IsWindows) {
# PS 6+ on Windows
Join-Path $env:LocalAppData "dsc\PSAdapterCache.json"
} else {
# either WinPS or PS 6+ on Linux/Mac
if ($PSVersionTable.PSVersion.Major -le 5) {
Join-Path $env:LocalAppData "dsc\WindowsPSAdapterCache.json"
} else {
Join-Path $env:HOME ".dsc" "PSAdapterCache.json"
}
}
'Deleting cache file ' + $cacheFilePath | Write-DscTrace
Remove-Item -Force -ea SilentlyContinue -Path $cacheFilePath
exit 0
}
if ('Validate' -ne $Operation) {
# write $jsonInput to STDERR for debugging
$trace = @{'Debug' = 'jsonInput=' + $jsonInput } | ConvertTo-Json -Compress
$host.ui.WriteErrorLine($trace)
# load private functions of psDscAdapter stub module
if ($PSVersionTable.PSVersion.Major -le 5) {
$psDscAdapter = Import-Module "$PSScriptRoot/win_psDscAdapter.psd1" -Force -PassThru
}
else {
$psDscAdapter = Import-Module "$PSScriptRoot/psDscAdapter.psd1" -Force -PassThru
}
# initialize OUTPUT as array
$result = [System.Collections.Generic.List[Object]]::new()
}
if ($jsonInput) {
if ($jsonInput -ne '@{}') {
$inputobj_pscustomobj = $jsonInput | ConvertFrom-Json
}
$new_psmodulepath = $inputobj_pscustomobj.psmodulepath
if ($new_psmodulepath)
{
$env:PSModulePath = $ExecutionContext.InvokeCommand.ExpandString($new_psmodulepath)
}
}
# process the operation requested to the script
switch ($Operation) {
'List' {
$dscResourceCache = Invoke-DscCacheRefresh
# cache was refreshed on script load
foreach ($dscResource in $dscResourceCache) {
# https://learn.microsoft.com/dotnet/api/system.management.automation.dscresourceinfo
$DscResourceInfo = $dscResource.DscResourceInfo
# Provide a way for existing resources to specify their capabilities, or default to Get, Set, Test
# TODO: for perf, it is better to take capabilities from psd1 in Invoke-DscCacheRefresh, not by extra call to Get-Module
if ($DscResourceInfo.ModuleName) {
$module = Get-Module -Name $DscResourceInfo.ModuleName -ListAvailable | Sort-Object -Property Version -Descending | Select-Object -First 1
if ($module.PrivateData.PSData.DscCapabilities) {
$capabilities = $module.PrivateData.PSData.DscCapabilities
}
else {
$capabilities = @('Get', 'Set', 'Test')
}
}
# this text comes directly from the resource manifest for v3 native resources
if ($DscResourceInfo.Description) {
$description = $DscResourceInfo.Description
}
elseif ($module.Description) {
# some modules have long multi-line descriptions. to avoid issue, use only the first line.
$description = $module.Description.split("`r`n")[0]
}
else {
$description = ''
}
# match adapter to version of powershell
if ($PSVersionTable.PSVersion.Major -le 5) {
$requireAdapter = 'Microsoft.Windows/WindowsPowerShell'
}
else {
$requireAdapter = 'Microsoft.DSC/PowerShell'
}
# OUTPUT dsc is expecting the following properties
[resourceOutput]@{
type = $dscResource.Type
kind = 'Resource'
version = [string]$DscResourceInfo.version
capabilities = $capabilities
path = $DscResourceInfo.Path
directory = $DscResourceInfo.ParentPath
implementedAs = $DscResourceInfo.ImplementationDetail
author = $DscResourceInfo.CompanyName
properties = $DscResourceInfo.Properties.Name
requireAdapter = $requireAdapter
description = $description
} | ConvertTo-Json -Compress
}
}
{ @('Get','Set','Test','Export') -contains $_ } {
$desiredState = $psDscAdapter.invoke( { param($jsonInput) Get-DscResourceObject -jsonInput $jsonInput }, $jsonInput )
if ($null -eq $desiredState) {
$trace = @{'Debug' = 'ERROR: Failed to create configuration object from provided input JSON.' } | ConvertTo-Json -Compress
$host.ui.WriteErrorLine($trace)
exit 1
}
# only need to cache the resources that are used
$dscResourceModules = $desiredState | ForEach-Object { $_.Type.Split('/')[0] }
if ($null -eq $dscResourceModules) {
$trace = @{'Debug' = 'ERROR: Could not get list of DSC resource types from provided JSON.' } | ConvertTo-Json -Compress
$host.ui.WriteErrorLine($trace)
exit 1
}
# get unique module names from the desiredState input
$moduleInput = $desiredState | Select-Object -ExpandProperty Type | Sort-Object -Unique
# refresh the cache with the modules that are available on the system
$dscResourceCache = Invoke-DscCacheRefresh -module $dscResourceModules
# check if all the desired modules are in the cache
$moduleInput | ForEach-Object {
if ($dscResourceCache.type -notcontains $_) {
('DSC resource {0} module not found.' -f $_) | Write-DscTrace -Operation Error
exit 1
}
}
foreach ($ds in $desiredState) {
# process the INPUT (desiredState) for each resource as dscresourceInfo and return the OUTPUT as actualState
$actualState = $psDscAdapter.invoke( { param($op, $ds, $dscResourceCache) Invoke-DscOperation -Operation $op -DesiredState $ds -dscResourceCache $dscResourceCache }, $Operation, $ds, $dscResourceCache)
if ($null -eq $actualState) {
$trace = @{'Debug' = 'ERROR: Incomplete GET for resource ' + $ds.Name } | ConvertTo-Json -Compress
$host.ui.WriteErrorLine($trace)
exit 1
}
$result += $actualState
}
# OUTPUT json to stderr for debug, and to stdout
$result = @{ result = $result } | ConvertTo-Json -Depth 10 -Compress
$trace = @{'Debug' = 'jsonOutput=' + $result } | ConvertTo-Json -Compress
$host.ui.WriteErrorLine($trace)
return $result
}
'Validate' {
# VALIDATE not implemented
# OUTPUT
@{ valid = $true } | ConvertTo-Json
}
Default {
Write-Error 'Unsupported operation. Please use one of the following: List, Get, Set, Test, Export, Validate'
}
}
# output format for resource list
class resourceOutput {
[string] $type
[string] $kind
[string] $version
[string[]] $capabilities
[string] $path
[string] $directory
[string] $implementedAs
[string] $author
[string[]] $properties
[string] $requireAdapter
[string] $description
}