Debian Codegraph @

lib/ansible/modules/uri.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2013, Romeo Theriault <romeot () hawaii.edu>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8
9 DOCUMENTATION = r"""
10 ---
11 module: uri
12 short_description: Interacts with webservices
13 description:
14 - Interacts with HTTP and HTTPS web services and supports Digest, Basic and WSSE
15 HTTP authentication mechanisms.
16 - For Windows targets, use the M(ansible.windows.win_uri) module instead.
17 version_added: "1.1"
18 options:
19 ciphers:
20 description:
21 - SSL/TLS Ciphers to use for the request.
22 - 'When a list is provided, all ciphers are joined in order with V(:)'
23 - See the L(OpenSSL Cipher List Format,https://www.openssl.org/docs/manmaster/man1/openssl-ciphers.html#CIPHER-LIST-FORMAT)
24 for more details.
25 - The available ciphers is dependent on the Python and OpenSSL/LibreSSL versions.
26 type: list
27 elements: str
28 version_added: '2.14'
29 decompress:
30 description:
31 - Whether to attempt to decompress gzip content-encoded responses.
32 type: bool
33 default: true
34 version_added: '2.14'
35 url:
36 description:
37 - HTTP or HTTPS URL in the form (http|https)://host.domain[:port]/path.
38 type: str
39 required: true
40 dest:
41 description:
42 - A path of where to download the file to (if desired). If O(dest) is a
43 directory, the basename of the file on the remote server will be used.
44 type: path
45 url_username:
46 description:
47 - A username for the module to use for Digest, Basic or WSSE authentication.
48 type: str
49 aliases: [ user ]
50 url_password:
51 description:
52 - A password for the module to use for Digest, Basic or WSSE authentication.
53 type: str
54 aliases: [ password ]
55 body:
56 description:
57 - The body of the http request/response to the web service. If O(body_format) is set
58 to V(json) it will take an already formatted JSON string or convert a data structure
59 into JSON.
60 - If O(body_format) is set to V(form-urlencoded) it will convert a dictionary
61 or list of tuples into an C(application/x-www-form-urlencoded) string. (Added in v2.7)
62 - If O(body_format) is set to V(form-multipart) it will convert a dictionary
63 into C(multipart/form-multipart) body. (Added in v2.10)
64 - If C(body_format) is set to V(form-multipart) the option 'multipart_encoding' allows to change multipart file encoding. (Added in v2.19)
65 type: raw
66 body_format:
67 description:
68 - The serialization format of the body. When set to V(json), V(form-multipart), or V(form-urlencoded), encodes
69 the body argument, if needed, and automatically sets the C(Content-Type) header accordingly.
70 - As of v2.3 it is possible to override the C(Content-Type) header, when
71 set to V(json) or V(form-urlencoded) via the O(headers) option.
72 - The C(Content-Type) header cannot be overridden when using V(form-multipart).
73 - V(form-urlencoded) was added in v2.7.
74 - V(form-multipart) was added in v2.10.
75 type: str
76 choices: [ form-urlencoded, json, raw, form-multipart ]
77 default: raw
78 version_added: "2.0"
79 method:
80 description:
81 - The HTTP method of the request or response.
82 - In more recent versions we do not restrict the method at the module level anymore
83 but it still must be a valid method accepted by the service handling the request.
84 type: str
85 default: GET
86 return_content:
87 description:
88 - Whether or not to return the body of the response as a "content" key in
89 the dictionary result no matter it succeeded or failed.
90 - Independently of this option, if the reported C(Content-Type) is C(application/json), then the JSON is
91 always loaded into a key called RV(ignore:json) in the dictionary results.
92 type: bool
93 default: no
94 force_basic_auth:
95 description:
96 - Force the sending of the Basic authentication header upon initial request.
97 - When this setting is V(false), this module will first try an unauthenticated request, and when the server replies
98 with an C(HTTP 401) error, it will submit the Basic authentication header.
99 - When this setting is V(true), this module will immediately send a Basic authentication header on the first
100 request.
101 - "Use this setting in any of the following scenarios:"
102 - You know the webservice endpoint always requires HTTP Basic authentication, and you want to speed up your
103 requests by eliminating the first roundtrip.
104 - The web service does not properly send an HTTP 401 error to your client, so Ansible's HTTP library will not
105 properly respond with HTTP credentials, and logins will fail.
106 - The webservice bans or rate-limits clients that cause any HTTP 401 errors.
107 type: bool
108 default: no
109 creates:
110 description:
111 - A filename, when it already exists, this step will not be run.
112 type: path
113 removes:
114 description:
115 - A filename, when it does not exist, this step will not be run.
116 type: path
117 status_code:
118 description:
119 - A list of valid, numeric, HTTP status codes that signifies success of the request.
120 type: list
121 elements: int
122 default: [ 200 ]
123 timeout:
124 description:
125 - The socket level timeout in seconds
126 type: int
127 default: 30
128 headers:
129 description:
130 - Add custom HTTP headers to a request in the format of a YAML hash. As
131 of Ansible 2.3 supplying C(Content-Type) here will override the header
132 generated by supplying V(json) or V(form-urlencoded) for O(body_format).
133 type: dict
134 default: {}
135 version_added: '2.1'
136 validate_certs:
137 description:
138 - If V(false), SSL certificates will not be validated.
139 - This should only set to V(false) used on personally controlled sites using self-signed certificates.
140 - Prior to 1.9.2 the code defaulted to V(false).
141 type: bool
142 default: true
143 version_added: '1.9.2'
144 client_cert:
145 description:
146 - PEM formatted certificate chain file to be used for SSL client authentication.
147 - This file can also include the key as well, and if the key is included, O(client_key) is not required.
148 type: path
149 version_added: '2.4'
150 client_key:
151 description:
152 - PEM formatted file that contains your private key to be used for SSL client authentication.
153 - If O(client_cert) contains both the certificate and key, this option is not required.
154 type: path
155 version_added: '2.4'
156 ca_path:
157 description:
158 - PEM formatted file that contains a CA certificate to be used for validation.
159 type: path
160 version_added: '2.11'
161 src:
162 description:
163 - Path to file to be submitted to the remote server.
164 - Cannot be used with O(body).
165 - Should be used with O(force_basic_auth) to ensure success when the remote end sends a 401.
166 type: path
167 version_added: '2.7'
168 remote_src:
169 description:
170 - If V(false), the module will search for the O(src) on the controller node.
171 - If V(true), the module will search for the O(src) on the managed (remote) node.
172 type: bool
173 default: no
174 version_added: '2.7'
175 force:
176 description:
177 - If V(true) do not get a cached copy.
178 type: bool
179 default: no
180 use_proxy:
181 description:
182 - If V(false), it will not use a proxy, even if one is defined in an environment variable on the target hosts.
183 type: bool
184 default: true
185 unix_socket:
186 description:
187 - Path to Unix domain socket to use for connection.
188 type: path
189 version_added: '2.8'
190 http_agent:
191 description:
192 - Header to identify as, generally appears in web server logs.
193 type: str
194 default: ansible-httpget
195 unredirected_headers:
196 description:
197 - A list of header names that will not be sent on subsequent redirected requests. This list is case
198 insensitive. By default all headers will be redirected. In some cases it may be beneficial to list
199 headers such as C(Authorization) here to avoid potential credential exposure.
200 default: []
201 type: list
202 elements: str
203 version_added: '2.12'
204 use_gssapi:
205 description:
206 - Use GSSAPI to perform the authentication, typically this is for Kerberos or Kerberos through Negotiate
207 authentication.
208 - Requires the Python library L(gssapi,https://github.com/pythongssapi/python-gssapi) to be installed.
209 - Credentials for GSSAPI can be specified with O(url_username)/O(url_password) or with the GSSAPI env var
210 C(KRB5CCNAME) that specified a custom Kerberos credential cache.
211 - NTLM authentication is B(not) supported even if the GSSAPI mech for NTLM has been installed.
212 type: bool
213 default: no
214 version_added: '2.11'
215 use_netrc:
216 description:
217 - Determining whether to use credentials from C(~/.netrc) file.
218 - By default C(.netrc) is used with Basic authentication headers.
219 - When V(false), C(.netrc) credentials are ignored.
220 type: bool
221 default: true
222 version_added: '2.14'
223 extends_documentation_fragment:
224 - action_common_attributes
225 - files
226 - url.url_redirect
227 attributes:
228 check_mode:
229 support: none
230 diff_mode:
231 support: none
232 platform:
233 platforms: posix
234 notes:
235 - The dependency on httplib2 was removed in Ansible 2.1.
236 - The module returns all the HTTP headers in lower-case.
237 - For Windows targets, use the M(ansible.windows.win_uri) module instead.
238 seealso:
239 - module: ansible.builtin.get_url
240 - module: ansible.windows.win_uri
241 author:
242 - Romeo Theriault (@romeotheriault)
243 """
244
245 EXAMPLES = r"""
246 - name: Check that you can connect (GET) to a page and it returns a status 200
247 ansible.builtin.uri:
248 url: http://www.example.com
249
250 - name: Check that a page returns successfully but fail if the word AWESOME is not in the page contents
251 ansible.builtin.uri:
252 url: http://www.example.com
253 return_content: true
254 register: this
255 failed_when: "this is failed or 'AWESOME' not in this.content"
256
257 - name: Create a JIRA issue
258 ansible.builtin.uri:
259 url: https://your.jira.example.com/rest/api/2/issue/
260 user: your_username
261 password: your_pass
262 method: POST
263 body: "{{ lookup('ansible.builtin.file','issue.json') }}"
264 force_basic_auth: true
265 status_code: 201
266 body_format: json
267
268 - name: Login to a form based webpage, then use the returned cookie to access the app in later tasks
269 ansible.builtin.uri:
270 url: https://your.form.based.auth.example.com/index.php
271 method: POST
272 body_format: form-urlencoded
273 body:
274 name: your_username
275 password: your_password
276 enter: Sign in
277 status_code: 302
278 register: login
279
280 - name: Login to a form based webpage using a list of tuples
281 ansible.builtin.uri:
282 url: https://your.form.based.auth.example.com/index.php
283 method: POST
284 body_format: form-urlencoded
285 body:
286 - [ name, your_username ]
287 - [ password, your_password ]
288 - [ enter, Sign in ]
289 status_code: 302
290 register: login
291
292 - name: Upload a file via multipart/form-multipart
293 ansible.builtin.uri:
294 url: https://httpbin.org/post
295 method: POST
296 body_format: form-multipart
297 body:
298 file1:
299 filename: /bin/true
300 mime_type: application/octet-stream
301 multipart_encoding: base64
302 file2:
303 content: text based file content
304 filename: fake.txt
305 mime_type: text/plain
306 multipart_encoding: 7or8bit
307 text_form_field: value
308
309 - name: Connect to website using a previously stored cookie
310 ansible.builtin.uri:
311 url: https://your.form.based.auth.example.com/dashboard.php
312 method: GET
313 return_content: true
314 headers:
315 Cookie: "{{ login.cookies_string }}"
316
317 - name: Queue build of a project in Jenkins
318 ansible.builtin.uri:
319 url: http://{{ jenkins.host }}/job/{{ jenkins.job }}/build?token={{ jenkins.token }}
320 user: "{{ jenkins.user }}"
321 password: "{{ jenkins.password }}"
322 method: GET
323 force_basic_auth: true
324 status_code: 201
325
326 - name: POST from contents of local file
327 ansible.builtin.uri:
328 url: https://httpbin.org/post
329 method: POST
330 src: file.json
331
332 - name: POST from contents of remote file
333 ansible.builtin.uri:
334 url: https://httpbin.org/post
335 method: POST
336 src: /path/to/my/file.json
337 remote_src: true
338
339 - name: Create workspaces in Log analytics Azure
340 ansible.builtin.uri:
341 url: https://www.mms.microsoft.com/Embedded/Api/ConfigDataSources/LogManagementData/Save
342 method: POST
343 body_format: json
344 status_code: [200, 202]
345 return_content: true
346 headers:
347 Content-Type: application/json
348 x-ms-client-workspace-path: /subscriptions/{{ sub_id }}/resourcegroups/{{ res_group }}/providers/microsoft.operationalinsights/workspaces/{{ w_spaces }}
349 x-ms-client-platform: ibiza
350 x-ms-client-auth-token: "{{ token_az }}"
351 body:
352
353 - name: Pause play until a URL is reachable from this host
354 ansible.builtin.uri:
355 url: "http://192.0.2.1/some/test"
356 follow_redirects: none
357 method: GET
358 register: _result
359 until: _result.status == 200
360 retries: 720 # 720 * 5 seconds = 1hour (60*60/5)
361 delay: 5 # Every 5 seconds
362
363 - name: Provide SSL/TLS ciphers as a list
364 uri:
365 url: https://example.org
366 ciphers:
367 - '@SECLEVEL=2'
368 - ECDH+AESGCM
369 - ECDH+CHACHA20
370 - ECDH+AES
371 - DHE+AES
372 - '!aNULL'
373 - '!eNULL'
374 - '!aDSS'
375 - '!SHA1'
376 - '!AESCCM'
377
378 - name: Provide SSL/TLS ciphers as an OpenSSL formatted cipher list
379 uri:
380 url: https://example.org
381 ciphers: '@SECLEVEL=2:ECDH+AESGCM:ECDH+CHACHA20:ECDH+AES:DHE+AES:!aNULL:!eNULL:!aDSS:!SHA1:!AESCCM'
382 """
383
384 RETURN = r"""
385 # The return information includes all the HTTP headers in lower-case.
386 content:
387 description: The response body content.
388 returned: status not in status_code or return_content is true
389 type: str
390 sample: "{}"
391 cookies:
392 description: The cookie values placed in cookie jar.
393 returned: on success
394 type: dict
395 sample: {"SESSIONID": "[SESSIONID]"}
396 version_added: "2.4"
397 cookies_string:
398 description: The value for future request Cookie headers.
399 returned: on success
400 type: str
401 sample: "SESSIONID=[SESSIONID]"
402 version_added: "2.6"
403 elapsed:
404 description: The number of seconds that elapsed while performing the download.
405 returned: on success
406 type: int
407 sample: 23
408 msg:
409 description: The HTTP message from the request.
410 returned: always
411 type: str
412 sample: OK (unknown bytes)
413 path:
414 description: destination file/path
415 returned: dest is defined
416 type: str
417 sample: /path/to/file.txt
418 redirected:
419 description: Whether the request was redirected.
420 returned: on success
421 type: bool
422 sample: false
423 status:
424 description: The HTTP status code from the request.
425 returned: always
426 type: int
427 sample: 200
428 url:
429 description: The actual URL used for the request.
430 returned: always
431 type: str
432 sample: https://www.ansible.com/
433 """
434
435 import http
436 import json
437 import os
438 import re
439 import shutil
440 import tempfile
441 from collections.abc import Mapping, Sequence
442 from datetime import datetime, timezone
443 from urllib.parse import urlencode, urljoin
444
445 from ansible.module_utils.basic import AnsibleModule
446 from ansible.module_utils.common.text.converters import to_native, to_text
447 from ansible.module_utils.urls import (
448 create_multipart,
449 fetch_url,
450 get_response_filename,
451 mask_url,
452 parse_content_type,
453 url_argument_spec,
454 url_redirect_argument_spec,
455 )
456
457 JSON_CANDIDATES = {'json', 'javascript'}
458
459
460 def format_message(err, resp):
461 msg = resp.pop('msg')
462 return err + (' %s' % msg if msg else '')
463
464
465 def write_file(module, dest, content, resp):
466 """
467 Create temp file and write content to dest file only if content changed
468 """
469
470 tmpsrc = None
471
472 try:
473 fd, tmpsrc = tempfile.mkstemp(dir=module.tmpdir)
474 with os.fdopen(fd, 'wb') as f:
475 if isinstance(content, bytes):
476 f.write(content)
477 else:
478 shutil.copyfileobj(content, f)
479 except Exception as e:
480 if tmpsrc and os.path.exists(tmpsrc):
481 os.remove(tmpsrc)
482 msg = format_message("Failed to create temporary content file: %s" % to_native(e), resp)
483 module.fail_json(msg=msg, **resp)
484
485 checksum_src = module.sha1(tmpsrc)
486 checksum_dest = module.sha1(dest)
487
488 if checksum_src != checksum_dest:
489 try:
490 module.atomic_move(tmpsrc, dest)
491 except Exception as e:
492 if os.path.exists(tmpsrc):
493 os.remove(tmpsrc)
494 msg = format_message("failed to copy %s to %s: %s" % (tmpsrc, dest, to_native(e)), resp)
495 module.fail_json(msg=msg, **resp)
496
497 if os.path.exists(tmpsrc):
498 os.remove(tmpsrc)
499
500
501 def kv_list(data):
502 """ Convert data into a list of key-value tuples """
503 if data is None:
504 return None
505
506 if isinstance(data, Sequence):
507 return list(data)
508
509 if isinstance(data, Mapping):
510 return list(data.items())
511
512 raise TypeError('cannot form-urlencode body, expect list or dict')
513
514
515 def form_urlencoded(body):
516 """ Convert data into a form-urlencoded string """
517 if isinstance(body, str):
518 return body
519
520 if isinstance(body, (Mapping, Sequence)):
521 result = []
522 # Turn a list of lists into a list of tuples that urlencode accepts
523 for key, values in kv_list(body):
524 if isinstance(values, str) or not isinstance(values, (Mapping, Sequence)):
525 values = [values]
526 for value in values:
527 if value is not None:
528 result.append((to_text(key), to_text(value)))
529 return urlencode(result, doseq=True)
530
531 return body
532
533
534 def uri(module, url, dest, body, body_format, method, headers, socket_timeout, ca_path, unredirected_headers, decompress,
535 ciphers, use_netrc):
536 # is dest is set and is a directory, let's check if we get redirected and
537 # set the filename from that url
538
539 src = module.params['src']
540 if src:
541 try:
542 headers.update({
543 'Content-Length': os.stat(src).st_size
544 })
545 data = open(src, 'rb')
546 except OSError:
547 module.fail_json(msg='Unable to open source file %s' % src, elapsed=0)
548 else:
549 data = body
550
551 kwargs = {}
552 if dest is not None and os.path.isfile(dest):
553 # if destination file already exist, only download if file newer
554 kwargs['last_mod_time'] = datetime.fromtimestamp(
555 os.path.getmtime(dest),
556 tz=timezone.utc,
557 )
558
559 resp, info = fetch_url(module, url, data=data, headers=headers,
560 method=method, timeout=socket_timeout, unix_socket=module.params['unix_socket'],
561 ca_path=ca_path, unredirected_headers=unredirected_headers,
562 use_proxy=module.params['use_proxy'], decompress=decompress,
563 ciphers=ciphers, use_netrc=use_netrc, force=module.params['force'], **kwargs)
564
565 if src:
566 # Try to close the open file handle
567 try:
568 data.close()
569 except Exception:
570 pass
571
572 return resp, info
573
574
575 def main():
576 argument_spec = url_argument_spec()
577 argument_spec['url']['required'] = True
578 argument_spec.update(url_redirect_argument_spec())
579 argument_spec.update(
580 dest=dict(type='path'),
581 url_username=dict(type='str', aliases=['user']),
582 url_password=dict(type='str', aliases=['password'], no_log=True),
583 body=dict(type='raw'),
584 body_format=dict(type='str', default='raw', choices=['form-urlencoded', 'json', 'raw', 'form-multipart']),
585 src=dict(type='path'),
586 method=dict(type='str', default='GET'),
587 return_content=dict(type='bool', default=False),
588 follow_redirects=dict(type='str', default='safe', choices=['all', 'none', 'safe', 'urllib2']),
589 creates=dict(type='path'),
590 removes=dict(type='path'),
591 status_code=dict(type='list', elements='int', default=[200]),
592 timeout=dict(type='int', default=30),
593 headers=dict(type='dict', default={}),
594 unix_socket=dict(type='path'),
595 remote_src=dict(type='bool', default=False),
596 ca_path=dict(type='path', default=None),
597 unredirected_headers=dict(type='list', elements='str', default=[]),
598 decompress=dict(type='bool', default=True),
599 ciphers=dict(type='list', elements='str'),
600 use_netrc=dict(type='bool', default=True),
601 )
602
603 module = AnsibleModule(
604 argument_spec=argument_spec,
605 add_file_common_args=True,
606 mutually_exclusive=[['body', 'src']],
607 )
608
609 url = module.params['url']
610 body = module.params['body']
611 body_format = module.params['body_format'].lower()
612 method = module.params['method'].upper()
613 dest = module.params['dest']
614 return_content = module.params['return_content']
615 creates = module.params['creates']
616 removes = module.params['removes']
617 status_code = [int(x) for x in list(module.params['status_code'])]
618 socket_timeout = module.params['timeout']
619 ca_path = module.params['ca_path']
620 dict_headers = module.params['headers']
621 unredirected_headers = module.params['unredirected_headers']
622 decompress = module.params['decompress']
623 ciphers = module.params['ciphers']
624 use_netrc = module.params['use_netrc']
625
626 # for errors and to compare to fetched responses
627 masked_url = mask_url(url)
628
629 if not re.match('^[A-Z]+$', method):
630 module.fail_json(msg="Parameter 'method' needs to be a single word in uppercase, like GET or POST.")
631
632 if body_format == 'json':
633 # Encode the body unless its a string, then assume it is pre-formatted JSON
634 if not isinstance(body, str):
635 body = json.dumps(body)
636 if 'content-type' not in [header.lower() for header in dict_headers]:
637 dict_headers['Content-Type'] = 'application/json'
638 elif body_format == 'form-urlencoded':
639 if not isinstance(body, str):
640 try:
641 body = form_urlencoded(body)
642 except ValueError as e:
643 module.fail_json(msg='failed to parse body as form_urlencoded: %s' % to_native(e), elapsed=0)
644 if 'content-type' not in [header.lower() for header in dict_headers]:
645 dict_headers['Content-Type'] = 'application/x-www-form-urlencoded'
646 elif body_format == 'form-multipart':
647 try:
648 multipart = create_multipart(body)
649 content_type = multipart.content_type
650 body = multipart.as_fp()
651 except (TypeError, ValueError) as e:
652 module.fail_json(msg='failed to parse body as form-multipart: %s' % to_native(e))
653 dict_headers['Content-Type'] = content_type
654
655 if creates is not None:
656 # do not run the command if the line contains creates=filename
657 # and the filename already exists. This allows idempotence
658 # of uri executions.
659 if os.path.exists(creates):
660 module.exit_json(stdout="skipped, since '%s' exists" % creates, changed=False)
661
662 if removes is not None:
663 # do not run the command if the line contains removes=filename
664 # and the filename does not exist. This allows idempotence
665 # of uri executions.
666 if not os.path.exists(removes):
667 module.exit_json(stdout="skipped, since '%s' does not exist" % removes, changed=False)
668
669 # Make the request
670 start = datetime.now(timezone.utc)
671 r, info = uri(module, url, dest, body, body_format, method,
672 dict_headers, socket_timeout, ca_path, unredirected_headers,
673 decompress, ciphers, use_netrc)
674
675 elapsed = (datetime.now(timezone.utc) - start).seconds
676
677 if r and dest is not None and os.path.isdir(dest):
678 filename = get_response_filename(r) or 'index.html'
679 dest = os.path.join(dest, filename)
680
681 if r and r.fp is not None:
682 # r may be None for some errors
683 # r.fp may be None depending on the error, which means there are no headers either
684 content_type, main_type, sub_type, content_encoding = parse_content_type(r)
685 else:
686 content_type = 'application/octet-stream'
687 main_type = 'application'
688 sub_type = 'octet-stream'
689 content_encoding = 'utf-8'
690
691 if sub_type and '+' in sub_type:
692 # https://www.rfc-editor.org/rfc/rfc6839#section-3.1
693 sub_type_suffix = sub_type.partition('+')[2]
694 maybe_json = content_type and sub_type_suffix.lower() in JSON_CANDIDATES
695 elif sub_type:
696 maybe_json = content_type and sub_type.lower() in JSON_CANDIDATES
697 else:
698 maybe_json = False
699
700 maybe_output = maybe_json or return_content or info['status'] not in status_code
701
702 if maybe_output:
703 try:
704 if r.fp is None or r.closed:
705 raise TypeError
706 content = r.read()
707 except (AttributeError, TypeError):
708 # there was no content, but the error read()
709 # may have been stored in the info as 'body'
710 content = info.pop('body', b'')
711 except http.client.HTTPException as http_err:
712 module.fail_json(msg=f"HTTP Error while fetching {masked_url}: {to_native(http_err)}")
713 elif r:
714 content = r
715 else:
716 content = None
717
718 resp = {}
719 resp['redirected'] = info['url'] != masked_url
720 resp.update(info)
721
722 resp['elapsed'] = elapsed
723 resp['status'] = int(resp['status'])
724 resp['changed'] = False
725
726 # Write the file out if requested
727 if r and dest is not None:
728 if resp['status'] in status_code and resp['status'] != 304:
729 write_file(module, dest, content, resp)
730 # allow file attribute changes
731 resp['changed'] = True
732 module.params['path'] = dest
733 file_args = module.load_file_common_arguments(module.params, path=dest)
734 resp['changed'] = module.set_fs_attributes_if_different(file_args, resp['changed'])
735 resp['path'] = dest
736
737 # Transmogrify the headers, replacing '-' with '_', since variables don't
738 # work with dashes.
739 # In python3, the headers are title cased. Lowercase them to be
740 # compatible with the python2 behaviour.
741 uresp = {}
742 for key, value in resp.items():
743 ukey = key.replace("-", "_").lower()
744 uresp[ukey] = value
745
746 if 'location' in uresp:
747 uresp['location'] = urljoin(masked_url, uresp['location'])
748
749 # Default content_encoding to try
750 if isinstance(content, bytes):
751 u_content = to_text(content, encoding=content_encoding)
752 if maybe_json:
753 try:
754 js = json.loads(u_content)
755 uresp['json'] = js
756 except Exception:
757 ...
758 else:
759 u_content = None
760
761 if resp['status'] not in status_code:
762 uresp['msg'] = 'Status code was %s and not %s: %s' % (resp['status'], status_code, uresp.get('msg', ''))
763 if return_content:
764 module.fail_json(content=u_content, **uresp)
765 else:
766 module.fail_json(**uresp)
767 elif return_content:
768 module.exit_json(content=u_content, **uresp)
769 else:
770 module.exit_json(**uresp)
771
772
773 if __name__ == '__main__':
774 main()