Skip to content

uri

Collection Note

This module is part of the ansible.builtin collection. To install the collection, use:

ansible-galaxy collection install ansible.builtin
Added in version 1.1.

Synopsis

  • Interacts with HTTP and HTTPS web services and supports Digest, Basic and WSSE HTTP authentication mechanisms.
  • For Windows targets, use the M(ansible.windows.win_uri) module instead.

Parameters

Parameter Defaults / Choices Comments
attributes
str
The attributes the resulting filesystem object should have.
To get supported flags look at the man page for C(chattr) on the target system.
This string should contain the attributes in the same order as the one displayed by C(lsattr).
The C(=) operator is assumed as default, otherwise C(+) or C(-) operators need to be included in the string.
Version Added: 2.3
body
raw
The body of the http request/response to the web service. If O(body_format) is set to V(json) it will take an already formatted JSON string or convert a data structure into JSON.
If O(body_format) is set to V(form-urlencoded) it will convert a dictionary or list of tuples into an C(application/x-www-form-urlencoded) string. (Added in v2.7)
If O(body_format) is set to V(form-multipart) it will convert a dictionary into C(multipart/form-multipart) body. (Added in v2.10)
body_format
str
Default: raw
Choices: form-urlencoded, json, raw, form-multipart
The serialization format of the body. When set to V(json), V(form-multipart), or V(form-urlencoded), encodes the body argument, if needed, and automatically sets the C(Content-Type) header accordingly.
As of v2.3 it is possible to override the C(Content-Type) header, when set to V(json) or V(form-urlencoded) via the O(headers) option.
The C(Content-Type) header cannot be overridden when using V(form-multipart).
V(form-urlencoded) was added in v2.7.
V(form-multipart) was added in v2.10.
Version Added: 2.0
ca_path
path
PEM formatted file that contains a CA certificate to be used for validation.
Version Added: 2.11
ciphers
list / elements=str
SSL/TLS Ciphers to use for the request.
When a list is provided, all ciphers are joined in order with V(:)
See the L(OpenSSL Cipher List Format,https://www.openssl.org/docs/manmaster/man1/openssl-ciphers.html#CIPHER-LIST-FORMAT) for more details.
The available ciphers is dependent on the Python and OpenSSL/LibreSSL versions.
Version Added: 2.14
client_cert
path
PEM formatted certificate chain file to be used for SSL client authentication.
This file can also include the key as well, and if the key is included, O(client_key) is not required.
Version Added: 2.4
client_key
path
PEM formatted file that contains your private key to be used for SSL client authentication.
If O(client_cert) contains both the certificate and key, this option is not required.
Version Added: 2.4
creates
path
A filename, when it already exists, this step will not be run.
decompress
bool
Default: True
Whether to attempt to decompress gzip content-encoded responses.
Version Added: 2.14
dest
path
A path of where to download the file to (if desired). If O(dest) is a directory, the basename of the file on the remote server will be used.
follow_redirects
str
Default: safe
Choices: all, no, none, safe, urllib2, yes
Whether or not the URI module should follow redirects.
force
bool
If V(true) do not get a cached copy.
force_basic_auth
bool
Force the sending of the Basic authentication header upon initial request.
When this setting is V(false), this module will first try an unauthenticated request, and when the server replies with an C(HTTP 401) error, it will submit the Basic authentication header.
When this setting is V(true), this module will immediately send a Basic authentication header on the first request.
Use this setting in any of the following scenarios:
You know the webservice endpoint always requires HTTP Basic authentication, and you want to speed up your requests by eliminating the first roundtrip.
The web service does not properly send an HTTP 401 error to your client, so Ansible's HTTP library will not properly respond with HTTP credentials, and logins will fail.
The webservice bans or rate-limits clients that cause any HTTP 401 errors.
group
str
Name of the group that should own the filesystem object, as would be fed to C(chown).
When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership.
headers
dict
Add custom HTTP headers to a request in the format of a YAML hash. As of Ansible 2.3 supplying C(Content-Type) here will override the header generated by supplying V(json) or V(form-urlencoded) for O(body_format).
Version Added: 2.1
http_agent
str
Default: ansible-httpget
Header to identify as, generally appears in web server logs.
method
str
Default: GET
The HTTP method of the request or response.
In more recent versions we do not restrict the method at the module level anymore but it still must be a valid method accepted by the service handling the request.
mode
raw
The permissions the resulting filesystem object should have.
For those used to C(/usr/bin/chmod) remember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example, V('644') or V('1777')) so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example, V(0755)) works sometimes, but can fail in loops and some other circumstances.
Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results.
As of Ansible 1.8, the mode may be specified as a symbolic mode (for example, V(u+rwx) or V(u=rw,g=r,o=r)).
If O(mode) is not specified and the destination filesystem object B(does not) exist, the default C(umask) on the system will be used when setting the mode for the newly created filesystem object.
If O(mode) is not specified and the destination filesystem object B(does) exist, the mode of the existing filesystem object will be used.
Specifying O(mode) is the best way to ensure filesystem objects are created with the correct permissions. See CVE-2020-1736 for further details.
owner
str
Name of the user that should own the filesystem object, as would be fed to C(chown).
When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership.
Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion.
remote_src
bool
If V(false), the module will search for the O(src) on the controller node.
If V(true), the module will search for the O(src) on the managed (remote) node.
Version Added: 2.7
removes
path
A filename, when it does not exist, this step will not be run.
return_content
bool
Whether or not to return the body of the response as a "content" key in the dictionary result no matter it succeeded or failed.
Independently of this option, if the reported C(Content-Type) is C(application/json), then the JSON is always loaded into a key called RV(ignore:json) in the dictionary results.
selevel
str
The level part of the SELinux filesystem object context.
This is the MLS/MCS attribute, sometimes known as the C(range).
When set to V(_default), it will use the C(level) portion of the policy if available.
serole
str
The role part of the SELinux filesystem object context.
When set to V(_default), it will use the C(role) portion of the policy if available.
setype
str
The type part of the SELinux filesystem object context.
When set to V(_default), it will use the C(type) portion of the policy if available.
seuser
str
The user part of the SELinux filesystem object context.
By default it uses the V(system) policy, where applicable.
When set to V(_default), it will use the C(user) portion of the policy if available.
src
path
Path to file to be submitted to the remote server.
Cannot be used with O(body).
Should be used with O(force_basic_auth) to ensure success when the remote end sends a 401.
Version Added: 2.7
status_code
list / elements=int
Default: [200]
A list of valid, numeric, HTTP status codes that signifies success of the request.
timeout
int
Default: 30
The socket level timeout in seconds
unix_socket
path
Path to Unix domain socket to use for connection.
Version Added: 2.8
unredirected_headers
list / elements=str
A list of header names that will not be sent on subsequent redirected requests. This list is case insensitive. By default all headers will be redirected. In some cases it may be beneficial to list headers such as C(Authorization) here to avoid potential credential exposure.
Version Added: 2.12
unsafe_writes
bool
Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target filesystem object.
By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target filesystem objects, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted filesystem objects, which cannot be updated atomically from inside the container and can only be written in an unsafe manner.
This option allows Ansible to fall back to unsafe methods of updating filesystem objects when atomic operations fail (however, it doesn't force Ansible to perform unsafe writes).
IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
Version Added: 2.2
url
str
required
HTTP or HTTPS URL in the form (http|https)://host.domain[:port]/path.
url_password
str
A password for the module to use for Digest, Basic or WSSE authentication.
url_username
str
A username for the module to use for Digest, Basic or WSSE authentication.
use_gssapi
bool
Use GSSAPI to perform the authentication, typically this is for Kerberos or Kerberos through Negotiate authentication.
Requires the Python library L(gssapi,https://github.com/pythongssapi/python-gssapi) to be installed.
Credentials for GSSAPI can be specified with O(url_username)/O(url_password) or with the GSSAPI env var C(KRB5CCNAME) that specified a custom Kerberos credential cache.
NTLM authentication is B(not) supported even if the GSSAPI mech for NTLM has been installed.
Version Added: 2.11
use_netrc
bool
Default: True
Determining whether to use credentials from C(~/.netrc) file.
By default C(.netrc) is used with Basic authentication headers.
When V(false), C(.netrc) credentials are ignored.
Version Added: 2.14
use_proxy
bool
Default: True
If V(false), it will not use a proxy, even if one is defined in an environment variable on the target hosts.
validate_certs
bool
Default: True
If V(false), SSL certificates will not be validated.
This should only set to V(false) used on personally controlled sites using self-signed certificates.
Prior to 1.9.2 the code defaulted to V(false).
Version Added: 1.9.2

Notes

Note

  • The dependency on httplib2 was removed in Ansible 2.1.
  • The module returns all the HTTP headers in lower-case.
  • For Windows targets, use the M(ansible.windows.win_uri) module instead.

Examples

- name: Check that you can connect (GET) to a page and it returns a status 200
  ansible.builtin.uri:
    url: http://www.example.com

- name: Check that a page returns successfully but fail if the word AWESOME is not in the page contents
  ansible.builtin.uri:
    url: http://www.example.com
    return_content: true
  register: this
  failed_when: this is failed or "'AWESOME' not in this.content"

- name: Create a JIRA issue
  ansible.builtin.uri:
    url: https://your.jira.example.com/rest/api/2/issue/
    user: your_username
    password: your_pass
    method: POST
    body: "{{ lookup('ansible.builtin.file','issue.json') }}"
    force_basic_auth: true
    status_code: 201
    body_format: json

- name: Login to a form based webpage, then use the returned cookie to access the app in later tasks
  ansible.builtin.uri:
    url: https://your.form.based.auth.example.com/index.php
    method: POST
    body_format: form-urlencoded
    body:
      name: your_username
      password: your_password
      enter: Sign in
    status_code: 302
  register: login

- name: Login to a form based webpage using a list of tuples
  ansible.builtin.uri:
    url: https://your.form.based.auth.example.com/index.php
    method: POST
    body_format: form-urlencoded
    body:
    - [ name, your_username ]
    - [ password, your_password ]
    - [ enter, Sign in ]
    status_code: 302
  register: login

- name: Upload a file via multipart/form-multipart
  ansible.builtin.uri:
    url: https://httpbin.org/post
    method: POST
    body_format: form-multipart
    body:
      file1:
        filename: /bin/true
        mime_type: application/octet-stream
      file2:
        content: text based file content
        filename: fake.txt
        mime_type: text/plain
      text_form_field: value

- name: Connect to website using a previously stored cookie
  ansible.builtin.uri:
    url: https://your.form.based.auth.example.com/dashboard.php
    method: GET
    return_content: true
    headers:
      Cookie: "{{ login.cookies_string }}"

- name: Queue build of a project in Jenkins
  ansible.builtin.uri:
    url: http://{{ jenkins.host }}/job/{{ jenkins.job }}/build?token={{ jenkins.token }}
    user: "{{ jenkins.user }}"
    password: "{{ jenkins.password }}"
    method: GET
    force_basic_auth: true
    status_code: 201

- name: POST from contents of local file
  ansible.builtin.uri:
    url: https://httpbin.org/post
    method: POST
    src: file.json

- name: POST from contents of remote file
  ansible.builtin.uri:
    url: https://httpbin.org/post
    method: POST
    src: /path/to/my/file.json
    remote_src: true

- name: Create workspaces in Log analytics Azure
  ansible.builtin.uri:
    url: https://www.mms.microsoft.com/Embedded/Api/ConfigDataSources/LogManagementData/Save
    method: POST
    body_format: json
    status_code: [200, 202]
    return_content: true
    headers:
      Content-Type: application/json
      x-ms-client-workspace-path: /subscriptions/{{ sub_id }}/resourcegroups/{{ res_group }}/providers/microsoft.operationalinsights/workspaces/{{ w_spaces }}
      x-ms-client-platform: ibiza
      x-ms-client-auth-token: "{{ token_az }}"
    body:

- name: Pause play until a URL is reachable from this host
  ansible.builtin.uri:
    url: "http://192.0.2.1/some/test"
    follow_redirects: none
    method: GET
  register: _result
  until: _result.status == 200
  retries: 720 # 720 * 5 seconds = 1hour (60*60/5)
  delay: 5 # Every 5 seconds

- name: Provide SSL/TLS ciphers as a list
  uri:
    url: https://example.org
    ciphers:
      - '@SECLEVEL=2'
      - ECDH+AESGCM
      - ECDH+CHACHA20
      - ECDH+AES
      - DHE+AES
      - '!aNULL'
      - '!eNULL'
      - '!aDSS'
      - '!SHA1'
      - '!AESCCM'

- name: Provide SSL/TLS ciphers as an OpenSSL formatted cipher list
  uri:
    url: https://example.org
    ciphers: '@SECLEVEL=2:ECDH+AESGCM:ECDH+CHACHA20:ECDH+AES:DHE+AES:!aNULL:!eNULL:!aDSS:!SHA1:!AESCCM'

Return Values

Key Data Type Description Returned
content str The response body content. status not in status_code or return_content is true
cookies dict The cookie values placed in cookie jar. on success
cookies_string str The value for future request Cookie headers. on success
elapsed int The number of seconds that elapsed while performing the download. on success
msg str The HTTP message from the request. always
path str destination file/path dest is defined
redirected bool Whether the request was redirected. on success
status int The HTTP status code from the request. always
url str The actual URL used for the request. always

Authors

  • Romeo Theriault (@romeotheriault)