---
# Execute Orchestration Workflow
- hosts: localhost
  collections:
    - cisco.intersight
  gather_facts: false
  vars:
    # Create an anchor for api_info that can be used throughout the file
    api_info: &api_info
      api_private_key: "{{ api_private_key }}"
      api_key_id: "{{ api_key_id }}"
    image_url: "{{ image_url | default('http://172.28.224.62/UCSPE_4.0.4e.ova') }}"
    vm_name: "{{ vm_name | default('ucspe-4-0-4e-orch') }}"
  tasks:
    - name: Get vCenter Moid
      intersight_rest_api:
        <<: *api_info
        resource_path: /asset/DeviceRegistrations
        query_params:
          $filter: DeviceIpAddress eq '172.28.225.220'
      register: vcenter
    - name: Execute OVA deploy workflow
      intersight_rest_api:
        <<: *api_info
        resource_path: /workflow/WorkflowInfos
        update_method: post
        api_body: {
          "Name": "ucspe_vm",
          "Organization": {
            # "Selector": "Name eq 'default'",
            # "ObjectType": "organization.Organization"
            "Moid": "5dde9f116972652d33539d39"
          },
          "Action": "Start",
          "Input": {
            "Vcenter": {
              "Moid": "{{ vcenter.api_response.Moid }}",
              "ObjectType":"asset.DeviceRegistration"
            },
            "Datastore": "Atlanta Data",
            "Image": "{{ image_url }}",
            "VmName": "{{ vm_name }}",
            "PowerOn": false,
            "Datacenter": "SJC07",
            "Cluster": "Atlanta"
          },
          "WorkflowDefinition": {
            "Selector": "Name eq 'ucspe_vm'",
            "ObjectType":"workflow.WorkflowDefinition"
          },
          "WorkflowCtx": {
            "InitiatorCtx": {
              "InitiatorName":"ucspe_vm",
              "InitiatorType":"workflow.WorkflowDefinition"
            }
          }
        }
      register: workflow
    - name: Get status of OVA deploy workflow
      intersight_rest_api:
        <<: *api_info
        resource_path: /workflow/WorkflowInfos
        query_params:
          $expand: ParentTaskInfo($select=WorkflowInfo;$expand=WorkflowInfo($select=WorkflowDefinition))
          $filter: "Moid eq '{{ workflow.api_response.Moid }}'"
      register: status
      until: status.api_response.Status != 'RUNNING' and status.api_response.Status != 'WAITING'
      retries: 10
      delay: 60
      ignore_errors: true
    - debug:
        msg: "Final workflow status: {{ status.api_response.Status }}"
