Debian Codegraph @

ansible_collections/community/windows/plugins/modules/win_psmodule.ps1

raw
1 #!powershell
2
3 # Copyright: (c) 2018, Wojciech Sciesinski <wojciech[at]sciesinski[dot]net>
4 # Copyright: (c) 2017, Daniele Lazzari <[email protected]>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 #AnsibleRequires -PowerShell ..module_utils._Tls
8 #Requires -Module Ansible.ModuleUtils.Legacy
9
10 # win_psmodule (Windows PowerShell modules Additions/Removals/Updates)
11
12 $params = Parse-Args -arguments $args -supports_check_mode $true
13 $check_mode = Get-AnsibleParam -obj $params -name "_ansible_check_mode" -type "bool" -default $false
14
15 $name = Get-AnsibleParam -obj $params -name "name" -type "str" -failifempty $true
16 $required_version = Get-AnsibleParam -obj $params -name "required_version" -type "str"
17 $minimum_version = Get-AnsibleParam -obj $params -name "minimum_version" -type "str"
18 $maximum_version = Get-AnsibleParam -obj $params -name "maximum_version" -type "str"
19 $repo = Get-AnsibleParam -obj $params -name "repository" -type "str"
20 $repo_user = Get-AnsibleParam -obj $params -name "username" -type "str"
21 $repo_pass = Get-AnsibleParam -obj $params -name "password" -type "str"
22 $state = Get-AnsibleParam -obj $params -name "state" -type "str" -default "present" -validateset "present", "absent", "latest"
23 $allow_clobber = Get-AnsibleParam -obj $params -name "allow_clobber" -type "bool" -default $false
24 $skip_publisher_check = Get-AnsibleParam -obj $params -name "skip_publisher_check" -type "bool" -default $false
25 $allow_prerelease = Get-AnsibleParam -obj $params -name "allow_prerelease" -type "bool" -default $false
26 $accept_license = Get-AnsibleParam -obj $params -name "accept_license" -type "bool" -default $false
27 $force = Get-AnsibleParam -obj $params -name "force" -type "bool" -default $false
28
29 $result = @{changed = $false
30 output = ""
31 nuget_changed = $false
32 repository_changed = $false
33 }
34
35 Enable-TlsProtocol
36
37 Function Install-NugetProvider {
38 Param(
39 [Bool]$CheckMode
40 )
41 $PackageProvider = Get-PackageProvider -ListAvailable | Where-Object { ($_.name -eq 'Nuget') -and ($_.version -ge "2.8.5.201") }
42 if (-not($PackageProvider)) {
43 try {
44 Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -WhatIf:$CheckMode | Out-Null
45 $result.changed = $true
46 $result.nuget_changed = $true
47 }
48 catch [ System.Exception ] {
49 $ErrorMessage = "Problems adding package provider: $($_.Exception.Message)"
50 Fail-Json $result $ErrorMessage
51 }
52 }
53 }
54
55 Function Install-PrereqModule {
56 Param(
57 [Switch]$TestInstallationOnly,
58 [bool]$AllowClobber,
59 [Bool]$CheckMode,
60 [bool]$AcceptLicense,
61 [string]$Repository
62 )
63
64 # Those are minimum required versions of modules.
65 $PrereqModules = @{
66 PackageManagement = '1.1.7'
67 PowerShellGet = '1.6.0'
68 }
69
70 $ExistingPrereqModule = Get-Module -Name @($PrereqModules.Keys) -ListAvailable |
71 Where-Object { $_.Version -ge $PreReqModules[$_.Name] } |
72 Select-Object -ExpandProperty Name -Unique
73 $toInstall = $PrereqModules.Keys |
74 Where-Object { $_ -notin $ExistingPrereqModule } |
75 Select-Object @{N = 'Name'; E = { $_ } }, @{N = 'Version'; E = { $PrereqModules[$_] } }
76
77 if ($TestInstallationOnly) {
78 -not [bool]$toInstall
79 }
80 elseif ($toInstall) {
81 $result.changed = $true
82 if ($CheckMode) {
83 $result.output = "Skipped check mode run on win_psmodule as the pre-reqs need upgrading"
84 Exit-Json $result
85 }
86
87 # Need to run this in another process as importing PackageManagement at
88 # the older version is irreversible (you cannot load the same dll at
89 # different versions). Start-Job runs in a new process so it can safely
90 # use the older version to install our pre-reqs.
91 # https://github.com/ansible-collections/community.windows/issues/487
92 $job = Start-Job -ScriptBlock {
93 $ErrorActionPreference = 'Stop'
94
95 if (-not (Get-PackageProvider -ListAvailable | Where-Object { ($_.name -eq 'Nuget') -and ($_.version -ge "2.8.5.201") }) ) {
96 Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force | Out-Null
97 }
98
99 $Repository = $using:Repository
100
101 foreach ($info in $using:ToInstall) {
102 $install_params = @{
103 Name = $info.Name
104 MinimumVersion = $info.Version
105 Force = $true
106 }
107 $installCmd = Get-Command -Name Install-Module
108 if ($installCmd.Parameters.ContainsKey('SkipPublisherCheck')) {
109 $install_params.SkipPublisherCheck = $true
110 }
111 if ($installCmd.Parameters.ContainsKey('AllowClobber')) {
112 $install_params.AllowClobber = $using:AllowClobber
113 }
114 if ($installCmd.Parameters.ContainsKey('AcceptLicense')) {
115 $install_params.AcceptLicense = $using:AcceptLicense
116 }
117 if ($Repository) {
118 $install_params.Repository = $Repository
119 }
120
121 Install-Module @install_params > $null
122 }
123 }
124
125 try {
126 $null = $job | Receive-Job -AutoRemoveJob -Wait -ErrorAction Stop
127 }
128 catch {
129 $ErrorMessage = "Problems adding a prerequisite module PackageManagement or PowerShellGet: $($_.Exception.Message)"
130 $result.exception = ($_ | Out-String) + "`r`n" + $_.ScriptStackTrace
131 Fail-Json $result $ErrorMessage
132 }
133 }
134 }
135
136 Function Get-PsModule {
137 Param(
138 [Parameter(Mandatory = $true)]
139 [String]$Name,
140 [String]$RequiredVersion,
141 [String]$MinimumVersion,
142 [String]$MaximumVersion
143 )
144
145 $ExistingModule = @{
146 Exists = $false
147 Version = ""
148 }
149
150 $ExistingModules = Get-Module -ListAvailable | Where-Object { ($_.name -eq $Name) }
151 $ExistingModulesCount = $($ExistingModules | Measure-Object).Count
152
153 if ( $ExistingModulesCount -gt 0 ) {
154
155 $ExistingModules | Add-Member -MemberType ScriptProperty -Name FullVersion -Value {
156 if ( $null -ne ( $this.PrivateData ) ) {
157 [String]"$($this.Version)-$(($this | Select-Object -ExpandProperty PrivateData).PSData.Prerelease)".TrimEnd('-')
158 }
159 else {
160 [String]"$($this.Version)"
161 }
162 }
163
164 if ( -not ($RequiredVersion -or
165 $MinimumVersion -or
166 $MaximumVersion) ) {
167
168 $ReturnedModule = $ExistingModules | Select-Object -First 1
169 }
170 elseif ( $RequiredVersion ) {
171 $ReturnedModule = $ExistingModules | Where-Object -FilterScript { $_.FullVersion -eq $RequiredVersion }
172 }
173 elseif ( $MinimumVersion -and $MaximumVersion ) {
174 $ReturnedModule = $ExistingModules |
175 Where-Object -FilterScript { $MinimumVersion -le $_.Version -and $MaximumVersion -ge $_.Version } |
176 Select-Object -First 1
177 }
178 elseif ( $MinimumVersion ) {
179 $ReturnedModule = $ExistingModules | Where-Object -FilterScript { $MinimumVersion -le $_.Version } | Select-Object -First 1
180 }
181 elseif ( $MaximumVersion ) {
182 $ReturnedModule = $ExistingModules | Where-Object -FilterScript { $MaximumVersion -ge $_.Version } | Select-Object -First 1
183 }
184 }
185
186 $ReturnedModuleCount = ($ReturnedModule | Measure-Object).Count
187
188 if ( $ReturnedModuleCount -eq 1 ) {
189 $ExistingModule.Exists = $true
190 $ExistingModule.Version = $ReturnedModule.FullVersion
191 }
192
193 $ExistingModule
194 }
195
196 Function Add-DefinedParameter {
197 Param (
198 [Parameter(Mandatory = $true)]
199 [Hashtable]$Hashtable,
200 [Parameter(Mandatory = $true)]
201 [String[]]$ParametersNames
202 )
203
204 ForEach ($ParameterName in $ParametersNames) {
205 $ParameterVariable = Get-Variable -Name $ParameterName -ErrorAction SilentlyContinue
206 if ( $ParameterVariable.Value -and $Hashtable.Keys -notcontains $ParameterName ) {
207 $Hashtable.Add($ParameterName, $ParameterVariable.Value)
208 }
209 }
210
211 $Hashtable
212 }
213
214 Function Install-PsModule {
215 Param(
216 [Parameter(Mandatory = $true)]
217 [String]$Name,
218 [String]$RequiredVersion,
219 [String]$MinimumVersion,
220 [String]$MaximumVersion,
221 [String]$Repository,
222 [System.Management.Automation.PSCredential]$Credential = [System.Management.Automation.PSCredential]::Empty,
223 [Bool]$AllowClobber,
224 [Bool]$SkipPublisherCheck,
225 [Bool]$AllowPrerelease,
226 [Bool]$CheckMode,
227 [Bool]$AcceptLicense,
228 [Bool]$Force
229 )
230
231 $getParams = @{
232 Name = $Name
233 RequiredVersion = $RequiredVersion
234 MinimumVersion = $MinimumVersion
235 MaximumVersion = $MaximumVersion
236 }
237 $ExistingModuleBefore = Get-PsModule @getParams
238
239 if ( -not $ExistingModuleBefore.Exists ) {
240 try {
241 # Install NuGet provider if needed.
242 Install-NugetProvider -CheckMode $CheckMode
243
244 $ht = @{
245 Name = $Name
246 }
247
248 [String[]]$ParametersNames = @("RequiredVersion", "MinimumVersion", "MaximumVersion", "AllowPrerelease",
249 "Repository", "Credential")
250 $ht = Add-DefinedParameter -Hashtable $ht -ParametersNames $ParametersNames
251
252 # When module require License Acceptance, or repository is Untrusted.
253 # `-Force` is mandatory to skip interactive prompt
254 $psgetModuleInfo = Find-Module @ht
255 if (($psgetModuleInfo.AdditionalMetadata.requireLicenseAcceptance -eq "True") -or
256 ((Get-PSRepository -Name $psgetModuleInfo.Repository).InstallationPolicy -eq "Untrusted")) {
257 $ht["Force"] = $true
258 }
259 else {
260 $ht["Force"] = $Force
261 }
262
263 $ht = $ht + @{
264 WhatIf = $CheckMode
265 AcceptLicense = $AcceptLicense
266 }
267
268 [String[]]$ParametersNames = @("AllowClobber", "SkipPublisherCheck")
269 $ht = Add-DefinedParameter -Hashtable $ht -ParametersNames $ParametersNames
270
271 Install-Module @ht -ErrorVariable ErrorDetails | Out-Null
272
273 $result.changed = $true
274 $result.output = "Module $($Name) installed"
275 }
276 catch [ System.Exception ] {
277 $ErrorMessage = "Problems installing $($Name) module: $($_.Exception.Message)"
278 Fail-Json $result $ErrorMessage
279 }
280 }
281 else {
282 $result.output = "Module $($Name) already present"
283 }
284 }
285
286 Function Remove-PsModule {
287 Param(
288 [Parameter(Mandatory = $true)]
289 [String]$Name,
290 [String]$RequiredVersion,
291 [String]$MinimumVersion,
292 [String]$MaximumVersion,
293 [Bool]$CheckMode
294 )
295 # If module is present, uninstalls it.
296 if (Get-Module -ListAvailable | Where-Object { $_.name -eq $Name }) {
297 try {
298 $ht = @{
299 Name = $Name
300 Confirm = $false
301 Force = $true
302 }
303
304 $ExistingModuleBefore = Get-PsModule -Name $Name -RequiredVersion $RequiredVersion -MinimumVersion $MinimumVersion -MaximumVersion $MaximumVersion
305
306 [String[]]$ParametersNames = @("RequiredVersion", "MinimumVersion", "MaximumVersion")
307
308 $ht = Add-DefinedParameter -Hashtable $ht -ParametersNames $ParametersNames
309
310 if ( -not ( $RequiredVersion -or $MinimumVersion -or $MaximumVersion ) ) {
311 $ht.Add("AllVersions", $true)
312 }
313
314 if ( $ExistingModuleBefore.Exists) {
315 # The Force parameter overwrite the WhatIf parameter
316 if ( -not $CheckMode ) {
317 Uninstall-Module @ht -ErrorVariable ErrorDetails | Out-Null
318 }
319 $result.changed = $true
320 $result.output = "Module $($Name) removed"
321 }
322 }
323 catch [ System.Exception ] {
324 $ErrorMessage = "Problems uninstalling $($Name) module: $($_.Exception.Message)"
325 Fail-Json $result $ErrorMessage
326 }
327 }
328 else {
329 $result.output = "Module $($Name) removed"
330 }
331 }
332
333 Function Find-LatestPsModule {
334 Param(
335 [Parameter(Mandatory = $true)]
336 [String]$Name,
337 [String]$Repository,
338 [System.Management.Automation.PSCredential]$Credential = [System.Management.Automation.PSCredential]::Empty,
339 [Bool]$AllowPrerelease,
340 [Bool]$CheckMode
341 )
342
343 try {
344 $ht = @{
345 Name = $Name
346 }
347
348 [String[]]$ParametersNames = @("AllowPrerelease", "Repository", "Credential")
349
350 $ht = Add-DefinedParameter -Hashtable $ht -ParametersNames $ParametersNames
351
352 $LatestModule = Find-Module @ht | Select-Object Version
353 }
354 catch [ System.Exception ] {
355 $ErrorMessage = "Cant find the module $($Name): $($_.Exception.Message)"
356 Fail-Json $result $ErrorMessage
357 }
358
359 if ( $LatestModule.Version.GetType().FullName -eq 'System.Object[]' ) {
360 $ErrorMessage = "The module $Name exists in multiple repositories. Define a repository."
361 Fail-Json $result $ErrorMessage
362 }
363
364 $LatestModule
365 }
366
367 # Check PowerShell version, fail if < 5.0 and required modules are not installed
368 $PsVersion = $PSVersionTable.PSVersion
369 if ($PsVersion.Major -lt 5 ) {
370 $PrereqModulesInstalled = Install-PrereqModule -TestInstallationOnly
371 if ( -not $PrereqModulesInstalled ) {
372 $ErrorMessage = -join @(
373 "Modules PowerShellGet and PackageManagement in versions 1.6.0 and 1.1.7 respectively "
374 "have to be installed before using the win_psmodule."
375 )
376 Fail-Json $result $ErrorMessage
377 }
378 }
379
380 if ( $required_version -and ( $minimum_version -or $maximum_version ) ) {
381 $ErrorMessage = "Parameters required_version and minimum/maximum_version are mutually exclusive."
382 Fail-Json $result $ErrorMessage
383 }
384
385 if ( $allow_prerelease -and ( $minimum_version -or $maximum_version ) ) {
386 $ErrorMessage = "Parameters minimum_version, maximum_version can't be used with the parameter allow_prerelease."
387 Fail-Json $result $ErrorMessage
388 }
389
390 if ( $allow_prerelease -and $state -eq "absent" ) {
391 $ErrorMessage = "The parameter allow_prerelease can't be used with state set to 'absent'."
392 Fail-Json $result $ErrorMessage
393 }
394
395 if ( ($state -eq "latest") -and
396 ( $required_version -or $minimum_version -or $maximum_version ) ) {
397 $ErrorMessage = "When the parameter state is equal to 'latest' you can't use any of required_version, minimum_version, maximum_version."
398 Fail-Json $result $ErrorMessage
399 }
400
401 if ( $repo ) {
402 $RepositoryExists = Get-PSRepository -Name $repo -ErrorAction SilentlyContinue
403 if ( $null -eq $RepositoryExists) {
404 $ErrorMessage = "The repository $repo doesn't exist."
405 Fail-Json $result $ErrorMessage
406 }
407
408 }
409
410 if ($repo_user -and $repo_pass ) {
411 $repo_credential = New-Object -TypeName PSCredential ($repo_user, ($repo_pass | ConvertTo-SecureString -AsPlainText -Force))
412 }
413
414 if ( ($allow_clobber -or $allow_prerelease -or $skip_publisher_check -or
415 $required_version -or $minimum_version -or $maximum_version -or $accept_license) ) {
416 # Update the PowerShellGet and PackageManagement modules.
417 # It's required to support AllowClobber, AllowPrerelease parameters.
418 # This must occur before PackageManagement or PowerShellGet is imported in
419 # the current process.
420 Install-PrereqModule -AllowClobber $allow_clobber -CheckMode $check_mode -AcceptLicense $accept_license -Repository $repo
421 }
422
423 Import-Module -Name PackageManagement, PowerShellGet -Force
424
425 if ($state -eq "present") {
426 if ($name) {
427 $ht = @{
428 Name = $name
429 RequiredVersion = $required_version
430 MinimumVersion = $minimum_version
431 MaximumVersion = $maximum_version
432 Repository = $repo
433 AllowClobber = $allow_clobber
434 SkipPublisherCheck = $skip_publisher_check
435 AllowPrerelease = $allow_prerelease
436 CheckMode = $check_mode
437 Credential = $repo_credential
438 AcceptLicense = $accept_license
439 Force = $force
440 }
441 Install-PsModule @ht
442 }
443 }
444 elseif ($state -eq "absent") {
445 if ($name) {
446 $ht = @{
447 Name = $Name
448 CheckMode = $check_mode
449 RequiredVersion = $required_version
450 MinimumVersion = $minimum_version
451 MaximumVersion = $maximum_version
452 }
453 Remove-PsModule @ht
454 }
455 }
456 elseif ( $state -eq "latest") {
457
458 $ht = @{
459 Name = $Name
460 AllowPrerelease = $allow_prerelease
461 Repository = $repo
462 CheckMode = $check_mode
463 Credential = $repo_credential
464 }
465
466 $LatestModule = Find-LatestPsModule @ht
467
468 $ExistingModule = Get-PsModule $Name
469
470 if ( ($LatestModule.Version -ne $ExistingModule.Version) -or $force ) {
471
472 $ht = @{
473 Name = $Name
474 RequiredVersion = $LatestModule.Version
475 Repository = $repo
476 AllowClobber = $allow_clobber
477 SkipPublisherCheck = $skip_publisher_check
478 AllowPrerelease = $allow_prerelease
479 CheckMode = $check_mode
480 Credential = $repo_credential
481 AcceptLicense = $accept_license
482 Force = $force
483 }
484 Install-PsModule @ht
485 }
486 }
487
488 Exit-Json $result