data "aws_s3_bucket" "tf_state_bucket" {
  bucket = var.terrastate_bucket
}

data "aws_caller_identity" "current" {}

data "aws_iam_policy_document" "atlantis_terrastate_policy" {
  statement {
    actions = [
      "s3:GetObject",
      "s3:PutObject",
    ]

    resources = [
      "${data.aws_s3_bucket.tf_state_bucket.arn}/*",
    ]
  }
  statement {
    actions = [
      "s3:ListBucket",
    ]

    resources = [
      data.aws_s3_bucket.tf_state_bucket.arn,
    ]
  }
}


resource "aws_iam_policy" "atlantis_terrastate_policy" {
  name   = "${var.environment}-${var.service_name}-terrastate-policy"
  policy = data.aws_iam_policy_document.atlantis_terrastate_policy.json
  tags   = var.iam_policy_tags.terrastate_policy
}

data "aws_iam_policy_document" "atlantis_secrets_read_policy" {
  # checkov:skip=CKV_AWS_108:A widely permissive policy is the goal.
  # checkov:skip=CKV_AWS_111:Ensure IAM policies does not allow write access without constraints
  statement {
    actions = [
      "secretsmanager:GetSecretValue",
      "kms:Decrypt"
    ]

    resources = [
      "*",
    ]
  }
}

resource "aws_iam_policy" "atlantis_secrets_read_policy" {
  name   = "${var.environment}-${var.service_name}-secrets-read-policy"
  policy = data.aws_iam_policy_document.atlantis_secrets_read_policy.json
  tags   = var.iam_policy_tags.secrets_read_policy
}

