ansible.builtin.uri (v2.9.27) — module

Interacts with webservices

| "added in version" 1.1 of ansible.builtin"

Authors: Romeo Theriault (@romeotheriault)

stableinterface | supported by core

Install Ansible via pip

Install with pip install ansible==2.9.27

Description

Interacts with HTTP and HTTPS web services and supports Digest, Basic and WSSE HTTP authentication mechanisms.

For Windows targets, use the M(win_uri) module instead.

Usage examples

  • Success
    Steampunk Spotter scan finished with no errors, warnings or hints.
- name: Check that you can connect (GET) to a page and it returns a status 200
  uri:
    url: http://www.example.com
  • Success
    Steampunk Spotter scan finished with no errors, warnings or hints.
- name: Check that a page returns a status 200 and fail if the word AWESOME is not in the page contents
  uri:
    url: http://www.example.com
    return_content: yes
  register: this
  failed_when: "'AWESOME' not in this.content"
  • Success
    Steampunk Spotter scan finished with no errors, warnings or hints.
- name: Create a JIRA issue
  uri:
    url: https://your.jira.example.com/rest/api/2/issue/
    user: your_username
    password: your_pass
    method: POST
    body: "{{ lookup('file','issue.json') }}"
    force_basic_auth: yes
    status_code: 201
    body_format: json
  • Success
    Steampunk Spotter scan finished with no errors, warnings or hints.
- name: Login to a form based webpage, then use the returned cookie to access the app in later tasks
  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
  • Success
    Steampunk Spotter scan finished with no errors, warnings or hints.
- name: Login to a form based webpage using a list of tuples
  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
  • Success
    Steampunk Spotter scan finished with no errors, warnings or hints.
- name: Connect to website using a previously stored cookie
  uri:
    url: https://your.form.based.auth.example.com/dashboard.php
    method: GET
    return_content: yes
    headers:
      Cookie: "{{ login.set_cookie }}"
  • Success
    Steampunk Spotter scan finished with no errors, warnings or hints.
- name: Queue build of a project in Jenkins
  uri:
    url: http://{{ jenkins.host }}/job/{{ jenkins.job }}/build?token={{ jenkins.token }}
    user: "{{ jenkins.user }}"
    password: "{{ jenkins.password }}"
    method: GET
    force_basic_auth: yes
    status_code: 201
  • Success
    Steampunk Spotter scan finished with no errors, warnings or hints.
- name: POST from contents of local file
  uri:
    url: https://httpbin.org/post
    method: POST
    src: file.json
  • Success
    Steampunk Spotter scan finished with no errors, warnings or hints.
- name: POST from contents of remote file
  uri:
    url: https://httpbin.org/post
    method: POST
    src: /path/to/my/file.json
    remote_src: yes
  • Success
    Steampunk Spotter scan finished with no errors, warnings or hints.
- name: Pause play until a URL is reachable from this host
  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
  • Success
    Steampunk Spotter scan finished with no errors, warnings or hints.
# There are issues in a supporting Python library that is discussed in
# https://github.com/ansible/ansible/issues/52705 where a proxy is defined
# but you want to bypass proxy use on CIDR masks by using no_proxy
- name: Work around a python issue that doesn't support no_proxy envvar
  uri:
    follow_redirects: none
    validate_certs: false
    timeout: 5
    url: "http://{{ ip_address }}:{{ port | default(80) }}"
  register: uri_data
  failed_when: false
  changed_when: false
  vars:
    ip_address: 192.0.2.1
  environment: |
      {
        {% for no_proxy in (lookup('env', 'no_proxy') | regex_replace('\s*,\s*', ' ') ).split() %}
          {% if no_proxy | regex_search('\/') and
                no_proxy | ipaddr('net') != '' and
                no_proxy | ipaddr('net') != false and
                ip_address | ipaddr(no_proxy) is not none and
                ip_address | ipaddr(no_proxy) != false %}
            'no_proxy': '{{ ip_address }}'
          {% elif no_proxy | regex_search(':') != '' and
                  no_proxy | regex_search(':') != false and
                  no_proxy == ip_address + ':' + (port | default(80)) %}
            'no_proxy': '{{ ip_address }}:{{ port | default(80) }}'
          {% elif no_proxy | ipaddr('host') != '' and
                  no_proxy | ipaddr('host') != false and
                  no_proxy == ip_address %}
            'no_proxy': '{{ ip_address }}'
          {% elif no_proxy | regex_search('^(\*|)\.') != '' and
                  no_proxy | regex_search('^(\*|)\.') != false and
                  no_proxy | regex_replace('\*', '') in ip_address %}
            'no_proxy': '{{ ip_address }}'
          {% endif %}
        {% endfor %}
      }

Inputs

    
src:
    description:
    - Path to file to be submitted to the remote server.
    - Cannot be used with I(body).
    type: path
    version_added: '2.7'
    version_added_collection: ansible.builtin

url:
    description:
    - HTTP or HTTPS URL in the form (http|https)://host.domain[:port]/path
    required: true
    type: str

body:
    description:
    - The body of the http request/response to the web service. If C(body_format) is set
      to 'json' it will take an already formatted JSON string or convert a data structure
      into JSON. If C(body_format) is set to 'form-urlencoded' it will convert a dictionary
      or list of tuples into an 'application/x-www-form-urlencoded' string. (Added in
      v2.7)
    type: raw

dest:
    description:
    - A path of where to download the file to (if desired). If I(dest) is a directory,
      the basename of the file on the remote server will be used.
    type: path

