data aws_partition "current" {}

data aws_iam_policy_document "qualys_assume_role_policy" {
  statement {
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = [
        "arn:${data.aws_partition.current.partition}:iam::${var.common_services_account}:user/service_accounts/qualys"
      ]
    }
    actions = [
      "sts:AssumeRole"
    ]

    condition {
      test     = "StringEquals"
      variable = "sts:ExternalId"
      values = [
        var.qualys_connector_externalid
      ]
    }
  }
}

data aws_iam_policy_document "qualys_role_policy" {
  statement {
    effect = "Allow"
    actions = [
      "ec2:DescribeInstances",
      "ec2:DescribeAddresses",
      "ec2:DescribeImages"
    ]
    resources = ["*"]
  }
}

resource aws_iam_role "qualys" {
  name               = "QualysConnectorRole"
  assume_role_policy = data.aws_iam_policy_document.qualys_assume_role_policy.json
  description        = "Qualys Connector for EC2 instance enumeration"
  tags               = var.tags
}

resource aws_iam_role_policy "qualys" {
  role   = aws_iam_role.qualys.id
  name   = "QualysEC2Connector"
  policy = data.aws_iam_policy_document.qualys_role_policy.json

}
