AWSTemplateFormatVersion: '2010-09-09'
Description: >
  DocumentDB and Neptune Snapshot Review Remediator.
  Purpose-specific, opt-in remediation module for reviewing Amazon DocumentDB
  and Amazon Neptune clusters and manual cluster snapshots. Optional remediation
  deletes explicitly approved old manual snapshots only. It does not delete clusters.

Parameters:
  ProjectName:
    Type: String
    Default: docdb-neptune-snapshot-review
    Description: Short base name used for created resources.

  TargetRegionsCsv:
    Type: String
    Default: all-enabled
    Description: Comma-separated AWS Regions to scan, or all-enabled to scan all enabled Regions.

  ExcludedRegionsCsv:
    Type: String
    Default: ap-northeast-3
    Description: Comma-separated AWS Regions to exclude from scanning/remediation.

  DryRun:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: When true, only report what would happen. When false, perform eligible approved snapshot deletion.

  ActionMode:
    Type: String
    Default: review-only
    AllowedValues:
      - review-only
      - delete-approved-manual-snapshots
    Description: review-only never changes resources. delete-approved-manual-snapshots deletes eligible approved manual snapshots.

  MinimumSnapshotAgeDays:
    Type: Number
    Default: 180
    Description: Manual snapshot must be at least this many days old before deletion consideration.

  IncludeDocumentDB:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Include Amazon DocumentDB clusters and manual cluster snapshots.

  IncludeNeptune:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Include Amazon Neptune clusters and manual DB cluster snapshots.

  RequireApprovalTag:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Snapshot deletion requires ApprovalTagKey=ApprovalTagValue when true.

  ApprovalTagKey:
    Type: String
    Default: CostOptApproved
    Description: Tag key required when RequireApprovalTag is true.

  ApprovalTagValue:
    Type: String
    Default: 'true'
    Description: Tag value required when RequireApprovalTag is true.

  IgnoreTagKeysCsv:
    Type: String
    Default: CostOptIgnore,DoNotDelete,DoNotModify,ComplianceHold,LegalHold,Production,prod
    Description: Comma-separated tag keys that prevent snapshot deletion.

  IgnoreTagPairsCsv:
    Type: String
    Default: CostOptIgnore=true,DoNotDelete=true,DoNotModify=true,ComplianceHold=true,LegalHold=true,Environment=Production,Environment=Prod
    Description: Comma-separated key=value tag pairs that prevent snapshot deletion.

  IncludeSnapshotIdPrefixesCsv:
    Type: String
    Default: ''
    Description: Optional comma-separated snapshot identifier prefixes to include. Leave blank to include all.

  ExcludeSnapshotIdPrefixesCsv:
    Type: String
    Default: ''
    Description: Optional comma-separated snapshot identifier prefixes to exclude.

  MaxSnapshotsPerRun:
    Type: Number
    Default: 50
    Description: Safety limit. 0 means no limit. Recommended actual deletion batch is 1 to 10.

  ContinueOnAccessDenied:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Continue scanning other Regions/resources when blocked by IAM/SCP.

  ScheduleEnabled:
    Type: String
    Default: 'false'
    AllowedValues: ['true', 'false']
    Description: Whether to create an enabled EventBridge schedule.

  ScheduleExpression:
    Type: String
    Default: rate(30 days)
    Description: EventBridge schedule expression used when ScheduleEnabled is true.

Conditions:
  IsScheduleEnabled: !Equals [!Ref ScheduleEnabled, 'true']

