Debian Codegraph @

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

raw
1 #!powershell
2
3 # Copyright: (c) 2017, Red Hat, Inc.
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 #Requires -Module Ansible.ModuleUtils.Legacy
7
8 $ErrorActionPreference = "Stop"
9 Set-StrictMode -Version 2
10
11 If (-not (Get-Command Get-DiskImage -ErrorAction SilentlyContinue)) {
12 Fail-Json -message "win_disk_image requires Windows 8+ or Windows Server 2012+"
13 }
14
15 $parsed_args = Parse-Args $args -supports_check_mode $true
16
17 $result = @{ changed = $false }
18
19 $image_path = Get-AnsibleParam $parsed_args "image_path" -failifempty $result
20 $state = Get-AnsibleParam $parsed_args "state" -default "present" -validateset "present", "absent"
21 $check_mode = Get-AnsibleParam $parsed_args "_ansible_check_mode" -default $false
22
23 $di = Get-DiskImage $image_path
24
25 If ($state -eq "present") {
26 If (-not $di.Attached) {
27 $result.changed = $true
28
29 If (-not $check_mode) {
30 $di = Mount-DiskImage $image_path -PassThru
31
32 # the actual mount is async, so the CIMInstance result may not immediately contain the data we need
33 $retry_count = 0
34 While (-not $di.Attached -and $retry_count -lt 5) {
35 Start-Sleep -Seconds 1 > $null
36 $di = $di | Get-DiskImage
37 $retry_count++
38 }
39
40 If (-not $di.Attached) {
41 Fail-Json $result -message "Timed out waiting for disk to attach"
42 }
43 }
44 }
45
46 # FUTURE: detect/handle "ejected" ISOs
47 # FUTURE: support explicit drive letter and NTFS in-volume mountpoints.
48 # VHDs don't always auto-assign, and other system settings can prevent automatic assignment
49
50 If ($di.Attached) {
51 # only try to get the mount_path if the disk is attached (
52 If ($di.StorageType -eq 1) {
53 # ISO, we can get the mountpoint directly from Get-Volume
54 $drive_letters = ($di | Get-Volume).DriveLetter
55 }
56 ElseIf ($di.StorageType -in @(2, 3)) {
57 # VHD/VHDX, need Get-Disk + Get-Partition to discover mountpoint
58 $drive_letters = ($di | Get-Disk | Get-Partition).DriveLetter
59 }
60 # remove any null entries (no drive letter)
61 $drive_letters = $drive_letters | Where-Object { $_ }
62
63 If (-not $drive_letters) {
64 Fail-Json -message "Unable to retrieve drive letter from mounted image"
65 }
66
67 $result.mount_paths = @($drive_letters | ForEach-Object { "$($_):\" })
68 }
69 }
70 ElseIf ($state -eq "absent") {
71 If ($di.Attached) {
72 $result.changed = $true
73 If (-not $check_mode) {
74 Dismount-DiskImage $image_path > $null
75 }
76 }
77 }
78
79 Exit-Json $result