AWSTemplateFormatVersion: '2010-09-09'
Description: >
  Secrets Manager Unused Secret Review Remediator.
  Purpose-specific, opt-in remediation module for reviewing AWS Secrets Manager
  secrets that may be unused, old, or costly. Optional remediation schedules
  deletion for explicitly approved secrets using a recovery window.

Parameters:
  ProjectName:
    Type: String
    Default: secrets-unused-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 actions.

  ActionMode:
    Type: String
    Default: review-only
    AllowedValues:
      - review-only
      - schedule-approved-secret-deletion
    Description: review-only never changes resources. schedule-approved-secret-deletion schedules deletion for eligible approved secrets.

  MinimumSecretAgeDays:
    Type: Number
    Default: 180
    Description: Secret must be at least this many days old to be considered a deletion candidate.

  MinimumDaysSinceLastAccessed:
    Type: Number
    Default: 180
    Description: If LastAccessedDate exists, it must be this many days ago or older. Secrets never accessed are evaluated by age.

  IncludeNeverAccessedSecrets:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: When true, secrets with no LastAccessedDate can be considered candidates if old enough.

  SkipRotatingSecrets:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Skip secrets with rotation enabled.

  SkipReplicatedSecrets:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Skip secrets with replica Regions.

  RecoveryWindowInDays:
    Type: Number
    Default: 30
    MinValue: 7
    MaxValue: 30
    Description: Recovery window used when scheduling deletion.

  RequireApprovalTag:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Secret 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 deletion when present.

  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 deletion.

  IncludeSecretNamePrefixesCsv:
    Type: String
    Default: ''
    Description: Optional comma-separated secret name prefixes to include. Leave blank to include all.

  ExcludeSecretNamePrefixesCsv:
    Type: String
    Default: ''
    Description: Optional comma-separated secret name prefixes to exclude.

  MaxSecretsPerRun:
    Type: Number
    Default: 100
    Description: Safety limit. 0 means no limit. Recommended actual remediation batch is 1 to 10.

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

  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: SecretsManagerUnusedReviewPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: DiscoverRegions
                Effect: Allow
                Action:
                  - ec2:DescribeRegions
                Resource: '*'
              - Sid: ReadSecrets
                Effect: Allow
                Action:
                  - secretsmanager:ListSecrets
                  - secretsmanager:DescribeSecret
                  - secretsmanager:ListSecretVersionIds
                Resource: '*'
              - Sid: ScheduleApprovedSecretDeletion
                Effect: Allow
                Action:
                  - secretsmanager:DeleteSecret
                Resource: '*'

  RemediatorFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Ref ProjectName
      Description: Purpose-specific Lambda for Secrets Manager unused secret review and guarded deletion scheduling.
      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_SECRET_AGE_DAYS: !Ref MinimumSecretAgeDays
          MINIMUM_DAYS_SINCE_LAST_ACCESSED: !Ref MinimumDaysSinceLastAccessed
          INCLUDE_NEVER_ACCESSED_SECRETS: !Ref IncludeNeverAccessedSecrets
          SKIP_ROTATING_SECRETS: !Ref SkipRotatingSecrets
          SKIP_REPLICATED_SECRETS: !Ref SkipReplicatedSecrets
          RECOVERY_WINDOW_IN_DAYS: !Ref RecoveryWindowInDays
          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_SECRET_NAME_PREFIXES_CSV: !Ref IncludeSecretNamePrefixesCsv
          EXCLUDE_SECRET_NAME_PREFIXES_CSV: !Ref ExcludeSecretNamePrefixesCsv
          MAX_SECRETS_PER_RUN: !Ref MaxSecretsPerRun
          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 utc_now():
              return datetime.now(timezone.utc)

          def utc_now_iso():
              return utc_now().isoformat()

          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 split_csv(value):
              if value is None:
                  return []
              return [x.strip() for x in str(value).split(',') if x.strip()]

          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 get_enabled_regions(excluded_regions):
              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_regions]

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

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

          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 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 list_secrets(client):
              items = []
              paginator = client.get_paginator('list_secrets')
              for page in paginator.paginate(IncludePlannedDeletion=False):
                  items.extend(page.get('SecretList', []))
              return items

          def version_count(client, secret_id):
              try:
                  total = 0
                  current = 0
                  kwargs = {
                      'SecretId': secret_id,
                      'IncludeDeprecated': True
                  }

                  while True:
                      page = client.list_secret_version_ids(**kwargs)
                      for v in page.get('Versions', []):
                          total += 1
                          if 'AWSCURRENT' in v.get('VersionStages', []):
                              current += 1

                      next_token = page.get('NextToken')
                      if not next_token:
                          break
                      kwargs['NextToken'] = next_token

                  return total, current, None
              except Exception as e:
                  return 0, 0, e

          def scan_region(region, settings):
              client = boto3.client('secretsmanager', region_name=region)
              result = {
                  'region': region,
                  'evaluated_secrets': 0,
                  'secrets': 0,
                  'old_secrets': 0,
                  'never_accessed_secrets': 0,
                  'unused_secrets': 0,
                  'eligible': 0,
                  'would_schedule_deletion': 0,
                  'scheduled_deletion': 0,
                  'skipped_too_new': 0,
                  'skipped_recently_accessed': 0,
                  'skipped_never_accessed_not_included': 0,
                  'skipped_rotation_enabled': 0,
                  'skipped_replicated': 0,
                  'skipped_already_scheduled_deletion': 0,
                  'skipped_include_prefix': 0,
                  'skipped_exclude_prefix': 0,
                  'skipped_missing_approval_tag': 0,
                  'skipped_ignore_tag': 0,
                  'access_denied': 0,
                  'failed': 0,
                  'failures': [],
                  'candidates': [],
                  'scheduled_deletion_secrets': []
              }

              try:
                  secrets = list_secrets(client)
              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': 'ListSecrets', '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

              for secret in secrets:
                  if settings['max_secrets_per_run'] and (result['would_schedule_deletion'] + result['scheduled_deletion']) >= settings['max_secrets_per_run']:
                      result['stopped_due_to_max_secrets_per_run'] = True
                      return result

                  result['evaluated_secrets'] += 1
                  result['secrets'] += 1

                  name = secret.get('Name')
                  arn = secret.get('ARN')
                  created = secret.get('CreatedDate')
                  last_accessed = secret.get('LastAccessedDate')
                  deleted_date = secret.get('DeletedDate')
                  tags = tags_to_dict(secret.get('Tags', []))
                  secret_age = age_days(created)
                  days_since_access = age_days(last_accessed)
                  rotation_enabled = bool(secret.get('RotationEnabled'))
                  replica_regions = secret.get('ReplicationStatus', []) or []

                  total_versions, current_versions, version_error = version_count(client, arn)

                  item = {
                      'name': name,
                      'arn': arn,
                      'region': region,
                      'description': secret.get('Description'),
                      'created_date': str(created) if created else None,
                      'last_accessed_date': str(last_accessed) if last_accessed else None,
                      'deleted_date': str(deleted_date) if deleted_date else None,
                      'age_days': secret_age,
                      'days_since_last_accessed': days_since_access,
                      'rotation_enabled': rotation_enabled,
                      'last_rotated_date': str(secret.get('LastRotatedDate')) if secret.get('LastRotatedDate') else None,
                      'replica_region_count': len(replica_regions),
                      'version_count': total_versions,
                      'current_version_count': current_versions,
                      'tags': tags
                  }

                  if version_error:
                      code = version_error.response.get('Error', {}).get('Code', 'Unknown')
                      message = version_error.response.get('Error', {}).get('Message', str(version_error))
                      item['version_count_error'] = {'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 deleted_date:
                      result['skipped_already_scheduled_deletion'] += 1
                      item['action'] = 'skipped_already_scheduled_deletion'
                      result['candidates'].append(item)
                      continue

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

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

                  if rotation_enabled and settings['skip_rotating_secrets']:
                      result['skipped_rotation_enabled'] += 1
                      item['action'] = 'skipped_rotation_enabled'
                      result['candidates'].append(item)
                      continue

                  if replica_regions and settings['skip_replicated_secrets']:
                      result['skipped_replicated'] += 1
                      item['action'] = 'skipped_replicated'
                      result['candidates'].append(item)
                      continue

                  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 secret_age is None or secret_age < settings['minimum_secret_age_days']:
                      result['skipped_too_new'] += 1
                      item['action'] = 'skipped_too_new'
                      result['candidates'].append(item)
                      continue

                  result['old_secrets'] += 1

                  if last_accessed is None:
                      result['never_accessed_secrets'] += 1
                      if not settings['include_never_accessed_secrets']:
                          result['skipped_never_accessed_not_included'] += 1
                          item['action'] = 'skipped_never_accessed_not_included'
                          result['candidates'].append(item)
                          continue
                  else:
                      if days_since_access is None or days_since_access < settings['minimum_days_since_last_accessed']:
                          result['skipped_recently_accessed'] += 1
                          item['action'] = 'skipped_recently_accessed'
                          result['candidates'].append(item)
                          continue

                  result['unused_secrets'] += 1

                  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'] != 'schedule-approved-secret-deletion':
                      item['action'] = 'review_only_candidate'
                      result['candidates'].append(item)
                      continue

                  item['action'] = 'would_schedule_deletion' if settings['dry_run'] else 'schedule_deletion'
                  item['recovery_window_in_days'] = settings['recovery_window_in_days']

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

                  try:
                      client.delete_secret(
                          SecretId=arn,
                          RecoveryWindowInDays=settings['recovery_window_in_days']
                      )
                      result['scheduled_deletion'] += 1
                      result['scheduled_deletion_secrets'].append(item)
                  except ClientError as e:
                      code = e.response.get('Error', {}).get('Code', 'Unknown')
                      message = e.response.get('Error', {}).get('Message', str(e))
                      result['failures'].append({'secret_arn': arn, 'operation': 'DeleteSecret', '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 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_secret_age_days': env_int('MINIMUM_SECRET_AGE_DAYS', 180),
                  'minimum_days_since_last_accessed': env_int('MINIMUM_DAYS_SINCE_LAST_ACCESSED', 180),
                  'include_never_accessed_secrets': env_bool('INCLUDE_NEVER_ACCESSED_SECRETS', True),
                  'skip_rotating_secrets': env_bool('SKIP_ROTATING_SECRETS', True),
                  'skip_replicated_secrets': env_bool('SKIP_REPLICATED_SECRETS', True),
                  'recovery_window_in_days': env_int('RECOVERY_WINDOW_IN_DAYS', 30),
                  '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_name_prefixes': split_csv(os.environ.get('INCLUDE_SECRET_NAME_PREFIXES_CSV', '')),
                  'exclude_name_prefixes': split_csv(os.environ.get('EXCLUDE_SECRET_NAME_PREFIXES_CSV', '')),
                  'max_secrets_per_run': env_int('MAX_SECRETS_PER_RUN', 100),
                  '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_secret_age_days' in event:
                      settings['minimum_secret_age_days'] = int(event['minimum_secret_age_days'])
                  if 'minimum_days_since_last_accessed' in event:
                      settings['minimum_days_since_last_accessed'] = int(event['minimum_days_since_last_accessed'])
                  if 'include_never_accessed_secrets' in event:
                      settings['include_never_accessed_secrets'] = bool(event['include_never_accessed_secrets'])
                  if 'skip_rotating_secrets' in event:
                      settings['skip_rotating_secrets'] = bool(event['skip_rotating_secrets'])
                  if 'skip_replicated_secrets' in event:
                      settings['skip_replicated_secrets'] = bool(event['skip_replicated_secrets'])
                  if 'recovery_window_in_days' in event:
                      settings['recovery_window_in_days'] = int(event['recovery_window_in_days'])
                  if 'max_secrets_per_run' in event:
                      settings['max_secrets_per_run'] = int(event['max_secrets_per_run'])
                  if 'target_regions' in event and event['target_regions']:
                      os.environ['TARGET_REGIONS_CSV'] = ','.join(event['target_regions'])
                  if 'excluded_regions' in event and event['excluded_regions']:
                      settings['excluded_regions'] = list(event['excluded_regions'])

              if settings['action_mode'] not in ('review-only', 'schedule-approved-secret-deletion'):
                  settings['action_mode'] = 'review-only'

              if settings['recovery_window_in_days'] < 7:
                  settings['recovery_window_in_days'] = 7
              if settings['recovery_window_in_days'] > 30:
                  settings['recovery_window_in_days'] = 30

              summary = {
                  'started_at': utc_now_iso(),
                  'dry_run': settings['dry_run'],
                  'action_mode': settings['action_mode'],
                  'minimum_secret_age_days': settings['minimum_secret_age_days'],
                  'minimum_days_since_last_accessed': settings['minimum_days_since_last_accessed'],
                  'include_never_accessed_secrets': settings['include_never_accessed_secrets'],
                  'skip_rotating_secrets': settings['skip_rotating_secrets'],
                  'skip_replicated_secrets': settings['skip_replicated_secrets'],
                  'recovery_window_in_days': settings['recovery_window_in_days'],
                  'require_approval_tag': settings['require_approval_tag'],
                  'approval_tag': settings['approval_tag_key'] + '=' + settings['approval_tag_value'],
                  'max_secrets_per_run': settings['max_secrets_per_run'],
                  'excluded_regions': settings['excluded_regions'],
                  'regions': [],
                  'totals': {
                      'evaluated_secrets': 0,
                      'secrets': 0,
                      'old_secrets': 0,
                      'never_accessed_secrets': 0,
                      'unused_secrets': 0,
                      'eligible': 0,
                      'would_schedule_deletion': 0,
                      'scheduled_deletion': 0,
                      'skipped_too_new': 0,
                      'skipped_recently_accessed': 0,
                      'skipped_never_accessed_not_included': 0,
                      'skipped_rotation_enabled': 0,
                      'skipped_replicated': 0,
                      'skipped_already_scheduled_deletion': 0,
                      'skipped_include_prefix': 0,
                      'skipped_exclude_prefix': 0,
                      'skipped_missing_approval_tag': 0,
                      'skipped_ignore_tag': 0,
                      'access_denied': 0,
                      'failed': 0
                  },
                  'region_results': []
              }

              try:
                  regions = get_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,
                              'evaluated_secrets': 0,
                              'secrets': 0,
                              'old_secrets': 0,
                              'never_accessed_secrets': 0,
                              'unused_secrets': 0,
                              'eligible': 0,
                              'would_schedule_deletion': 0,
                              'scheduled_deletion': 0,
                              'skipped_too_new': 0,
                              'skipped_recently_accessed': 0,
                              'skipped_never_accessed_not_included': 0,
                              'skipped_rotation_enabled': 0,
                              'skipped_replicated': 0,
                              'skipped_already_scheduled_deletion': 0,
                              'skipped_include_prefix': 0,
                              'skipped_exclude_prefix': 0,
                              'skipped_missing_approval_tag': 0,
                              'skipped_ignore_tag': 0,
                              'access_denied': 0,
                              'failed': 1,
                              'failures': [{'error_code': type(e).__name__, 'error_message': str(e), 'trace': traceback.format_exc()}],
                              'candidates': [],
                              'scheduled_deletion_secrets': []
                          }
                      summary['region_results'].append(rr)
                      for key in summary['totals']:
                          summary['totals'][key] += int(rr.get(key, 0) or 0)
              finally:
                  summary['ended_at'] = utc_now_iso()
                  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 Secrets Manager Unused Secret Review Remediator.
      ScheduleExpression: !Ref ScheduleExpression
      State: ENABLED
      Targets:
        - Arn: !GetAtt RemediatorFunction.Arn
          Id: SecretsUnusedReviewTarget
          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

  ManualReviewExample:
    Description: Example manual review invocation payload.
    Value: !Sub 'aws lambda invoke --function-name ${RemediatorFunction} --cli-binary-format raw-in-base64-out --payload ''{"dry_run":true,"action_mode":"review-only","require_approval_tag":false}'' response.json'
