# Copyright 2019 Google Inc.
# Licensed 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.

---
# Pre-test setup
- name: Create a key ring
  google.cloud.gcp_kms_key_ring:
    name: key-key-ring
    location: us-central1
    project: "{{ gcp_project }}"
    auth_kind: "{{ gcp_cred_kind }}"
    service_account_file: "{{ gcp_cred_file | default(omit) }}"
    state: present
  register: keyring
- name: Delete a crypto key
  google.cloud.gcp_kms_crypto_key:
    name: "{{ resource_name }}"
    key_ring: projects/{{ gcp_project }}/locations/us-central1/keyRings/key-key-ring
    project: "{{ gcp_project }}"
    auth_kind: "{{ gcp_cred_kind }}"
    service_account_file: "{{ gcp_cred_file | default(omit) }}"
    state: absent
#----------------------------------------------------------
- name: Create a crypto key
  google.cloud.gcp_kms_crypto_key:
    name: "{{ resource_name }}"
    key_ring: projects/{{ gcp_project }}/locations/us-central1/keyRings/key-key-ring
    project: "{{ gcp_project }}"
    auth_kind: "{{ gcp_cred_kind }}"
    service_account_file: "{{ gcp_cred_file | default(omit) }}"
    state: present
  register: result
- name: Assert changed is true
  ansible.builtin.assert:
    that:
      - result.changed == true
- name: Verify that crypto_key was created
  google.cloud.gcp_kms_crypto_key_info:
    key_ring: projects/{{ gcp_project }}/locations/us-central1/keyRings/key-key-ring
    project: "{{ gcp_project }}"
    auth_kind: "{{ gcp_cred_kind }}"
    service_account_file: "{{ gcp_cred_file | default(omit) }}"
    scopes:
      - https://www.googleapis.com/auth/cloudkms
  register: results
- name: Verify that command succeeded
  ansible.builtin.assert:
    that:
      - results['resources'] | map(attribute='name') | select("match", ".*{{ resource_name }}.*") | list | length == 1
# ----------------------------------------------------------------------------
- name: Create a crypto key that already exists
  google.cloud.gcp_kms_crypto_key:
    name: "{{ resource_name }}"
    key_ring: projects/{{ gcp_project }}/locations/us-central1/keyRings/key-key-ring
    project: "{{ gcp_project }}"
    auth_kind: "{{ gcp_cred_kind }}"
    service_account_file: "{{ gcp_cred_file | default(omit) }}"
    state: present
  register: result
- name: Assert changed is false
  ansible.builtin.assert:
    that:
      - result.changed == false
