cloudwatch.tf 2.5 KB

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