data "aws_iam_policy_document" "atlantis_tf_infra_core_apply_policy" {
  # checkov:skip=CKV_AWS_111:Ensure IAM policies does not allow write access without constraints
  # checkov:skip=CKV_AWS_110:The same as above.
  # checkov:skip=CKV_AWS_108:The same as above.
  # checkov:skip=CKV_AWS_109:The same as above.
  # checkov:skip=CKV_AWS_107:The same as above.
  statement {
    actions = [
      "acm:*",
      "airflow:*",
      "apigateway:*",
      "application-autoscaling:*",
      "athena:*",
      "autoscaling:*",
      "batch:*",
      "backup:*",
      "backup-storage:*",
      "cloudfront:*",
      "cloudformation:*",
      "cloudwatch:*",
      "config:*",
      "cloudtrail:*",
      "ce:Get*",
      "ce:List*",
      "ce:*AnomalyMonitor",
      "ce:*AnomalySubscription",
      "ce:TagResource",
      "cur:*",
      "dlm:*",
      "dsql:*",
      "dynamodb:*",
      "ec2:*VpcEndpoint*",
      "ec2:AcceptTransitGatewayVpcAttachment",
      "ec2:AcceptTransitGatewayPeeringAttachment",
      "ec2:AllocateAddress",
      "ec2:AssociateRouteTable",
      "ec2:AssociateTransitGatewayRouteTable",
      "ec2:AssociateVpcCidrBlock",
      "ec2:AttachInternetGateway",
      "ec2:Authorize*",
      "ec2:CancelCapacityReservation*",
      "ec2:Create*",
      "ec2:*NetworkInterface*",
      "ec2:Delete*",
      "ec2:Describe*",
      "ec2:DisassociateTransitGatewayRouteTable",
      "ec2:Get*",
      "ec2:Modify*",
      "ec2:Monitor*",
      "ec2:ReplaceNetworkAclAssociation",
      "ec2:Revoke*",
      "ec2:RunInstances",
      "ec2:Search*",
      "ec2:Update*",
      "ecr:*",
      "eks:*",
      "ecs:Create*",
      "ecs:Delete*",
      "ecs:Deregister*",
      "ecs:Describe*",
      "ecs:DiscoverPollEndpoint",
      "ecs:List*",
      "ecs:Poll",
      "ecs:PutClusterCapacityProviders",
      "ecs:Register*",
      "ecs:RunTask",
      "ecs:Start*",
      "ecs:StopTask",
      "ecs:Submit*",
      "ecs:TagResource",
      "ecs:UntagResource",
      "ecs:Update*",
      "elasticache:*",
      "elasticfilesystem:*",
      "elasticloadbalancing:*",
      "elasticmapreduce:*",
      "es:*",
      "events:*",
      "firehose:*",
      "geo:*",
      "glue:*",
      "guardduty:*",
      "iam:Add*",
      "iam:Attach*",
      "iam:Create*",
      "iam:Delete*",
      "iam:Detach*",
      "iam:Get*",
      "iam:List*",
      "iam:PassRole",
      "iam:PutRolePolicy",
      "iam:PutRolePermissionsBoundary",
      "iam:Remove*",
      "iam:Tag*",
      "iam:Untag*",
      "iam:Update*",
      "kafka:*",
      "kafkaconnect:*",
      "kafka-cluster:*",
      "kinesis:*",
      "kms:*",
      "lakeformation:*",
      "lambda:Add*",
      "lambda:Create*",
      "lambda:Delete*",
      "lambda:Get*",
      "lambda:List*",
      "lambda:PublishVersion",
      "lambda:PutFunctionConcurrency",
      "lambda:RemovePermission",
      "lambda:TagResource",
      "lambda:UntagResource",
      "lambda:Update*",
      "logs:*",
      "network-firewall:*",
      "networkmanager:Get*",
      "networkmanager:Describe*",
      "networkmanager:RegisterTransitGateway",
      "ram:AssociateResourceShare",
      "ram:CreateResourceShare",
      "ram:DeleteResourceShare",
      "ram:DisassociateResourceShare",
      "ram:Get*",
      "ram:List*",
      "ram:TagResource",
      "route53resolver:*",
      "rds:Add*",
      "rds:CreateDB*",
      "rds:CreateEventSubscription",
      "rds:DeleteDB*",
      "rds:DeleteEventSubscription",
      "rds:ModifyDB*",
      "rds:PurchaseReservedDBInstancesOffering",
      "rds:RegisterDBProxyTargets",
      "rds:RemoveRoleFromDBCluster",
      "rds:RemoveSourceIdentifierFromSubscription",
      "rds:RemoveTagsFromResource",
      "rds:RestoreDBClusterFromSnapshot",
      "rds:Describe*",
      "rds:List*",
      "resource-explorer-2:*",
      "route53:*",
      "route53profiles:*",
      "s3:*",
      "secretsmanager:*",
      "ses:*",
      "servicequotas:*",
      "sns:*",
      "scheduler:*",
      "sqs:*",
      "ssm:*",
      "storagegateway:*",
      "states:*",
      "waf:Get*",
      "waf:List*",
      "wafv2:AssociateWebACL",
      "wafv2:CreateIPSet",
      "wafv2:CreateRuleGroup",
      "wafv2:CreateWebACL",
      "wafv2:DeleteIPSet",
      "wafv2:DeleteLoggingConfiguration",
      "wafv2:DeleteRuleGroup",
      "wafv2:DeleteWebACL",
      "wafv2:Get*",
      "wafv2:List*",
      "wafv2:PutLoggingConfiguration",
      "wafv2:TagResource",
      "wafv2:UntagResource",
      "wafv2:UpdateIPSet",
      "wafv2:UpdateRuleGroup",
      "wafv2:UpdateWebACL",
    ]
    resources = [
      "*",
    ]
  }
}

