#------------------------------------------------------------------------------------------
# A variant on PowerUserAccess that isn't so damn generous with sts:assumeRole
#------------------------------------------------------------------------------------------
data "aws_iam_policy_document" "mdr_terraformer" {
  statement {
    sid    = "AllowEverythingButAssumeRoleAndPassRole"
    effect = "Allow"
    not_actions = [
      "sts:AssumeRole",
      "iam:PassRole",
    ]
    resources = [
      "*"
    ]
  }
  statement {
    sid     = "AllowPassRoleForSpecificRoleTypes"
    effect = "Allow"
    actions = [
      "iam:PassRole",
    ]

    resources = [
      "arn:${local.aws_partition}:iam::${local.aws_account}:role/instance/*",
      "arn:${local.aws_partition}:iam::${local.aws_account}:role/lambda/*",
      "arn:${local.aws_partition}:iam::${local.aws_account}:role/aws_services/*",
      "arn:${local.aws_partition}:iam::${local.aws_account}:role/fargate/*",
    ]
  }

  statement {
    sid     = "AllowPassRoleForLegacyAccountRoles"
    effect = "Allow"
    actions = [
      "iam:PassRole",
    ]

    resources = [
			"arn:${local.aws_partition}:iam::${local.aws_account}:role/vault-instance-role",
			"arn:${local.aws_partition}:iam::${local.aws_account}:role/splunk-aws-instance-role",
			"arn:${local.aws_partition}:iam::${local.aws_account}:role/salt-master-instance-role",
			"arn:${local.aws_partition}:iam::${local.aws_account}:role/portal-instance-role",
			"arn:${local.aws_partition}:iam::${local.aws_account}:role/portal-data-sync-lambda-role",
			"arn:${local.aws_partition}:iam::${local.aws_account}:role/msoc-default-instance-role",
			"arn:${local.aws_partition}:iam::${local.aws_account}:role/ecsFargateTaskExecutionRole",
			"arn:${local.aws_partition}:iam::${local.aws_account}:role/dlm-lifecycle-role",
			"arn:${local.aws_partition}:iam::${local.aws_account}:role/codebuild_role",
    ]
  }

  statement {
    sid    = "AssumeThisRoleInOtherAccounts"
    effect = "Allow"
    actions = [
      "sts:AssumeRole"
    ]

    resources = [
      "arn:${local.aws_partition}:iam::*:role/user/mdr_terraformer",

      # These two are the legacy roles in the older AWS accounts. 
      # Adding them in the hope we'll be able to get AssumeRole from
      # one central place to everything...
      "arn:${local.aws_partition}:iam::*:role/mdr_powerusers",
      "arn:${local.aws_partition}:iam::*:role/mdr_iam_admins",
    ]
  }
}

resource "aws_iam_policy" "mdr_terraformer" {
  name   = "mdr_terraformer"
  path   = "/user/"
  policy = data.aws_iam_policy_document.mdr_terraformer.json
}

