AWSTemplateFormatVersion: '2010-09-09'
Description: >
  ECR Lifecycle Policy Review Remediator.
  Purpose-specific, opt-in remediation module for identifying ECR repositories
  without lifecycle policies and optionally applying a conservative baseline policy.
  This template is separate from the cost optimization assessment/reporting template.

Parameters:
  ProjectName:
    Type: String
    Default: ecr-lifecycle-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, apply eligible lifecycle policies.

  RequireApprovalTag:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Repository changes require 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,DoNotModify,DoNotDelete
    Description: Comma-separated tag keys that prevent lifecycle policy application when present.

  IgnoreTagPairsCsv:
    Type: String
    Default: CostOptIgnore=true,DoNotModify=true,DoNotDelete=true
    Description: Comma-separated key=value tag pairs that prevent lifecycle policy application.

  OnlyIfNoLifecyclePolicy:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: When true, only repositories without an existing lifecycle policy are eligible.

  AllowOverwriteExistingLifecyclePolicy:
    Type: String
    Default: 'false'
    AllowedValues: ['true', 'false']
    Description: Allows replacing existing lifecycle policies. Not recommended for normal use.

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

  ExcludeRepositoryNamePrefixesCsv:
    Type: String
    Default: ''
    Description: Optional comma-separated repository name prefixes to exclude.

  UntaggedExpireDays:
    Type: Number
    Default: 14
    Description: Expire untagged images older than this many days.

  TaggedImageCountToKeep:
    Type: Number
    Default: 30
    Description: Keep this many tagged images per repository.

  ApplyUntaggedRule:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Whether the baseline policy expires old untagged images.

  ApplyTaggedCountRule:
    Type: String
    Default: 'false'
    AllowedValues: ['true', 'false']
    Description: Whether the baseline policy also limits tagged images by count. Conservative default is false.

  MaxRepositoriesPerRun:
    Type: Number
    Default: 50
    Description: Safety limit. 0 means no limit. Recommended first apply batch is 10 to 25.

  ContinueOnAccessDenied:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Continue scanning other Regions/repositories when blocked by IAM/SCP/repository 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: EcrLifecycleReviewPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: DiscoverRegions
                Effect: Allow
                Action:
                  - ec2:DescribeRegions
                Resource: '*'
              - Sid: ReadEcr
                Effect: Allow
                Action:
                  - ecr:DescribeRepositories
                  - ecr:GetLifecyclePolicy
                  - ecr:ListTagsForResource
                Resource: '*'
              - Sid: PutEcrLifecyclePolicy
                Effect: Allow
                Action:
                  - ecr:PutLifecyclePolicy
                Resource: '*'

  RemediatorFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Ref ProjectName
      Description: Purpose-specific Lambda for ECR lifecycle policy review and baseline policy application.
      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
          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
          ONLY_IF_NO_LIFECYCLE_POLICY: !Ref OnlyIfNoLifecyclePolicy
          ALLOW_OVERWRITE_EXISTING_LIFECYCLE_POLICY: !Ref AllowOverwriteExistingLifecyclePolicy
          INCLUDE_REPOSITORY_NAME_PREFIXES_CSV: !Ref IncludeRepositoryNamePrefixesCsv
          EXCLUDE_REPOSITORY_NAME_PREFIXES_CSV: !Ref ExcludeRepositoryNamePrefixesCsv
          UNTAGGED_EXPIRE_DAYS: !Ref UntaggedExpireDays
          TAGGED_IMAGE_COUNT_TO_KEEP: !Ref TaggedImageCountToKeep
          APPLY_UNTAGGED_RULE: !Ref ApplyUntaggedRule
          APPLY_TAGGED_COUNT_RULE: !Ref ApplyTaggedCountRule
          MAX_REPOSITORIES_PER_RUN: !Ref MaxRepositoriesPerRun
          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_iso():
              return datetime.now(timezone.utc).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):
              result = {}
              for item in split_csv(value):
                  if '=' in item:
                      k, v = item.split('=', 1)
                      if k.strip():
                          result[k.strip()] = v.strip()
              return result

          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 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_tags(ecr, arn):
              try:
                  response = ecr.list_tags_for_resource(resourceArn=arn)
                  return {t.get('Key'): t.get('Value', '') for t in response.get('tags', []) if t.get('Key')}
              except ClientError:
                  return {}

          def get_lifecycle_policy(ecr, repository_name):
              try:
                  response = ecr.get_lifecycle_policy(repositoryName=repository_name)
                  text = response.get('lifecyclePolicyText')
                  parsed = None
                  try:
                      parsed = json.loads(text) if text else None
                  except Exception:
                      parsed = text
                  return True, parsed, None
              except ClientError as e:
                  code = e.response.get('Error', {}).get('Code', '')
                  if code == 'LifecyclePolicyNotFoundException':
                      return False, None, None
                  return None, None, e

          def baseline_policy(settings):
              rules = []
              priority = 1

              if settings['apply_untagged_rule']:
                  rules.append({
                      'rulePriority': priority,
                      'description': 'CostOpt expire untagged images older than configured days',
                      'selection': {
                          'tagStatus': 'untagged',
                          'countType': 'sinceImagePushed',
                          'countUnit': 'days',
                          'countNumber': settings['untagged_expire_days']
                      },
                      'action': {'type': 'expire'}
                  })
                  priority += 1

              if settings['apply_tagged_count_rule']:
                  rules.append({
                      'rulePriority': priority,
                      'description': 'CostOpt keep configured number of tagged images',
                      'selection': {
                          'tagStatus': 'tagged',
                          'tagPrefixList': ['v', 'release', 'build'],
                          'countType': 'imageCountMoreThan',
                          'countNumber': settings['tagged_image_count_to_keep']
                      },
                      'action': {'type': 'expire'}
                  })

              return {'rules': rules}

          def describe_repositories(ecr):
              repos = []
              paginator = ecr.get_paginator('describe_repositories')
              for page in paginator.paginate():
                  repos.extend(page.get('repositories', []))
              return repos

          def scan_region(region, settings):
              ecr = boto3.client('ecr', region_name=region)
              result = {
                  'region': region,
                  'evaluated': 0,
                  'repositories': 0,
                  'repositories_without_lifecycle_policy': 0,
                  'repositories_with_lifecycle_policy': 0,
                  'eligible': 0,
                  'would_apply': 0,
                  'applied': 0,
                  'skipped_existing_lifecycle_policy': 0,
                  'skipped_no_baseline_rules_enabled': 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': [],
                  'applied_repositories': []
              }

              try:
                  repositories = describe_repositories(ecr)
              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': 'DescribeRepositories', 'error_code': code, 'error_message': message})
                  if code in ('AccessDeniedException', 'AccessDenied') or 'explicit deny' in message.lower():
                      result['access_denied'] += 1
                  else:
                      result['failed'] += 1
                  if not settings['continue_on_access_denied']:
                      raise
                  return result

              policy = baseline_policy(settings)
              if not policy['rules']:
                  result['skipped_no_baseline_rules_enabled'] = len(repositories)
                  return result

              for repo in repositories:
                  if settings['max_repositories_per_run'] and (result['would_apply'] + result['applied']) >= settings['max_repositories_per_run']:
                      result['stopped_due_to_max_repositories_per_run'] = True
                      return result

                  name = repo.get('repositoryName')
                  arn = repo.get('repositoryArn')
                  result['evaluated'] += 1
                  result['repositories'] += 1

                  item = {
                      'repository_name': name,
                      'repository_arn': arn,
                      'region': region,
                      'created_at': str(repo.get('createdAt')),
                      'image_tag_mutability': repo.get('imageTagMutability'),
                      'encryption_type': (repo.get('encryptionConfiguration') or {}).get('encryptionType'),
                      'scan_on_push': (repo.get('imageScanningConfiguration') or {}).get('scanOnPush')
                  }

                  if not name_included(name, settings['include_repository_name_prefixes']):
                      result['skipped_include_prefix'] += 1
                      continue
                  if name_excluded(name, settings['exclude_repository_name_prefixes']):
                      result['skipped_exclude_prefix'] += 1
                      item['action'] = 'skipped_exclude_prefix'
                      result['candidates'].append(item)
                      continue

                  tags = list_tags(ecr, arn)
                  item['tags'] = tags

                  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

                  has_policy, existing_policy, policy_error = get_lifecycle_policy(ecr, name)
                  if policy_error:
                      code = policy_error.response.get('Error', {}).get('Code', 'Unknown')
                      message = policy_error.response.get('Error', {}).get('Message', str(policy_error))
                      result['failures'].append({'repository_name': name, 'operation': 'GetLifecyclePolicy', 'error_code': code, 'error_message': message})
                      if code in ('AccessDeniedException', 'AccessDenied') or 'explicit deny' in message.lower():
                          result['access_denied'] += 1
                      else:
                          result['failed'] += 1
                      if not settings['continue_on_access_denied']:
                          raise policy_error
                      continue

                  item['has_lifecycle_policy'] = bool(has_policy)
                  if has_policy:
                      result['repositories_with_lifecycle_policy'] += 1
                      item['existing_lifecycle_policy'] = existing_policy
                      if settings['only_if_no_lifecycle_policy'] and not settings['allow_overwrite_existing_lifecycle_policy']:
                          result['skipped_existing_lifecycle_policy'] += 1
                          item['action'] = 'skipped_existing_lifecycle_policy'
                          result['candidates'].append(item)
                          continue
                  else:
                      result['repositories_without_lifecycle_policy'] += 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
                  item['new_lifecycle_policy'] = policy
                  item['action'] = 'would_apply' if settings['dry_run'] else 'apply'

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

                  try:
                      ecr.put_lifecycle_policy(repositoryName=name, lifecyclePolicyText=json.dumps(policy))
                      result['applied'] += 1
                      result['applied_repositories'].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({'repository_name': name, 'operation': 'PutLifecyclePolicy', 'error_code': code, 'error_message': message})
                      if code in ('AccessDeniedException', 'AccessDenied') 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),
                  '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', '')),
                  'only_if_no_lifecycle_policy': env_bool('ONLY_IF_NO_LIFECYCLE_POLICY', True),
                  'allow_overwrite_existing_lifecycle_policy': env_bool('ALLOW_OVERWRITE_EXISTING_LIFECYCLE_POLICY', False),
                  'include_repository_name_prefixes': split_csv(os.environ.get('INCLUDE_REPOSITORY_NAME_PREFIXES_CSV', '')),
                  'exclude_repository_name_prefixes': split_csv(os.environ.get('EXCLUDE_REPOSITORY_NAME_PREFIXES_CSV', '')),
                  'untagged_expire_days': env_int('UNTAGGED_EXPIRE_DAYS', 14),
                  'tagged_image_count_to_keep': env_int('TAGGED_IMAGE_COUNT_TO_KEEP', 30),
                  'apply_untagged_rule': env_bool('APPLY_UNTAGGED_RULE', True),
                  'apply_tagged_count_rule': env_bool('APPLY_TAGGED_COUNT_RULE', False),
                  'max_repositories_per_run': env_int('MAX_REPOSITORIES_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 'require_approval_tag' in event:
                      settings['require_approval_tag'] = bool(event['require_approval_tag'])
                  if 'max_repositories_per_run' in event:
                      settings['max_repositories_per_run'] = int(event['max_repositories_per_run'])
                  if 'untagged_expire_days' in event:
                      settings['untagged_expire_days'] = int(event['untagged_expire_days'])
                  if 'tagged_image_count_to_keep' in event:
                      settings['tagged_image_count_to_keep'] = int(event['tagged_image_count_to_keep'])
                  if 'apply_untagged_rule' in event:
                      settings['apply_untagged_rule'] = bool(event['apply_untagged_rule'])
                  if 'apply_tagged_count_rule' in event:
                      settings['apply_tagged_count_rule'] = bool(event['apply_tagged_count_rule'])
                  if 'include_repository_name_prefixes' in event:
                      settings['include_repository_name_prefixes'] = list(event['include_repository_name_prefixes'])
                  if 'exclude_repository_name_prefixes' in event:
                      settings['exclude_repository_name_prefixes'] = list(event['exclude_repository_name_prefixes'])
                  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'])

              summary = {
                  'started_at': utc_now_iso(),
                  'dry_run': settings['dry_run'],
                  'require_approval_tag': settings['require_approval_tag'],
                  'approval_tag': settings['approval_tag_key'] + '=' + settings['approval_tag_value'],
                  'only_if_no_lifecycle_policy': settings['only_if_no_lifecycle_policy'],
                  'allow_overwrite_existing_lifecycle_policy': settings['allow_overwrite_existing_lifecycle_policy'],
                  'apply_untagged_rule': settings['apply_untagged_rule'],
                  'untagged_expire_days': settings['untagged_expire_days'],
                  'apply_tagged_count_rule': settings['apply_tagged_count_rule'],
                  'tagged_image_count_to_keep': settings['tagged_image_count_to_keep'],
                  'include_repository_name_prefixes': settings['include_repository_name_prefixes'],
                  'exclude_repository_name_prefixes': settings['exclude_repository_name_prefixes'],
                  'max_repositories_per_run': settings['max_repositories_per_run'],
                  'excluded_regions': settings['excluded_regions'],
                  'regions': [],
                  'baseline_policy': baseline_policy(settings),
                  'totals': {
                      'evaluated': 0,
                      'repositories': 0,
                      'repositories_without_lifecycle_policy': 0,
                      'repositories_with_lifecycle_policy': 0,
                      'eligible': 0,
                      'would_apply': 0,
                      'applied': 0,
                      'skipped_existing_lifecycle_policy': 0,
                      'skipped_no_baseline_rules_enabled': 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': 0,
                              'repositories': 0,
                              'repositories_without_lifecycle_policy': 0,
                              'repositories_with_lifecycle_policy': 0,
                              'eligible': 0,
                              'would_apply': 0,
                              'applied': 0,
                              'skipped_existing_lifecycle_policy': 0,
                              'skipped_no_baseline_rules_enabled': 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': [],
                              'applied_repositories': []
                          }
                      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 ECR Lifecycle Policy Review Remediator.
      ScheduleExpression: !Ref ScheduleExpression
      State: ENABLED
      Targets:
        - Arn: !GetAtt RemediatorFunction.Arn
          Id: EcrLifecycleReviewTarget
          Input: '{"source":"eventbridge-schedule","dry_run":true}'

  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

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