---

- module_defaults:
    group/aws:
      aws_access_key: '{{ aws_access_key | default(omit) }}'
      aws_secret_key: '{{ aws_secret_key | default(omit) }}'
      security_token: '{{ security_token | default(omit) }}'
      region: '{{ aws_region | default(omit) }}'

  block:

    # ==== Tests ===================================================

    - name: Create a new instance
      lightsail:
        name: "{{ instance_name }}"
        zone: "{{ zone }}"
        blueprint_id: amazon_linux
        bundle_id: nano_2_0
        wait: yes
      register: result

    - assert:
        that:
          - result.changed == True
          - "'instance' in result and result.instance.name == instance_name"
          - "result.instance.state.name == 'running'"

    - name: Make sure create is idempotent
      lightsail:
        name: "{{ instance_name }}"
        zone: "{{ zone }}"
        blueprint_id: amazon_linux
        bundle_id: nano_2_0
      register: result

    - assert:
        that:
          - result.changed == False

    - name: Start the running instance
      lightsail:
        name: "{{ instance_name }}"
        state: running
      register: result

    - assert:
        that:
          - result.changed == False

    - name: Stop the instance
      lightsail:
        name: "{{ instance_name }}"
        state: stopped
        wait: yes
      register: result

    - assert:
        that:
          - result.changed == True
          - "result.instance.state.name == 'stopped'"

    - name: Stop the stopped instance
      lightsail:
        name: "{{ instance_name }}"
        state: stopped
      register: result

    - assert:
        that:
          - result.changed == False

    - name: Start the instance
      lightsail:
        name: "{{ instance_name }}"
        state: running
      register: result

    - assert:
        that:
          - result.changed == True
          - "result.instance.state.name == 'running'"

    - name: Restart the instance
      lightsail:
        name: "{{ instance_name }}"
        state: restarted
      register: result

    - assert:
        that:
          - result.changed == True

    - name: Delete the instance
      lightsail:
        name: "{{ instance_name }}"
        state: absent
      register: result

    - assert:
        that:
          - result.changed == True

    - name: Make sure instance deletion is idempotent
      lightsail:
        name: "{{ instance_name }}"
        state: absent
      register: result

    - assert:
        that:
          - result.changed == False

  # ==== Cleanup ====================================================

  always:

    - name: Cleanup - delete instance
      lightsail:
        name: "{{ instance_name }}"
        state: absent
      ignore_errors: yes
