#############################
# Salt Master instance profile
#
# Salt Master got needs for some sweet sweet passwords

resource "aws_iam_instance_profile" "salt_master_instance_profile" {
  name     = "salt-master-instance-profile"
  role     = aws_iam_role.salt_master_instance_role.name
}

resource "aws_iam_role" "salt_master_instance_role" {
  name     = "salt-master-instance-role"
  assume_role_policy = <<EOF
{   
    "Version": "2012-10-17",
    "Statement": [
      {   
        "Sid": "", 
        "Effect": "Allow",
        "Principal": {
          "Service": [
            "ec2.amazonaws.com",
            "ssm.amazonaws.com"
            ]
        },
        "Action": "sts:AssumeRole"
      }
    ]
  }
EOF
}

data "aws_iam_policy_document" "salt_master_policy_doc" {
  statement {
    sid    = "AllowSaltSecretsCommunication"
    effect = "Allow"

    actions = [
      "secretsmanager:GetResourcePolicy",
      "secretsmanager:GetSecretValue",
      "secretsmanager:DescribeSecret",
      "secretsmanager:ListSecretVersionIds"
    ]

    resources = [
      "arn:${var.aws_partition}:secretsmanager:*:*:secret:saltmaster/*"
    ]
  }

  statement {
    sid    = "AllowAssumeRole"
    effect = "Allow"

    actions = [
      "sts:AssumeRole"
    ]

    resources = [
      "arn:${var.aws_partition}:iam::*:role/service/salt-master-inventory-role",
      "arn:${var.aws_partition}:iam::*:role/service/afsxdr-binaries_writers",
    ]
  }
}

resource "aws_iam_policy" "salt_master_policy" {
  name        = "salt_master_sm"
  path        = "/"
  policy      = data.aws_iam_policy_document.salt_master_policy_doc.json
}

resource "aws_iam_role_policy_attachment" "salt_master_sm_attach" {
  role       = aws_iam_role.salt_master_instance_role.name
  policy_arn = aws_iam_policy.salt_master_policy.arn
}

resource "aws_iam_role_policy_attachment" "salt_master_AmazonEC2RoleforSSM" {
  role       = aws_iam_role.salt_master_instance_role.name
  policy_arn = "arn:${var.aws_partition}:iam::aws:policy/service-role/AmazonEC2RoleforSSM"
}

#This policy needs to be create prior to creating the Salt Master
resource "aws_iam_role_policy_attachment" "salt_master_policy_attach_tag_read" {
  role       = aws_iam_role.salt_master_instance_role.name
  policy_arn = "arn:${var.aws_partition}:iam::${var.aws_account_id}:policy/launchroles/default_instance_tag_read"
}

#This policy needs to be create prior to creating the Salt Master
resource "aws_iam_role_policy_attachment" "salt_master_policy_attach_binaries" {
  role       = aws_iam_role.salt_master_instance_role.name
  policy_arn = "arn:${var.aws_partition}:iam::${var.aws_account_id}:policy/launchroles/default_instance_s3_binaries"
}