data "aws_iam_policy_document" "atlantis_apply_policy_part_one" {
  # checkov:skip=CKV_AWS_111:Ensure IAM policies does not allow write access without constraints
  # checkov:skip=CKV_AWS_110:The same as above.
  # checkov:skip=CKV_AWS_108:The same as above.
  # checkov:skip=CKV_AWS_109:The same as above.
  # checkov:skip=CKV_AWS_107:The same as above.
  statement {
    actions = [
      "acm:AddTagsToCertificate",
      "acm:Describe*",
      "acm:Get*",
      "acm:List*",
      "acm:RenewCertificate",
      "acm:RequestCertificate",
      "acm:UpdateCertificateOptions",
      "airflow:CreateEnvironment",
      "airflow:DeleteEnvironment",
      "airflow:Get*",
      "airflow:List*",
      "airflow:ListEnvironments",
      "airflow:ListTagsForResource",
      "airflow:PublishMetrics",
      "airflow:TagResource",
      "airflow:UpdateEnvironment",
      "application-autoscaling:*",
      "athena:*",
      "autoscaling:CreateAutoScalingGroup",
      "autoscaling:CreateLaunchConfiguration",
      "autoscaling:CreateOrUpdateTags",
      "autoscaling:DeleteAutoScalingGroup",
      "autoscaling:DeleteLaunchConfiguration",
      "autoscaling:DeleteScheduledAction",
      "autoscaling:Describe*",
      "autoscaling:EnableMetricsCollection",
      "autoscaling:PutScheduledUpdateGroupAction",
      "autoscaling:SuspendProcesses",
      "autoscaling:UpdateAutoScalingGroup",
      "batch:*ComputeEnvironment",
      "batch:*JobQueue",
      "batch:*JobDefinition",
      "batch:Describe*",
      "batch:TagResource",
      "batch:UntagResource",
      "backup:*",
      "backup-storage:*",
      "bedrock:ApplyGuardrail",
      "bedrock:CreateGuardrail*",
      "bedrock:Get*",
      "bedrock:List*",
      "bedrock:TagResource",
      "bedrock:UpdateGuardrail",
      "bedrock:UntagResource",
      "apigateway:*",
      "cloudfront:*",
      "cloudformation:*",
      "cloudwatch:*",
      "config:*",
      "cloudsearch:AddTags",
      "cloudsearch:CreateDomain",
      "cloudsearch:Define*",
      "cloudsearch:Delete*",
      "cloudsearch:Describe*",
      "cloudsearch:IndexDocuments",
      "cloudsearch:List*",
      "cloudsearch:RemoveTags",
      "cloudsearch:Update*",
      "cloudtrail:*",
      "cognito-identity:Describe*",
      "cognito-identity:Get*",
      "dlm:*",
      "dsql:*",
      "dynamodb:*",
      "ec2:*VpcEndpoint*",
      "ec2:AssociateIamInstanceProfile",
      "ec2:AttachVolume",
      "ec2:AuthorizeSecurityGroup*",
      "ec2:CancelCapacityReservation*",
      "ec2:CreateCapacityReservation*",
      "ec2:CreateLaunchTemplate*",
      "ec2:CreateNetworkInterface",
      "ec2:CreateRoute",
      "ec2:CreateSecurityGroup",
      "ec2:CreateTags",
      "ec2:CreateVolume",
      "ec2:DeleteLaunchTemplate*",
      "ec2:DeleteSecurityGroup",
      "ec2:DeleteTags",
      "ec2:Describe*",
      "ec2:Get*",
      "ec2:ModifyCapacityReservation",
      "ec2:ModifyCapacityReservationFleet",
      "ec2:ModifyInstanceAttribute",
      "ec2:ModifyInstanceCapacityReservationAttributes",
      "ec2:ModifyLaunchTemplate",
      "ec2:ModifyVolume",
      "ec2:MonitorInstances",
      "ec2:RevokeSecurityGroup*",
      "ec2:RunInstances",
      "ec2:SearchTransitGateway*",
      "ec2:UpdateSecurityGroupRuleDescriptions*",
      "ec2:DeleteNetworkInterface",
      "ecr:*",
      "eks:*",
      "ecs:Create*",
      "ecs:DeleteCluster",
      "ecs:DeleteService",
      "ecs:DeleteTaskSet",
      "ecs:Deregister*",
      "ecs:Describe*",
      "ecs:DiscoverPollEndpoint",
      "ecs:List*",
      "ecs:Poll",
      "ecs:PutClusterCapacityProviders",
      "ecs:Register*",
      "ecs:RunTask",
      "ecs:StartTask",
      "ecs:StartTelemetrySession",
      "ecs:StopTask",
      "ecs:SubmitContainerStateChange",
      "ecs:SubmitTaskStateChange",
      "ecs:TagResource",
      "ecs:UntagResource",
      "ecs:Update*",
      "elasticache:*",
      "elasticbeanstalk:UpdateEnvironment",
      "elasticbeanstalk:UpdateEnvironment",
      "elasticfilesystem:*",
      "elasticloadbalancing:*",
      "elasticmapreduce:*",
      "elastictranscoder:Read*",
      "elastictranscoder:List*",
      "es:*",
      "events:CreateApiDestination",
      "events:CreateConnection",
      "events:CreateEventBus",
      "events:DeleteApiDestination",
      "events:DeleteConnection",
      "events:DeleteEventBus",
      "events:DeleteRule",
      "events:Describe*",
      "events:PutRule",
      "events:PutTargets",
      "events:RemoveTargets",
      "events:TagResource",
      "events:UpdateApiDestination",
      "events:UpdateConnection",
      "events:List*",
      "events:UntagResource",
      "firehose:CreateDeliveryStream",
      "firehose:DeleteDeliveryStream",
      "firehose:DescribeDeliveryStream",
      "firehose:ListDeliveryStreams",
      "firehose:ListTagsForDeliveryStream",
      "firehose:TagDeliveryStream",
      "firehose:UntagDeliveryStream",
      "firehose:UpdateDestination",
      "geo:*",
      "glue:*",
      "guardduty:CreateMalwareProtectionPlan",
      "guardduty:DeleteMalwareProtectionPlan",
      "guardduty:GetMalwareProtectionPlan",
      "guardduty:ListTagsForResource",
      "guardduty:TagResource",
      "iam:AddRoleToInstanceProfile",
      "iam:AddUserToGroup",
      "iam:Attach*",
      "iam:CreateGroup",
      "iam:CreateInstanceProfile",
      "iam:CreatePolicy",
      "iam:CreatePolicyVersion",
      "iam:CreateRole",
      "iam:CreateServiceLinkedRole",
      "iam:CreateUser",
      "iam:DeleteGroup",
      "iam:DeleteInstanceProfile",
      "iam:DeletePolicy",
      "iam:DeletePolicyVersion",
      "iam:DeleteRole",
      "iam:DeleteRolePolicy",
      "iam:DeleteUser",
      "iam:DeleteUserPolicy",
      "iam:Detach*",
      "iam:PassRole",
      "iam:PutGroupPolicy",
      "iam:PutRolePermissionsBoundary",
      "iam:PutRolePolicy",
      "iam:PutUserPolicy",
      "iam:RemoveRoleFromInstanceProfile",
      "iam:RemoveUserFromGroup",
      "iam:Tag*",
      "iam:Untag*",
      "iam:Get*",
      "iam:List*",
      "iam:UpdateAssumeRolePolicy",
      "iam:UpdateGroup",
      "iam:UpdateRole",
      "iam:UpdateRoleDescription",
    ]
    resources = [
      "*",
    ]
  }
}

