---
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# This file is imported in create_log_analytics_ws.yml and terminate_cluster.yml
#

- name: Generate name for Workspace, Dashboard and Workbook
  shell: set -o pipefail && echo -n {{ resource_group + vmss_name + location }} | md5sum | tr -cd "[:alnum:]" | cut -c 1-48
  args:
    executable: bash
  changed_when: false
  register: monitor_name

- name: Set name for log analytics workspace
  set_fact:
     log_workspace_name: "{{ monitor_name.stdout + '-la' }}"

- name: Set name for dashboard
  set_fact:
     dashboard_name: "{{ monitor_name.stdout + '-db' }}"

- name: Set display name for workbook
  set_fact:
    workbook_title: "{{ monitor_name.stdout + '-wb' }}"

- name: Query all the resources in the resource group
  azure_rm_resource_info:
    resource_group: "{{ resource_group }}"
    resource_type: resources
  register: rgfacts

- name: Retrieve workbook and dashboard info (name, existance)
  set_fact:
    workbook_name: "{{ rgfacts.response|selectattr('type', 'equalto', 'microsoft.insights/workbooks')|selectattr('tags.hidden-title', 'equalto', workbook_title)|map(attribute='name')|join('') }}"
    workbook_exists: "{{ rgfacts.response|selectattr('type', 'equalto', 'microsoft.insights/workbooks')|map(attribute='tags')|selectattr('hidden-title','equalto', workbook_title)|length > 0 }}"
    dashboard_exists: "{{ rgfacts.response|selectattr('type', 'equalto', 'Microsoft.Portal/dashboards')|selectattr('name', 'equalto', dashboard_name)|length > 0 }}"
