---
- name: deallocate vm
  command: >
    az vm deallocate
    -g "{{ openshift_azure_resource_group_name }}"
    -n vm

- name: generalize vm
  command: >
    az vm generalize
    -g "{{ openshift_azure_resource_group_name }}"
    -n vm

- name: get vm details
  command: >
    az vm show
    -g "{{ openshift_azure_resource_group_name }}"
    -n vm
  register: vm

- name: create image resource group
  azure_rm_resourcegroup:
    name: "{{ image_resource_group }}"
    location: "{{ openshift_azure_resource_location }}"

- name: create image
  command: >
    az image create
    -g "{{ image_resource_group }}"
    -n "{{ image_name }}"
    --source "{{ (vm.stdout | from_json).storageProfile.osDisk.managedDisk.id }}"
    --os-type Linux

- name: get input image tags
  command: az image show -g "{{ openshift_azure_input_image_ns }}" -n "{{ (input_image.stdout | from_json).name }}"
  register: input_image_tags

- name: remove valid tag from input image tags
  set_fact:
    input_image_tags_no_valid: "{{ {} | combine({item.key: item.value}) }}"
  when: item.key not in ['valid']
  with_dict: "{{ (input_image_tags.stdout | from_json).tags }}"

- name: calculate final tags
  set_fact:
    final_tags: "{{ input_image_tags_no_valid | default({}) | combine(image_tags) }}"

- name: tag image
  command: >
    az resource tag
    --resource-type Microsoft.Compute/images
    -g "{{ image_resource_group }}"
    -n "{{ image_name }}"
    --tags {% for k in final_tags %}{{ k }}={{ final_tags[k] }} {% endfor %}

- name: log image resource group and name
  debug:
    msg: "{{ item }}"
  with_items:
  - "Resource group: {{ image_resource_group }}"
  - "Image name: {{ image_name }}"

- name: log image tag information
  debug:
    msg: "{{ item.key }}: {{ item.value }}"
  with_dict: "{{ final_tags }}"