data "aws_iam_policy_document" "atlantis_apply_policy_part_two" {
  # checkov:skip=CKV_AWS_111:Ensure IAM policies does not allow write access without constraints
  # checkov:skip=CKV_AWS_110:The same as above.
  # checkov:skip=CKV_AWS_108:The same as above.
  # checkov:skip=CKV_AWS_109:The same as above.
  statement {
    actions = [
      "inspector2:BatchGetAccountStatus",
      "inspector2:Disable",
      "inspector2:Enable",
      "inspector2:ListAccountPermissions",
      "kafka:*",
      "kafkaconnect:*",
      "kafka-cluster:*",
      "kinesis:AddTagsToStream",
      "kinesis:CreateStream",
      "kinesis:DecreaseStreamRetentionPeriod",
      "kinesis:DeleteStream",
      "kinesis:DeregisterStreamConsumer",
      "kinesis:Describe*",
      "kinesis:DisableEnhancedMonitoring",
      "kinesis:EnableEnhancedMonitoring",
      "kinesis:Get*",
      "kinesis:IncreaseStreamRetentionPeriod",
      "kinesis:List*",
      "kinesis:RegisterStreamConsumer",
      "kinesis:RemoveTagsFromStream",
      "kinesis:StartStreamEncryption",
      "kinesis:UpdateShardCount",
      "kms:CreateAlias",
      "kms:CreateGrant",
      "kms:CreateKey",
      "kms:Get*",
      "kms:GenerateDataKey*",
      "kms:DeleteAlias",
      "kms:Describe*",
      "kms:EnableKeyRotation",
      "kms:Encrypt",
      "kms:PutKeyPolicy",
      "kms:RetireGrant",
      "kms:ReEncrypt*",
      "kms:TagResource",
      "kms:UntagResource",
      "kms:List*",
      "kms:UpdateKeyDescription",
      "lakeformation:GrantPermissions",
      "lakeformation:List*",
      "lakeformation:RevokePermissions",
      "lambda:Add*",
      "lambda:Create*",
      "lambda:Delete*",
      "lambda:Get*",
      "lambda:List*",
      "lambda:PublishVersion",
      "lambda:Put*",
      "lambda:RemovePermission",
      "lambda:TagResource",
      "lambda:UntagResource",
      "lambda:Update*",
      "logs:*",
      "network-firewall:*",
      "mq:Describe*",
      "mq:List*",
      "pipes:*",
      "ram:*ResourceShare",
      "ram:Get*",
      "ram:List*",
      "ram:TagResource",
      "ram:UntagResource",
      "rds:Add*",
      "rds:CreateDB*",
      "rds:CreateEventSubscription",
      "rds:DeleteDB*",
      "rds:DeleteEventSubscription",
      "rds:DeregisterDBProxyTargets",
      "rds:ModifyDB*",
      "rds:RegisterDBProxyTargets",
      "rds:RemoveRoleFromDBCluster",
      "rds:RemoveSourceIdentifierFromSubscription",
      "rds:RemoveTagsFromResource",
      "rds:ResetDB*",
      "rds:RestoreDBClusterFromSnapshot",
      "rds:Describe*",
      "rds:List*",
      "redshift:Describe*",
      "resource-explorer-2:*",
      "route53:AssociateVPCWithHostedZone",
      "route53:ChangeResourceRecordSets",
      "route53:ChangeTagsForResource",
      "route53:CreateHostedZone",
      "route53:CreateHealthCheck",
      "route53:CreateQueryLoggingConfig",
      "route53:CreateVPCAssociationAuthorization",
      "route53:Get*",
      "route53:List*",
      "route53:UpdateHostedZoneComment",
      "route53:UpdateHealthCheck",
      "route53profiles:*",
      "s3:*",
      "sagemaker:*",
      "secretsmanager:*ResourcePolicy",
      "secretsmanager:CancelRotateSecret",
      "secretsmanager:CreateSecret",
      "secretsmanager:DeleteSecret",
      "secretsmanager:Describe*",
      "secretsmanager:Get*",
      "secretsmanager:List*",
      "secretsmanager:PutSecretValue",
      "secretsmanager:TagResource",
      "secretsmanager:UntagResource",
      "secretsmanager:UpdateSecret",
      "secretsmanager:UpdateSecretVersionStage",
      "secretsmanager:RotateSecret",
      "servicediscovery:Discover*",
      "servicediscovery:Get*",
      "servicediscovery:List*",
      "ses:CreateReceiptRule*",
      "ses:CreateConfigurationSet*",
      "ses:DeleteConfigurationSet*",
      "ses:DeleteReceiptRule*",
      "ses:Get*",
      "ses:DeleteIdentityPolicy",
      "ses:Describe*",
      "ses:List*",
      "ses:PutConfigurationSet*",
      "ses:PutEmailIdentityConfigurationSetAttributes",
      "ses:TagResource",
      "ses:UntagResource",
      "ses:PutIdentityPolicy",
      "ses:ReorderReceiptRuleSet",
      "ses:SetReceiptRulePosition",
      "ses:SetActiveReceiptRuleSet",
      "ses:UpdateConfigurationSet*",
      "ses:VerifyDomain*",
      "ses:VerifyEmailIdentity",
      "ses:UpdateReceiptRule",
      "sns:*",
      "scheduler:*",
      "sqs:*",
      "ssm:*",
      "storagegateway:*",
      "states:*",
      "swf:DeprecateDomain",
      "swf:Describe*",
      "swf:Get*",
      "swf:List*",
      "swf:RegisterDomain",
      "swf:TagResource",
      "swf:UntagResource",
      "transfer:Create*",
      "transfer:Describe*",
      "transfer:List*",
      "transfer:TagResource",
      "transfer:UntagResource",
      "transfer:Update*",
      "waf:Get*",
      "waf:List*",
      "wafv2:AssociateWebACL",
      "wafv2:CreateIPSet",
      "wafv2:CreateRuleGroup",
      "wafv2:CreateWebACL",
      "wafv2:DeleteIPSet",
      "wafv2:DeleteLoggingConfiguration",
      "wafv2:DeleteRuleGroup",
      "wafv2:DeleteWebACL",
      "wafv2:Get*",
      "wafv2:List*",
      "wafv2:PutLoggingConfiguration",
      "wafv2:TagResource",
      "wafv2:UpdateIPSet",
      "wafv2:UpdateRuleGroup",
      "wafv2:UpdateWebACL",
    ]
    resources = [
      "*",
    ]
  }

  statement {
    actions = [
      "rds-db:connect"
    ]
    resources = [
      "arn:aws:rds-db:*:${data.aws_caller_identity.current.account_id}:dbuser:*/atlantis"
    ]
  }
}

