{% extends "aws/base_resource.tf.j2" %}
{% block resources %}
{% for secret in resources %}
{{ resource_spacer() }}
resource "aws_secretsmanager_secret" "{{ secret.name_sanitized }}" {
  name = "{{ secret.Name }}"

  {% if secret.get('Description') %}
  description = "{{ secret.Description | replace('"', '\\"') }}"
  {%  endif %}

  {% if secret.get('kms_encrypted') and secret.get('kms_key_id') %}
  kms_key_id = "{{ secret.kms_key_id }}"
  {%  endif %}

  {% if secret.get('replica_regions_formatted') %}
  {% for replica in secret.replica_regions_formatted %}
  replica {
    region = "{{ replica.region }}"
    {% if replica.get('kms_key_id') %}
    kms_key_id = "{{ replica.kms_key_id }}"
    {%  endif %}
  }
  {% endfor %}
  {%  endif %}

  {% if secret.get('rotation_enabled') and secret.get('rotation_rules_formatted') and secret.rotation_rules_formatted.get('automatically_after_days') and secret.get('rotation_lambda_arn') %}
  rotation_lambda_arn = "{{ secret.rotation_lambda_arn }}"
  
  rotation_rules {
    automatically_after_days = {{ secret.rotation_rules_formatted.automatically_after_days }}
  }
  {%  endif %}

  recovery_window_in_days = {{ 30 if not secret.get('is_deleted') else 0 }}

  {% set has_any_tags = secret.get('tags_formatted') or secret.get('secret_type') or (secret.get('is_aws_managed') and secret.get('OwningService')) %}
  {% if has_any_tags %}
  {% set tags_dict = secret.get('tags_formatted', {}).copy() %}
  {% if secret.get('secret_type') %}{% set _ = tags_dict.update({'SecretType': secret.secret_type}) %}{% endif %}
  {% if secret.get('is_aws_managed') and secret.get('OwningService') %}{% set _ = tags_dict.update({'ManagedBy': secret.OwningService}) %}{% endif %}
  {{ common_macros.render_map('tags', tags_dict, 2) }}
  {% endif %}

  {% if secret.get('is_deleted') %}
  lifecycle {
    prevent_destroy = false
  }
  {% else %}
  lifecycle {
    prevent_destroy = true
  }
  {%  endif %}
}

{% if secret.get('resource_policy') %}
resource "aws_secretsmanager_secret_policy" "{{ secret.name_sanitized }}" {
  secret_arn = aws_secretsmanager_secret.{{ secret.name_sanitized }}.arn
  policy     = jsonencode({{ secret.resource_policy | tojson | safe }})
}
{%  endif %}

{% endfor %}
{% endblock %}
