data "aws_iam_role" "jenkins_aws_pipeline_agent_role" {
  name = "prod-jenkins-aws-pipeline-agent"
}

data "aws_iam_policy_document" "jenkins_assume_role_policy" {
  statement {
    effect = "Allow"

    actions = [
      "sts:AssumeRole",
    ]

    principals {
      type = "AWS"
      identifiers = [
        data.aws_iam_role.jenkins_aws_pipeline_agent_role.arn
      ]
    }
  }
}

# Jenkins agents will assume this role in order to access SecretManager
resource "aws_iam_role" "jenkins_invoke_role" {
  name               = "${var.environment}-ows-video-integration-tests"
  assume_role_policy = data.aws_iam_policy_document.jenkins_assume_role_policy.json
}

# Attach SecretManager access policy and bucket access policy to Jenkins role.
resource "aws_iam_role_policy_attachment" "ows_video_integration_tests_policy_attachment" {
  role = aws_iam_role.jenkins_invoke_role.id
  for_each = toset([
    aws_iam_policy.secrets_manager_policy.arn,
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/S3-qa-cucumbers-RW",
    aws_iam_policy.s3_list_bucket_policy.arn,
    aws_iam_policy.s3_raw_dir_readonly_policy.arn,
    data.aws_iam_policy.s3_raw_and_thumbnails_dir_putonly_policy.arn,
  ])
  policy_arn = each.value
}
