Search code examples
ansibleurihealth-check

How to use ansible to query local websites?


I am trying to health check a web host containing multiple websites. is is possible to cycle through different sites using the same port using the URI module?

I have this code :

# Check site directory is present

- name: "Check 'Site 1' site directory"
  ansible.windows.win_stat:
    path: C:\WWW\site1
  register: check_site_1

- name: "Check 'Site 2' site directory"
  ansible.windows.win_stat:
    path: C:\WWW\site2
  register: check_site_2

- name: "Check 'Site 3' site directory"
  ansible.windows.win_stat:
    path: C:\WWW\site3
  register: check_site_3

# Query Sites

# site-1.example.com
- name: "Check 'Site 1' site"
  uri:
    url: "http://{{ ansible_host }}:80/"
    status_code: 
      - 200 
      - 301 
      - 302
  register: result
    delay: 10
    failed_when: result.status == 404
  when: check_site_1.stat.exists

# site-2.example.com
- name: "Check 'Site 2' site"
  uri:
    url: "http://{{ ansible_host }}:80/"
    status_code: 
      - 200 
      - 301 
      - 302
  register: result
    delay: 10
    failed_when: result.status == 404
  when: check_site_2.stat.exists

# site-3.example.com
- name: "Check 'Site 3' site"
  uri:
    url: "http://{{ ansible_host }}:8080/"
    status_code: 
      - 200 
      - 301 
      - 302
  register: result
    delay: 10
    failed_when: result.status == 404
  when: check_site_3.stat.exists

The issue is that when the site is using the same port, I want to pass a hostname to the site to query the localhost website using ansible_host rather than the defined url site-1.example.com because that is an active local balancer url and may not point to the same host. Has any one tried to set the host header to query the site locally using the uri module?

ta,

x


Solution

  • As you mention - try adding a headers parameter, with Host, to your setup:

    # site-1.example.com
    - name: "Check 'Site 1' site"
      uri:
        url: "http://{{ ansible_host }}:80/"
        headers:
          Host: "site-1.example.com"
        status_code: 
          - 200 
          - 301 
          - 302
      register: result
        delay: 10
        failed_when: result.status == 404
      when: check_site_1.stat.exists
    
    # site-2.example.com
    - name: "Check 'Site 2' site"
      uri:
        url: "http://{{ ansible_host }}:80/"
        headers:
          Host: "site-2.example.com"
        status_code: 
          - 200 
          - 301 
          - 302
      register: result
        delay: 10
        failed_when: result.status == 404
      when: check_site_2.stat.exists