---
- hosts: keystone
  tasks:
  - name: Check for containerized keystone fernet repository
    stat:
      path: /var/lib/config-data/puppet-generated/keystone/etc/keystone/fernet-keys/
    register: containerized_keystone_dir

  - set_fact:
      is_container: containerized_keystone_dir.stat.isdir is defined and containerized_keystone_dir.stat.isdir

  - name: Rotate fernet keys for keystone container
    block:
      - set_fact:
          keystone_base: /var/lib/config-data/puppet-generated/keystone

      - name: Remove previous fernet keys
        shell: rm -rf /var/lib/config-data/puppet-generated/keystone/etc/keystone/fernet-keys/*
        args:
          warn: false

      - name: Persist fernet keys to repository
        copy:
          dest: "{{ keystone_base }}{{ item.key }}"
          content: "{{ item.value.content }}"
          mode: 0600
        with_dict: "{{ fernet_keys }}"
        no_log: true

      - name: Set permissions to match container's user
        shell: chown --reference={{ keystone_base }}/etc/keystone/fernet-keys {{ keystone_base }}{{ item.key }}
        with_dict: "{{ fernet_keys }}"
        no_log: true

      - name: Restart keystone container
        shell: docker restart keystone
    when: is_container

  - name: Rotate fernet keys for keystone (no container)
    block:
      - name: Remove previous fernet keys
        shell: rm -rf /etc/keystone/fernet-keys/*
        args:
          warn: false

      - name: Persist fernet keys to repository
        copy:
          dest: "{{ item.key }}"
          content: "{{ item.value.content }}"
          mode: 0600
          owner: keystone
          group: keystone
        with_dict: "{{ fernet_keys }}"
        no_log: true

      - name: Reload apache
        service:
          name: httpd
          state: reloaded
    when: not is_container