data "aws_iam_policy_document" "atlantis_kms_delete_policy" {
  # checkov:skip=CKV_AWS_111:Ensure IAM policies does not allow write access without constraints
  # checkov:skip=CKV_AWS_110:The same as above.
  # checkov:skip=CKV_AWS_108:The same as above.
  # checkov:skip=CKV_AWS_109:The same as above.
  # checkov:skip=CKV_AWS_107:The same as above.

  statement {
    actions = [
      "kms:DeleteAlias",
    ]

    resources = [
      "arn:aws:kms:*:${data.aws_caller_identity.current.account_id}:alias/eks/*",
      "arn:aws:kms:*:${data.aws_caller_identity.current.account_id}:alias/eks-*",
      "arn:aws:kms:*:${data.aws_caller_identity.current.account_id}:alias/lambda-*",
      "arn:aws:kms:*:${data.aws_caller_identity.current.account_id}:key/*",
    ]
  }

  statement {
    actions = [
      "kms:ScheduleKeyDeletion",
      "kms:DisableKey",
    ]

    resources = ["*"]

    condition {
      test     = "StringLike"
      variable = "kms:ResourceTag/service_name"
      values   = ["lambda-*"]
    }
  }
}

data "aws_iam_policy_document" "atlantis_kms_reencrypt_policy" {
  statement {
    effect = "Allow"
    actions = [
      "kms:ReEncryptFrom"
    ]
    resources = [
      "arn:aws:kms:*:086679231553:alias/shared-base-ami-key",
    ]
  }
}