Resources:
  RemediatorRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: DocDbNeptuneSnapshotReviewPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: DiscoverRegions
                Effect: Allow
                Action:
                  - ec2:DescribeRegions
                Resource: '*'
              - Sid: ReadDocumentDBAndNeptune
                Effect: Allow
                Action:
                  - docdb:DescribeDBClusters
                  - docdb:DescribeDBClusterSnapshots
                  - docdb:ListTagsForResource
                  - rds:DescribeDBClusters
                  - rds:DescribeDBClusterSnapshots
                  - rds:ListTagsForResource
                Resource: '*'
              - Sid: DeleteApprovedManualSnapshots
                Effect: Allow
                Action:
                  - docdb:DeleteDBClusterSnapshot
                  - rds:DeleteDBClusterSnapshot
                Resource: '*'

  RemediatorFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Ref ProjectName
      Description: Purpose-specific Lambda for DocumentDB and Neptune snapshot review and guarded manual snapshot cleanup.
      Runtime: python3.12
      Handler: index.handler
      Timeout: 900
      MemorySize: 512
      Role: !GetAtt RemediatorRole.Arn
      Environment:
        Variables:
          TARGET_REGIONS_CSV: !Ref TargetRegionsCsv
          EXCLUDED_REGIONS_CSV: !Ref ExcludedRegionsCsv
          DRY_RUN: !Ref DryRun
          ACTION_MODE: !Ref ActionMode
          MINIMUM_SNAPSHOT_AGE_DAYS: !Ref MinimumSnapshotAgeDays
          INCLUDE_DOCUMENTDB: !Ref IncludeDocumentDB
          INCLUDE_NEPTUNE: !Ref IncludeNeptune
          REQUIRE_APPROVAL_TAG: !Ref RequireApprovalTag
          APPROVAL_TAG_KEY: !Ref ApprovalTagKey
          APPROVAL_TAG_VALUE: !Ref ApprovalTagValue
          IGNORE_TAG_KEYS_CSV: !Ref IgnoreTagKeysCsv
          IGNORE_TAG_PAIRS_CSV: !Ref IgnoreTagPairsCsv
          INCLUDE_SNAPSHOT_ID_PREFIXES_CSV: !Ref IncludeSnapshotIdPrefixesCsv
          EXCLUDE_SNAPSHOT_ID_PREFIXES_CSV: !Ref ExcludeSnapshotIdPrefixesCsv
          MAX_SNAPSHOTS_PER_RUN: !Ref MaxSnapshotsPerRun
          CONTINUE_ON_ACCESS_DENIED: !Ref ContinueOnAccessDenied
      Code:
        ZipFile: |
          import json
          import os
          import traceback
          from datetime import datetime, timezone

          import boto3
          from botocore.exceptions import ClientError

          def now():
              return datetime.now(timezone.utc)

          def split_csv(value):
              return [x.strip() for x in str(value or '').split(',') if x.strip()]

          def env_bool(name, default=False):
              return os.environ.get(name, str(default)).strip().lower() in ('1', 'true', 'yes', 'y')

          def env_int(name, default=0):
              try:
                  return int(os.environ.get(name, str(default)).strip())
              except Exception:
                  return default

          def parse_tag_pairs(value):
              pairs = {}
              for item in split_csv(value):
                  if '=' not in item:
                      continue
                  key, val = item.split('=', 1)
                  if key.strip():
                      pairs[key.strip()] = val.strip()
              return pairs

          def age_days(dt):
              if not dt:
                  return None
              if dt.tzinfo is None:
                  dt = dt.replace(tzinfo=timezone.utc)
              return (now() - dt).days

          def enabled_regions(excluded):
              requested = os.environ.get('TARGET_REGIONS_CSV', 'all-enabled').strip()
              if requested and requested.lower() != 'all-enabled':
                  regions = split_csv(requested)
              else:
                  ec2 = boto3.client('ec2', region_name=os.environ.get('AWS_REGION', 'us-east-1'))
                  response = ec2.describe_regions(AllRegions=False)
                  regions = sorted([r['RegionName'] for r in response.get('Regions', [])])
              return [r for r in regions if r not in excluded]

          def paginate(client, operation_name, result_key, **kwargs):
              items = []
              try:
                  paginator = client.get_paginator(operation_name)
                  for page in paginator.paginate(**kwargs):
                      items.extend(page.get(result_key, []))
                  return items
              except Exception:
                  request = dict(kwargs)
                  while True:
                      response = getattr(client, operation_name)(**request)
                      items.extend(response.get(result_key, []))
                      marker = response.get('Marker')
                      if not marker:
                          break
                      request['Marker'] = marker
                  return items

          def tags_to_dict(tag_list):
              return {t.get('Key'): t.get('Value', '') for t in tag_list or [] if t.get('Key')}

          def safe_tags(client, arn):
              if not arn:
                  return {}, None
              try:
                  response = client.list_tags_for_resource(ResourceName=arn)
                  return tags_to_dict(response.get('TagList', [])), None
              except ClientError as e:
                  return {}, e

          def has_ignore_tag(tags, ignore_keys, ignore_pairs):
              for key in ignore_keys:
                  if key in tags:
                      return True, 'ignore_tag_key=' + key
              for key, value in ignore_pairs.items():
                  if tags.get(key) == value:
                      return True, 'ignore_tag_pair=' + key + '=' + value
              return False, ''

          def has_approval_tag(tags, settings):
              if not settings['require_approval_tag']:
                  return True
              return tags.get(settings['approval_tag_key']) == settings['approval_tag_value']

          def name_included(name, include_prefixes):
              if not include_prefixes:
                  return True
              return any((name or '').startswith(prefix) for prefix in include_prefixes)

          def name_excluded(name, exclude_prefixes):
              if not exclude_prefixes:
                  return False
              return any((name or '').startswith(prefix) for prefix in exclude_prefixes)

          def service_config(service_name, region):
              if service_name == 'documentdb':
                  return {
                      'service_name': 'documentdb',
                      'client': boto3.client('docdb', region_name=region),
                      'cluster_op': 'describe_db_clusters',
                      'cluster_key': 'DBClusters',
                      'snapshot_op': 'describe_db_cluster_snapshots',
                      'snapshot_key': 'DBClusterSnapshots',
                      'delete_op': 'delete_db_cluster_snapshot'
                  }
              return {
                  'service_name': 'neptune',
                  'client': boto3.client('rds', region_name=region),
                  'cluster_op': 'describe_db_clusters',
                  'cluster_key': 'DBClusters',
                  'snapshot_op': 'describe_db_cluster_snapshots',
                  'snapshot_key': 'DBClusterSnapshots',
                  'delete_op': 'delete_db_cluster_snapshot'
              }

          def list_clusters(cfg):
              clusters = paginate(cfg['client'], cfg['cluster_op'], cfg['cluster_key'])
              if cfg['service_name'] == 'neptune':
                  clusters = [c for c in clusters if str(c.get('Engine', '')).lower().startswith('neptune')]
              return clusters

          def list_manual_snapshots(cfg):
              snapshots = paginate(cfg['client'], cfg['snapshot_op'], cfg['snapshot_key'], SnapshotType='manual')
              if cfg['service_name'] == 'neptune':
                  snapshots = [s for s in snapshots if str(s.get('Engine', '')).lower().startswith('neptune')]
              return snapshots

          def cluster_inventory(cluster, service_name):
              return {
                  'service': service_name,
                  'db_cluster_identifier': cluster.get('DBClusterIdentifier'),
                  'engine': cluster.get('Engine'),
                  'engine_version': cluster.get('EngineVersion'),
                  'status': cluster.get('Status'),
                  'database_name': cluster.get('DatabaseName'),
                  'multi_az': cluster.get('MultiAZ'),
                  'storage_encrypted': cluster.get('StorageEncrypted'),
                  'kms_key_id': cluster.get('KmsKeyId'),
                  'backup_retention_period': cluster.get('BackupRetentionPeriod'),
                  'preferred_backup_window': cluster.get('PreferredBackupWindow'),
                  'cluster_create_time': str(cluster.get('ClusterCreateTime')) if cluster.get('ClusterCreateTime') else None,
                  'deletion_protection': cluster.get('DeletionProtection'),
                  'db_cluster_members_count': len(cluster.get('DBClusterMembers', []) or []),
                  'vpc_security_groups': [sg.get('VpcSecurityGroupId') for sg in cluster.get('VpcSecurityGroups', []) if sg.get('VpcSecurityGroupId')]
              }

          def scan_service(region, service_name, settings):
              cfg = service_config(service_name, region)
              result = {
                  'service': service_name,
                  'clusters': 0,
                  'manual_snapshots': 0,
                  'old_manual_snapshots': 0,
                  'eligible': 0,
                  'would_delete_snapshots': 0,
                  'deleted_snapshots': 0,
                  'skipped_too_new': 0,
                  'skipped_include_prefix': 0,
                  'skipped_exclude_prefix': 0,
                  'skipped_missing_approval_tag': 0,
                  'skipped_ignore_tag': 0,
                  'tag_read_access_denied': 0,
                  'access_denied': 0,
                  'failed': 0,
                  'failures': [],
                  'cluster_inventory': [],
                  'candidates': [],
                  'deleted_snapshot_identifiers': []
              }

              try:
                  clusters = list_clusters(cfg)
                  snapshots = list_manual_snapshots(cfg)
              except ClientError as e:
                  code = e.response.get('Error', {}).get('Code', 'Unknown')
                  message = e.response.get('Error', {}).get('Message', str(e))
                  result['failures'].append({'operation': 'DescribeResources', 'error_code': code, 'error_message': message})
                  if code in ('AccessDenied', 'AccessDeniedException', 'UnauthorizedOperation') or 'explicit deny' in message.lower():
                      result['access_denied'] += 1
                  else:
                      result['failed'] += 1
                  if not settings['continue_on_access_denied']:
                      raise
                  return result

              result['clusters'] = len(clusters)
              result['manual_snapshots'] = len(snapshots)
              result['cluster_inventory'] = [cluster_inventory(c, service_name) for c in clusters]

              for snap in snapshots:
                  if settings['max_snapshots_per_run'] and (result['would_delete_snapshots'] + result['deleted_snapshots']) >= settings['max_snapshots_per_run']:
                      result['stopped_due_to_max_snapshots_per_run'] = True
                      return result

                  snapshot_id = snap.get('DBClusterSnapshotIdentifier')
                  cluster_id = snap.get('DBClusterIdentifier')
                  created = snap.get('SnapshotCreateTime')
                  snap_age = age_days(created)
                  arn = snap.get('DBClusterSnapshotArn')
                  tags, tag_error = safe_tags(cfg['client'], arn)

                  item = {
                      'service': service_name,
                      'region': region,
                      'db_cluster_snapshot_identifier': snapshot_id,
                      'db_cluster_identifier': cluster_id,
                      'snapshot_type': snap.get('SnapshotType'),
                      'status': snap.get('Status'),
                      'engine': snap.get('Engine'),
                      'engine_version': snap.get('EngineVersion'),
                      'allocated_storage': snap.get('AllocatedStorage'),
                      'storage_encrypted': snap.get('StorageEncrypted'),
                      'kms_key_id': snap.get('KmsKeyId'),
                      'snapshot_create_time': str(created) if created else None,
                      'age_days': snap_age,
                      'arn': arn,
                      'tags': tags
                  }

                  if tag_error:
                      code = tag_error.response.get('Error', {}).get('Code', 'Unknown')
                      message = tag_error.response.get('Error', {}).get('Message', str(tag_error))
                      item['tag_read_error'] = {'error_code': code, 'error_message': message}
                      if code in ('AccessDenied', 'AccessDeniedException') or 'explicit deny' in message.lower():
                          result['tag_read_access_denied'] += 1
                      else:
                          result['failed'] += 1

                  if not name_included(snapshot_id, settings['include_snapshot_prefixes']):
                      result['skipped_include_prefix'] += 1
                      continue

                  if name_excluded(snapshot_id, settings['exclude_snapshot_prefixes']):
                      result['skipped_exclude_prefix'] += 1
                      item['action'] = 'skipped_exclude_prefix'
                      result['candidates'].append(item)
                      continue

                  if snap_age is None or snap_age < settings['minimum_snapshot_age_days']:
                      result['skipped_too_new'] += 1
                      item['action'] = 'skipped_too_new'
                      result['candidates'].append(item)
                      continue

                  result['old_manual_snapshots'] += 1

                  ignore, reason = has_ignore_tag(tags, settings['ignore_tag_keys'], settings['ignore_tag_pairs'])
                  if ignore:
                      result['skipped_ignore_tag'] += 1
                      item['action'] = 'skipped_ignore_tag'
                      item['reason'] = reason
                      result['candidates'].append(item)
                      continue

                  if not has_approval_tag(tags, settings):
                      result['skipped_missing_approval_tag'] += 1
                      item['action'] = 'skipped_missing_approval_tag'
                      item['required_tag'] = settings['approval_tag_key'] + '=' + settings['approval_tag_value']
                      result['candidates'].append(item)
                      continue

                  result['eligible'] += 1

                  if settings['action_mode'] != 'delete-approved-manual-snapshots':
                      item['action'] = 'review_only_candidate'
                      result['candidates'].append(item)
                      continue

                  if settings['dry_run']:
                      result['would_delete_snapshots'] += 1
                      item['action'] = 'would_delete_snapshot'
                      result['candidates'].append(item)
                      continue

                  try:
                      getattr(cfg['client'], cfg['delete_op'])(DBClusterSnapshotIdentifier=snapshot_id)
                      result['deleted_snapshots'] += 1
                      item['action'] = 'delete_snapshot'
                      result['deleted_snapshot_identifiers'].append(snapshot_id)
                  except ClientError as e:
                      code = e.response.get('Error', {}).get('Code', 'Unknown')
                      message = e.response.get('Error', {}).get('Message', str(e))
                      result['failures'].append({'snapshot_identifier': snapshot_id, 'operation': 'DeleteDBClusterSnapshot', 'error_code': code, 'error_message': message})
                      if code in ('AccessDenied', 'AccessDeniedException') or 'explicit deny' in message.lower():
                          result['access_denied'] += 1
                      else:
                          result['failed'] += 1
                      if not settings['continue_on_access_denied']:
                          raise

              return result

          def scan_region(region, settings):
              result = {
                  'region': region,
                  'documentdb': {},
                  'neptune': {},
                  'clusters': 0,
                  'manual_snapshots': 0,
                  'old_manual_snapshots': 0,
                  'eligible': 0,
                  'would_delete_snapshots': 0,
                  'deleted_snapshots': 0,
                  'skipped_too_new': 0,
                  'skipped_missing_approval_tag': 0,
                  'skipped_ignore_tag': 0,
                  'tag_read_access_denied': 0,
                  'access_denied': 0,
                  'failed': 0
              }

              services = []
              if settings['include_documentdb']:
                  services.append('documentdb')
              if settings['include_neptune']:
                  services.append('neptune')

              for service_name in services:
                  sr = scan_service(region, service_name, settings)
                  result[service_name] = sr
                  for key in ('clusters', 'manual_snapshots', 'old_manual_snapshots', 'eligible',
                              'would_delete_snapshots', 'deleted_snapshots', 'skipped_too_new',
                              'skipped_missing_approval_tag', 'skipped_ignore_tag',
                              'tag_read_access_denied', 'access_denied', 'failed'):
                      result[key] += int(sr.get(key, 0) or 0)

              return result

          def handler(event, context):
              settings = {
                  'excluded_regions': split_csv(os.environ.get('EXCLUDED_REGIONS_CSV', '')),
                  'dry_run': env_bool('DRY_RUN', True),
                  'action_mode': os.environ.get('ACTION_MODE', 'review-only'),
                  'minimum_snapshot_age_days': env_int('MINIMUM_SNAPSHOT_AGE_DAYS', 180),
                  'include_documentdb': env_bool('INCLUDE_DOCUMENTDB', True),
                  'include_neptune': env_bool('INCLUDE_NEPTUNE', True),
                  'require_approval_tag': env_bool('REQUIRE_APPROVAL_TAG', True),
                  'approval_tag_key': os.environ.get('APPROVAL_TAG_KEY', 'CostOptApproved'),
                  'approval_tag_value': os.environ.get('APPROVAL_TAG_VALUE', 'true'),
                  'ignore_tag_keys': split_csv(os.environ.get('IGNORE_TAG_KEYS_CSV', '')),
                  'ignore_tag_pairs': parse_tag_pairs(os.environ.get('IGNORE_TAG_PAIRS_CSV', '')),
                  'include_snapshot_prefixes': split_csv(os.environ.get('INCLUDE_SNAPSHOT_ID_PREFIXES_CSV', '')),
                  'exclude_snapshot_prefixes': split_csv(os.environ.get('EXCLUDE_SNAPSHOT_ID_PREFIXES_CSV', '')),
                  'max_snapshots_per_run': env_int('MAX_SNAPSHOTS_PER_RUN', 50),
                  'continue_on_access_denied': env_bool('CONTINUE_ON_ACCESS_DENIED', True)
              }

              if isinstance(event, dict):
                  if 'dry_run' in event:
                      settings['dry_run'] = bool(event['dry_run'])
                  if 'action_mode' in event:
                      settings['action_mode'] = str(event['action_mode'])
                  if 'require_approval_tag' in event:
                      settings['require_approval_tag'] = bool(event['require_approval_tag'])
                  if 'minimum_snapshot_age_days' in event:
                      settings['minimum_snapshot_age_days'] = int(event['minimum_snapshot_age_days'])
                  if 'max_snapshots_per_run' in event:
                      settings['max_snapshots_per_run'] = int(event['max_snapshots_per_run'])
                  if 'target_regions' in event and event['target_regions']:
                      os.environ['TARGET_REGIONS_CSV'] = ','.join(event['target_regions'])

              if settings['action_mode'] not in ('review-only', 'delete-approved-manual-snapshots'):
                  settings['action_mode'] = 'review-only'

              summary = {
                  'started_at': now().isoformat(),
                  'dry_run': settings['dry_run'],
                  'action_mode': settings['action_mode'],
                  'minimum_snapshot_age_days': settings['minimum_snapshot_age_days'],
                  'include_documentdb': settings['include_documentdb'],
                  'include_neptune': settings['include_neptune'],
                  'require_approval_tag': settings['require_approval_tag'],
                  'approval_tag': settings['approval_tag_key'] + '=' + settings['approval_tag_value'],
                  'max_snapshots_per_run': settings['max_snapshots_per_run'],
                  'excluded_regions': settings['excluded_regions'],
                  'regions': [],
                  'totals': {
                      'clusters': 0,
                      'manual_snapshots': 0,
                      'old_manual_snapshots': 0,
                      'eligible': 0,
                      'would_delete_snapshots': 0,
                      'deleted_snapshots': 0,
                      'skipped_too_new': 0,
                      'skipped_missing_approval_tag': 0,
                      'skipped_ignore_tag': 0,
                      'tag_read_access_denied': 0,
                      'access_denied': 0,
                      'failed': 0
                  },
                  'region_results': []
              }

              try:
                  regions = enabled_regions(settings['excluded_regions'])
                  summary['regions'] = regions
                  for region in regions:
                      try:
                          rr = scan_region(region, settings)
                      except Exception as e:
                          rr = {
                              'region': region,
                              'documentdb': {},
                              'neptune': {},
                              'clusters': 0,
                              'manual_snapshots': 0,
                              'old_manual_snapshots': 0,
                              'eligible': 0,
                              'would_delete_snapshots': 0,
                              'deleted_snapshots': 0,
                              'skipped_too_new': 0,
                              'skipped_missing_approval_tag': 0,
                              'skipped_ignore_tag': 0,
                              'tag_read_access_denied': 0,
                              'access_denied': 0,
                              'failed': 1,
                              'failures': [{'error_code': type(e).__name__, 'error_message': str(e), 'trace': traceback.format_exc()}]
                          }
                      summary['region_results'].append(rr)
                      for key in summary['totals']:
                          summary['totals'][key] += int(rr.get(key, 0) or 0)
              finally:
                  summary['ended_at'] = now().isoformat()
                  print(json.dumps(summary, indent=2, default=str))
              return summary

  RemediatorScheduleRule:
    Type: AWS::Events::Rule
    Condition: IsScheduleEnabled
    Properties:
      Name: !Sub '${ProjectName}-schedule'
      Description: Scheduled run for DocumentDB and Neptune Snapshot Review Remediator.
      ScheduleExpression: !Ref ScheduleExpression
      State: ENABLED
      Targets:
        - Arn: !GetAtt RemediatorFunction.Arn
          Id: DocDbNeptuneSnapshotReviewTarget
          Input: '{"source":"eventbridge-schedule","dry_run":true,"action_mode":"review-only"}'

  RemediatorSchedulePermission:
    Type: AWS::Lambda::Permission
    Condition: IsScheduleEnabled
    Properties:
      FunctionName: !Ref RemediatorFunction
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt RemediatorScheduleRule.Arn

Outputs:
  RemediatorFunctionName:
    Description: Lambda function name.
    Value: !Ref RemediatorFunction

  RemediatorFunctionArn:
    Description: Lambda function ARN.
    Value: !GetAtt RemediatorFunction.Arn

  DryRunSetting:
    Description: Current DryRun setting.
    Value: !Ref DryRun

  ActionModeSetting:
    Description: Current ActionMode setting.
    Value: !Ref ActionMode
