cloudwatch.tf 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. # creates a role and schedules a build for each server type
  2. #
  3. # Being polite aws users, we randomize the schedule over the hours of the early morning
  4. resource "random_integer" "hour" {
  5. min = 5 # Midnight ET
  6. max = 11 # 6am ET
  7. }
  8. resource "random_integer" "minute" {
  9. min = 0
  10. max = 59
  11. }
  12. resource "aws_cloudwatch_event_rule" "schedule_rule" {
  13. for_each = local.splunk_server_types
  14. name = "scheduled_build_${var.repository}_${each.value}"
  15. schedule_expression = "cron(${random_integer.minute.result} ${random_integer.hour.result} * * ? *)"
  16. }
  17. resource "aws_iam_role" "codebuild_role" {
  18. name_prefix = "splunk_apps_codebuild_role"
  19. path = "/aws_services/"
  20. assume_role_policy = <<EOF
  21. {
  22. "Version": "2012-10-17",
  23. "Statement": [
  24. {
  25. "Effect": "Allow",
  26. "Principal": {
  27. "Service": [
  28. "events.amazonaws.com",
  29. "codebuild.amazonaws.com"
  30. ]
  31. },
  32. "Action": "sts:AssumeRole"
  33. }
  34. ]
  35. }
  36. EOF
  37. }
  38. resource "aws_iam_policy" "codebuild_policy" {
  39. name_prefix = "splunk_apps_policy"
  40. path = "/aws_services/"
  41. policy = <<POLICY
  42. {
  43. "Version": "2012-10-17",
  44. "Statement": [
  45. {
  46. "Effect": "Allow",
  47. "Resource": [
  48. "arn:${var.aws_partition}:logs:${var.aws_region}:${var.aws_account_id}:log-group:/aws/codebuild/*"
  49. ],
  50. "Action": [
  51. "logs:CreateLogGroup",
  52. "logs:CreateLogStream",
  53. "logs:PutLogEvents"
  54. ]
  55. },
  56. {
  57. "Action": [
  58. "codebuild:StartBuild",
  59. "codebuild:StopBuild",
  60. "codebuild:BatchGet*",
  61. "codebuild:Get*",
  62. "codebuild:List*",
  63. "codecommit:GetBranch",
  64. "codecommit:GetCommit",
  65. "codecommit:GetRepository",
  66. "codecommit:ListBranches"
  67. ],
  68. "Effect": "Allow",
  69. "Resource": "*"
  70. }
  71. ]
  72. }
  73. POLICY
  74. }
  75. resource "aws_iam_policy_attachment" "service_role_attachment" {
  76. name = "splunk_apps_policy_attachment"
  77. policy_arn = aws_iam_policy.codebuild_policy.arn
  78. roles = [aws_iam_role.codebuild_role.id]
  79. }
  80. resource "aws_cloudwatch_event_target" "trigger_build" {
  81. for_each = local.splunk_server_types
  82. target_id = "trigger_build_${var.repository}_${each.value}"
  83. rule = aws_cloudwatch_event_rule.schedule_rule[each.value].name
  84. arn = aws_codebuild_project.this[each.value].id
  85. role_arn = aws_iam_role.codebuild_role.arn
  86. }