summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/windows/win_uri.ps1
blob: a84d7ed8d8db0b7d3f6240da5a492e27677db996 (plain)
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
#!powershell

# Copyright: (c) 2015, Corwin Brown <corwin@corwinbrown.com>
# Copyright: (c) 2017, Dag Wieers (@dagwieers) <dag@wieers.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

#AnsibleRequires -CSharpUtil Ansible.Basic
#Requires -Module Ansible.ModuleUtils.CamelConversion
#Requires -Module Ansible.ModuleUtils.FileUtil
#Requires -Module Ansible.ModuleUtils.Legacy
#Requires -Module Ansible.ModuleUtils.WebRequest

$spec = @{
    options = @{
       content_type = @{ type = "str" }
       body = @{ type = "raw" }
       dest = @{ type = "path" }
       creates = @{ type = "path" }
       method = @{ default = "GET" }
       removes = @{ type = "path" }
       return_content = @{ type = "bool"; default = $false }
       status_code = @{ type = "list"; elements = "int"; default = @(200) }

       # Defined for the alias backwards compatibility, remove once aliases are removed
       url_username = @{
           aliases = @("user", "username")
           deprecated_aliases = @(
               @{ name = "user"; version = "2.14" },
               @{ name = "username"; version = "2.14" }
           )
       }
       url_password = @{
           aliases = @("password")
           deprecated_aliases = @(
               @{ name = "password"; version = "2.14" }
           )
       }
    }
    supports_check_mode = $true
}
$spec = Merge-WebRequestSpec -ModuleSpec $spec

$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec)

$url = $module.Params.url
$method = $module.Params.method.ToUpper()
$content_type = $module.Params.content_type
$body = $module.Params.body
$dest = $module.Params.dest
$creates = $module.Params.creates
$removes = $module.Params.removes
$return_content = $module.Params.return_content
$status_code = $module.Params.status_code

$JSON_CANDIDATES = @('text', 'json', 'javascript')

$module.Result.elapsed = 0
$module.Result.url = $url

if (-not ($method -cmatch '^[A-Z]+$')) {
    $module.FailJson("Parameter 'method' needs to be a single word in uppercase, like GET or POST.")
}

if ($creates -and (Test-AnsiblePath -Path $creates)) {
    $module.Result.skipped = $true
    $module.Result.msg = "The 'creates' file or directory ($creates) already exists."
    $module.ExitJson()
}

if ($removes -and -not (Test-AnsiblePath -Path $removes)) {
    $module.Result.skipped = $true
    $module.Result.msg = "The 'removes' file or directory ($removes) does not exist."
    $module.ExitJson()
}

$client = Get-AnsibleWebRequest -Module $module

if ($null -ne $content_type) {
    $client.ContentType = $content_type
}

$response_script = {
    param($Response, $Stream)

    ForEach ($prop in $Response.PSObject.Properties) {
        $result_key = Convert-StringToSnakeCase -string $prop.Name
        $prop_value = $prop.Value
        # convert and DateTime values to ISO 8601 standard
        if ($prop_value -is [System.DateTime]) {
            $prop_value = $prop_value.ToString("o", [System.Globalization.CultureInfo]::InvariantCulture)
        }
        $module.Result.$result_key = $prop_value
    }

    # manually get the headers as not all of them are in the response properties
    foreach ($header_key in $Response.Headers.GetEnumerator()) {
        $header_value = $Response.Headers[$header_key]
        $header_key = $header_key.Replace("-", "") # replace - with _ for snake conversion
        $header_key = Convert-StringToSnakeCase -string $header_key
        $module.Result.$header_key = $header_value
    }

    # we only care about the return body if we need to return the content or create a file
    if ($return_content -or $dest) {
        # copy to a MemoryStream so we can read it multiple times
        $memory_st = New-Object -TypeName System.IO.MemoryStream
        try {
            $Stream.CopyTo($memory_st)

            if ($return_content) {
                $memory_st.Seek(0, [System.IO.SeekOrigin]::Begin) > $null
                $content_bytes = $memory_st.ToArray()
                $module.Result.content = [System.Text.Encoding]::UTF8.GetString($content_bytes)
                if ($module.Result.ContainsKey("content_type") -and $module.Result.content_type -Match ($JSON_CANDIDATES -join '|')) {
                    try {
                        $module.Result.json = ([Ansible.Basic.AnsibleModule]::FromJson($module.Result.content))
                    } catch [System.ArgumentException] {
                        # Simply continue, since 'text' might be anything
                    }
                }
            }

            if ($dest) {
                $memory_st.Seek(0, [System.IO.SeekOrigin]::Begin) > $null
                $changed = $true

                if (Test-AnsiblePath -Path $dest) {
                    $actual_checksum = Get-FileChecksum -path $dest -algorithm "sha1"

                    $sp = New-Object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider
                    $content_checksum = [System.BitConverter]::ToString($sp.ComputeHash($memory_st)).Replace("-", "").ToLower()

                    if ($actual_checksum -eq $content_checksum) {
                        $changed = $false
                    }
                }

                $module.Result.changed = $changed
                if ($changed -and (-not $module.CheckMode)) {
                    $memory_st.Seek(0, [System.IO.SeekOrigin]::Begin) > $null
                    $file_stream = [System.IO.File]::Create($dest)
                    try {
                        $memory_st.CopyTo($file_stream)
                    } finally {
                        $file_stream.Flush()
                        $file_stream.Close()
                    }
                }
            }
        } finally {
            $memory_st.Close()
        }
    }

    if ($status_code -notcontains $Response.StatusCode) {
        $module.FailJson("Status code of request '$([int]$Response.StatusCode)' is not in list of valid status codes $status_code : $($Response.StatusCode)'.")
    }
}

$body_st = $null
if ($null -ne $body) {
    if ($body -is [System.Collections.IDictionary] -or $body -is [System.Collections.IList]) {
        $body_string = ConvertTo-Json -InputObject $body -Compress
    } elseif ($body -isnot [String]) {
        $body_string = $body.ToString()
    } else {
        $body_string = $body
    }
    $buffer = [System.Text.Encoding]::UTF8.GetBytes($body_string)

    $body_st = New-Object -TypeName System.IO.MemoryStream -ArgumentList @(,$buffer)
}

try {
    Invoke-WithWebRequest -Module $module -Request $client -Script $response_script -Body $body_st -IgnoreBadResponse
} catch {
    $module.FailJson("Unhandled exception occurred when sending web request. Exception: $($_.Exception.Message)", $_)
} finally {
    if ($null -ne $body_st) {
        $body_st.Dispose()
    }
}

$module.ExitJson()