Class: CloudwatchScheduler::Provisioner

Inherits:
Object
  • Object
show all
Defined in:
lib/cloudwatch_scheduler/provisioner.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config, sqs_client: Aws::SQS::Client.new, cwe_client: Aws::CloudWatchEvents::Client.new) ⇒ Provisioner

Returns a new instance of Provisioner.



10
11
12
13
14
15
# File 'lib/cloudwatch_scheduler/provisioner.rb', line 10

def initialize(config, sqs_client: Aws::SQS::Client.new,
               cwe_client: Aws::CloudWatchEvents::Client.new)
  @config = config
  @sqs_client = sqs_client
  @cwe_client = cwe_client
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



8
9
10
# File 'lib/cloudwatch_scheduler/provisioner.rb', line 8

def config
  @config
end

Instance Method Details

#create_events!Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/cloudwatch_scheduler/provisioner.rb', line 29

def create_events!
  rule_arns = config.tasks.map do |_name, task|
    rule_arn = cwe.put_rule(
      name:                task.rule_name,
      schedule_expression: task.rule_schedule_expression,
      state:               "ENABLED",
      description:         "CloudwatchScheduler task defined at #{task.code.source_location}"
    ).rule_arn

    cwe.put_targets(
      rule:    task.rule_name,
      targets: [
        {
          id:    task.rule_name,
          arn:   queue_arn,
          input: task.event_data.to_json
        }
      ]
    )

    rule_arn
  end

  policy = {
    Version:   "2012-10-17",
    Id:        "#{queue_arn}/SQSDefaultPolicy",
    Statement: rule_arns.map do |rule_arn|
      {
        Sid:       "TrustCWESendingToSQS",
        Effect:    "Allow",
        Principal: {
          AWS: "*"
        },
        Action:    "sqs:SendMessage",
        Resource:  queue_arn,
        Condition: {
          ArnEquals: {
            "aws:SourceArn": rule_arn
          }
        }
      }
    end
  }

  sqs.set_queue_attributes(
    queue_url:  queue_url,
    attributes: {
      "Policy" => policy.to_json
    }
  )
end

#create_queue!Object



22
23
24
25
26
27
# File 'lib/cloudwatch_scheduler/provisioner.rb', line 22

def create_queue!
  attributes = { "VisibilityTimeout" => config.queue_visibility_timeout.to_s }
  @queue_url = sqs.create_queue(queue_name: queue_name, attributes: attributes).queue_url

  create_dead_letter_queue! if config.use_dead_letter_queue
end

#provisionObject



17
18
19
20
# File 'lib/cloudwatch_scheduler/provisioner.rb', line 17

def provision
  create_queue!
  create_events!
end