data "aws_iam_policy_document" "atlantis_invoke_lambdas_policy" {
  statement {
    effect = "Allow"
    actions = [
      "lambda:InvokeFunction",
    ]

    resources = concat(
      local.lambda_function_arns_to_invoke,
      # Give Atlantis the ability to associate lambda-auth0-m2m-token-secret-rotation
      # to AWS Secrets Manager secrets in this AWS account
      [
        "arn:aws:lambda:*:${data.aws_caller_identity.current.account_id}:function:${var.environment}-lambda-auth0-m2m-token-secret-rotation",
        "arn:aws:lambda:*:${data.aws_caller_identity.current.account_id}:function:${var.environment}-lambda-auth0-m2m-token-secret-rotation:*"
      ],
    )
  }
}

resource "aws_iam_policy" "atlantis_apply_policy_part_one" {
  name   = "${var.environment}-${var.service_name}-apply-part-one-policy"
  policy = data.aws_iam_policy_document.atlantis_apply_policy_part_one.json
  tags   = var.iam_policy_tags.apply_policy_part_one
}

resource "aws_iam_policy" "atlantis_apply_policy_part_two" {
  name   = "${var.environment}-${var.service_name}-apply-part-two-policy"
  policy = data.aws_iam_policy_document.atlantis_apply_policy_part_two.json
  tags   = var.iam_policy_tags.apply_policy_part_two
}

resource "aws_iam_policy" "atlantis_tf_infra_core_apply_policy" {
  name   = "${var.environment}-${var.service_name}-tf-infra-core-apply-policy"
  policy = data.aws_iam_policy_document.atlantis_tf_infra_core_apply_policy.json
  tags   = var.iam_policy_tags.tf_infra_core_apply_policy
}

resource "aws_iam_policy" "atlantis_kms_delete_policy" {
  name   = "${var.environment}-${var.service_name}-kms-delete-policy"
  policy = data.aws_iam_policy_document.atlantis_kms_delete_policy.json
  tags   = var.iam_policy_tags.kms_delete_policy
}