mode:
    description:
    - The permissions the resulting filesystem object should have.
    - For those used to I(/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.
    type: raw

force:
    aliases:
    - thirsty
    default: false
    description:
    - If C(yes) do not get a cached copy.
    - Alias C(thirsty) has been deprecated and will be removed in 2.13.
    type: bool

group:
    description:
    - Name of the group that should own the filesystem object, as would be fed to I(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.
    type: str

owner:
    description:
    - Name of the user that should own the filesystem object, as would be fed to I(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.
    type: str

method:
    default: GET
    description:
    - 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.
    type: str

serole:
    description:
    - 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.
    type: str

setype:
    description:
    - 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.
    type: str

seuser:
    description:
    - 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.
    type: str

creates:
    description:
    - A filename, when it already exists, this step will not be run.
    type: path

headers:
    description:
    - Add custom HTTP headers to a request in the format of a YAML hash. As of C(2.3)
      supplying C(Content-Type) here will override the header generated by supplying C(json)
      or C(form-urlencoded) for I(body_format).
    type: dict
    version_added: '2.1'
    version_added_collection: ansible.builtin

removes:
    description:
    - A filename, when it does not exist, this step will not be run.
    type: path

selevel:
    description:
    - 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.
    type: str

timeout:
    default: 30
    description:
    - The socket level timeout in seconds
    type: int

use_proxy:
    default: true
    description:
    - If C(no), it will not use a proxy, even if one is defined in an environment variable
      on the target hosts.
    type: bool

attributes:
    aliases:
    - attr
    description:
    - The attributes the resulting filesystem object should have.
    - To get supported flags look at the man page for I(chattr) on the target system.
    - This string should contain the attributes in the same order as the one displayed
      by I(lsattr).
    - The C(=) operator is assumed as default, otherwise C(+) or C(-) operators need to
      be included in the string.
    type: str
    version_added: '2.3'
    version_added_collection: ansible.builtin

client_key:
    description:
    - PEM formatted file that contains your private key to be used for SSL client authentication.
    - If I(client_cert) contains both the certificate and key, this option is not required.
    type: path
    version_added: '2.4'
    version_added_collection: ansible.builtin

http_agent:
    default: ansible-httpget
    description:
    - Header to identify as, generally appears in web server logs.
    type: str

remote_src:
    default: false
    description:
    - If C(no), the module will search for src on originating/master machine.
    - If C(yes) the module will use the C(src) path on the remote/target machine.
    type: bool
    version_added: '2.7'
    version_added_collection: ansible.builtin

body_format:
    choices:
    - form-urlencoded
    - json
    - raw
    default: raw
    description:
    - The serialization format of the body. When set to C(json) or C(form-urlencoded),
      encodes the body argument, if needed, and automatically sets the Content-Type header
      accordingly. As of C(2.3) it is possible to override the `Content-Type` header,
      when set to C(json) or C(form-urlencoded) via the I(headers) option.
    type: str
    version_added: '2.0'
    version_added_collection: ansible.builtin

client_cert:
    description:
    - 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, I(client_key)
      is not required
    type: path
    version_added: '2.4'
    version_added_collection: ansible.builtin

status_code:
    default:
    - 200
    description:
    - A list of valid, numeric, HTTP status codes that signifies success of the request.
    type: list

unix_socket:
    description:
    - Path to Unix domain socket to use for connection
    version_added: '2.8'
    version_added_collection: ansible.builtin

url_password:
    aliases:
    - password
    description:
    - A password for the module to use for Digest, Basic or WSSE authentication.
    type: str

url_username:
    aliases:
    - user
    description:
    - A username for the module to use for Digest, Basic or WSSE authentication.
    type: str

unsafe_writes:
    default: false
    description:
    - 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.
    type: bool
    version_added: '2.2'
    version_added_collection: ansible.builtin

return_content:
    default: false
    description:
    - Whether or not to return the body of the response as a "content" key in the dictionary
      result.
    - Independently of this option, if the reported Content-type is "application/json",
      then the JSON is always loaded into a key called C(json) in the dictionary results.
    type: bool

validate_certs:
    default: true
    description:
    - If C(no), SSL certificates will not be validated.
    - This should only set to C(no) used on personally controlled sites using self-signed
      certificates.
    - Prior to 1.9.2 the code defaulted to C(no).
    type: bool
    version_added: 1.9.2
    version_added_collection: ansible.builtin

follow_redirects:
    choices:
    - all
    - 'no'
    - none
    - safe
    - urllib2
    - 'yes'
    default: safe
    description:
    - Whether or not the URI module should follow redirects. C(all) will follow all redirects.
      C(safe) will follow only "safe" redirects, where "safe" means that the client is
      only doing a GET or HEAD on the URI to which it is being redirected. C(none) will
      not follow any redirects. Note that C(yes) and C(no) choices are accepted for backwards
      compatibility, where C(yes) is the equivalent of C(all) and C(no) is the equivalent
      of C(safe). C(yes) and C(no) are deprecated and will be removed in some future version
      of Ansible.
    type: str

force_basic_auth:
    default: false
    description:
    - Force the sending of the Basic authentication header upon initial request.
    - The library used by the uri module only sends authentication information when a
      webservice responds to an initial request with a 401 status. Since some basic auth
      services do not properly send a 401, logins will fail.
    type: bool

Outputs

elapsed:
  description: The number of seconds that elapsed while performing the download
  returned: on success
  sample: 23
  type: int
msg:
  description: The HTTP message from the request
  returned: always
  sample: OK (unknown bytes)
  type: str
redirected:
  description: Whether the request was redirected
  returned: on success
  sample: false
  type: bool
status:
  description: The HTTP status code from the request
  returned: always
  sample: 200
  type: int
url:
  description: The actual URL used for the request
  returned: always
  sample: https://www.ansible.com/
  type: str

See also