---
version: '2.0'

crawl_data_from_vms:
  input:
    - gateway_host
    - private_key_filename: id_rsa
    - vm_ids: null
    - username: ubuntu
    - filename: /var/log/auth.log

    # Email info
    - smtp_server: null
    - smtp_password: null
    - from_email: null
    - to_email: null

  tasks:
    schedule_get_data:
      on-success:
        - get_hosts: <% $.vm_ids != null %>
        - get_vms: <% $.vm_ids = null %>

    get_vms:
      action: nova.servers_list
      publish:
        vm_ids: <% task(get_vms).result.id %>
      keep-result: false
      on-success:
        - get_hosts

    get_hosts:
      with-items: id in <% $.vm_ids %>
      action: nova.servers_get server=<% $.id %>
      publish:
        hosts: <% task(get_hosts).result.select({ip => $.addresses.get($.addresses.keys().first()).where($.get("OS-EXT-IPS:type") = fixed).first().addr}).ip %>
      keep-result: false
      on-success:
        - get_data

    get_data:
      with-items: host in <% $.hosts %>
      action: std.ssh_proxied
      input:
        host: <% $.host %>
        username: <% $.username %>
        private_key_filename: <% $.private_key_filename %>
        gateway_host: <% $.gateway_host %>
        cmd: "cat <% $.filename %>"
      on-success:
        - send_report_email: <% $.smtp_server != null %>
      on-error:
        - send_error_email: <% $.smtp_server != null %>

    send_report_email:
      action: std.email
      input:
        from_addr: <% $.from_email %>
        to_addrs: [<% $.to_email %>]
        smtp_server: <% $.smtp_server %>
        smtp_password: <% $.smtp_password %>
        subject: VMs data from tenant
        body: |
          VMs data from tenant <% $.openstack.project_id %>:

          <% json_pp(task(get_data).result).replace("\\n", "\n") %>

    send_error_email:
      action: std.email
      input:
        from_addr: <% $.from_email %>
        to_addrs: [<% $.to_email %>]
        smtp_server: <% $.smtp_server %>
        smtp_password: <% $.smtp_password %>
        subject: (ERROR) VMs data from tenant
        body: |
          Failure while getting data from VMs: <% execution().state_info %>