resource "aws_iam_policy" "atlantis_kms_reencrypt_policy" {
  name   = "${var.environment}-${var.service_name}-kms-reencrypt-policy"
  policy = data.aws_iam_policy_document.atlantis_kms_reencrypt_policy.json
  tags   = var.iam_policy_tags.kms_reencrypt_policy
}

resource "aws_iam_policy" "atlantis_invoke_lambdas_policy" {
  name   = "${var.environment}-${var.service_name}-invoke-lambdas-policy"
  policy = data.aws_iam_policy_document.atlantis_invoke_lambdas_policy.json
  tags   = var.iam_policy_tags.invoke_lambdas_policy
}

data "aws_iam_policy_document" "atlantis_assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "AWS"
      identifiers = var.identifiers
    }
    condition {
      test     = "StringEquals"
      values   = [var.external_id]
      variable = "sts:ExternalId"
    }
  }
}

resource "aws_iam_role" "atlantis_role" {
  name                 = var.atlantis_role_name
  assume_role_policy   = data.aws_iam_policy_document.atlantis_assume_role_policy.json
  max_session_duration = 3600
  tags                 = local.tags
}

resource "aws_iam_role_policy_attachment" "atlantis_apply_policy_part_one_attachment" {
  role       = aws_iam_role.atlantis_role.name
  policy_arn = aws_iam_policy.atlantis_apply_policy_part_one.arn
}

resource "aws_iam_role_policy_attachment" "atlantis_apply_policy_part_two_attachment" {
  role       = aws_iam_role.atlantis_role.name
  policy_arn = aws_iam_policy.atlantis_apply_policy_part_two.arn
}

resource "aws_iam_role_policy_attachment" "atlantis_kms_delete_policy_attachment" {
  role       = aws_iam_role.atlantis_role.name
  policy_arn = aws_iam_policy.atlantis_kms_delete_policy.arn
}

resource "aws_iam_role_policy_attachment" "atlantis_kms_reencrypt_policy_attachment" {
  role       = aws_iam_role.atlantis_role.name
  policy_arn = aws_iam_policy.atlantis_kms_reencrypt_policy.arn
}

resource "aws_iam_role_policy_attachment" "atlantis_invoke_lambdas_policy_attachment" {
  role       = aws_iam_role.atlantis_role.name
  policy_arn = aws_iam_policy.atlantis_invoke_lambdas_policy.arn
}

resource "aws_iam_role_policy_attachment" "atlantis_terrastate_policy_attachment" {
  role       = aws_iam_role.atlantis_role.name
  policy_arn = aws_iam_policy.atlantis_terrastate_policy.arn
}

resource "aws_iam_role_policy_attachment" "atlantis_secrets_read_policy_attachment" {
  role       = aws_iam_role.atlantis_role.name
  policy_arn = aws_iam_policy.atlantis_secrets_read_policy.arn
}

data "aws_iam_policy_document" "atlantis_infra_core_assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "AWS"
      identifiers = var.infra_core_identifiers
    }
    condition {
      test     = "StringEquals"
      values   = [var.external_id]
      variable = "sts:ExternalId"
    }
  }
}

resource "aws_iam_role" "atlantis_tf_infra_core_role" {
  name                 = "cross-account-atlantis-tf-infra-core-role"
  assume_role_policy   = data.aws_iam_policy_document.atlantis_infra_core_assume_role_policy.json
  max_session_duration = 3600
  tags                 = local.tags
}

resource "aws_iam_role_policy_attachment" "atlantis_tf_infra_core_apply_policy_attachment" {
  role       = aws_iam_role.atlantis_tf_infra_core_role.name
  policy_arn = aws_iam_policy.atlantis_tf_infra_core_apply_policy.arn
}

resource "aws_iam_role_policy_attachment" "atlantis_core_terrastate_policy_attachment" {
  role       = aws_iam_role.atlantis_tf_infra_core_role.name
  policy_arn = aws_iam_policy.atlantis_terrastate_policy.arn
}

resource "aws_iam_role_policy_attachment" "atlantis_core_secrets_read_policy_attachment" {
  role       = aws_iam_role.atlantis_tf_infra_core_role.name
  policy_arn = aws_iam_policy.atlantis_secrets_read_policy.arn
}
