Class: CfnGuardian::Stacks::Main

Inherits:
Object
  • Object
show all
Includes:
CfnDsl::CloudFormation, Logging
Defined in:
lib/cfnguardian/stacks/main.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logging

colors, included, logger, #logger, logger=

Constructor Details

#initializeMain

Returns a new instance of Main.



11
12
13
14
# File 'lib/cfnguardian/stacks/main.rb', line 11

def initialize()
  @parameters = []
  @template = CloudFormation("Guardian main stack")
end

Instance Attribute Details

#templateObject (readonly)

Returns the value of attribute template.



9
10
11
# File 'lib/cfnguardian/stacks/main.rb', line 9

def template
  @template
end

Instance Method Details

#add_iam_role(ssm_parameters) ⇒ Object



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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/cfnguardian/stacks/main.rb', line 38

def add_iam_role(ssm_parameters)
  policies = []
  policies << {
    PolicyName: 'logging',
    PolicyDocument: {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Action: [ 'logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:PutLogEvents' ],
        Resource: 'arn:aws:logs:*:*:*'
      }]
    }
  }
  policies << {
    PolicyName: 'metrics',
    PolicyDocument: {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Action: [ 'cloudwatch:PutMetricData' ],
        Resource: '*'
      }]
    }
  }
  policies << {
    PolicyName: 'attach-network-interface',
    PolicyDocument: {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Action: [ 'ec2:CreateNetworkInterface', 'ec2:DescribeNetworkInterfaces', 'ec2:DeleteNetworkInterface' ],
        Resource: '*'
      }]
    }
  }
  policies << {
    PolicyName: 'maintenance-group-actions',
    PolicyDocument: {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Action: [ 'cloudwatch:DescribeAlarms', 'cloudwatch:DisableAlarmActions', 'cloudwatch:EnableAlarmActions', 'cloudwatch:SetAlarmState' ],
        Resource: FnSub("arn:aws:cloudwatch:${AWS::Region}:${AWS::AccountId}:alarm:*")
      }]
    }
  }
  policies << {
    PolicyName: 'container-instance-check',
    PolicyDocument: {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Action: [ 'ecs:ListContainerInstances','ecs:DescribeContainerInstances' ],
        Resource: '*'
      }]
    }
  }
  if ssm_parameters.any?
    policies << {
      PolicyName: 'ssm-parameters',
      PolicyDocument: {
        Version: '2012-10-17',
        Statement: [{
          Effect: 'Allow',
          Action: [ 'ssm:GetParameter', 'ssm:GetParametersByPath', 'ssm:GetParameters' ],
          Resource: ssm_parameters.map {|param| FnSub("arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter#{param}") }
        }]
      }
    }
  end
  @template.declare do
    IAM_Role(:LambdaExecutionRole) do
      AssumeRolePolicyDocument({
        Version: '2012-10-17',
        Statement: [{
          Effect: 'Allow',
          Principal: { Service: [ 'lambda.amazonaws.com' ] },
          Action: [ 'sts:AssumeRole' ]
        }]
      })
      Path '/guardian/'
      Policies(policies)
      Tags([
        { Key: 'Name', Value: 'guardian-lambda-role' },
        { Key: 'Environment', Value: 'guardian' }
      ])
    end
  end
end

#add_lambda(check) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/cfnguardian/stacks/main.rb', line 128

def add_lambda(check)
  vpc_config = {}
  if !check.vpc.nil?
    @template.declare do
      EC2_SecurityGroup("#{check.name}SecurityGroup#{check.environment}") do
        VpcId check.vpc
        GroupDescription "Guardian lambda function #{check.group} check"
        Tags([
          { Key: 'Name', Value: "guardian-#{check.name}-#{check.environment}" },
          { Key: 'Environment', Value: 'guardian' }
        ])
      end
    end
    
    vpc_config[:SecurityGroupIds] = [Ref("#{check.name}SecurityGroup#{check.environment}")]
    vpc_config[:SubnetIds] = check.subnets
  end
  
  @template.declare do
    Lambda_Function("#{check.name}Function#{check.environment}") do
      Code({ 
        S3Bucket: FnSub("base2.guardian.lambda.checks.${AWS::Region}"), 
        S3Key: "#{check.package}/#{check.branch}/#{check.version}.zip"
      })
      Handler check.handler
      MemorySize check.memory
      Runtime check.runtime
      Timeout check.timeout
      Role FnGetAtt(:LambdaExecutionRole, :Arn)
      VpcConfig vpc_config unless vpc_config.empty?
      Tags([
        { Key: 'Name', Value: "guardian-#{check.name}-#{check.group}" },
        { Key: 'Environment', Value: 'guardian' }
      ])
    end
    
    Lambda_Permission("#{check.name}Permissions#{check.environment}") do
      FunctionName Ref("#{check.name}Function#{check.environment}")
      Action 'lambda:InvokeFunction'
      Principal 'events.amazonaws.com'
    end
  end

  return FnGetAtt("#{check.name}Function#{check.environment}", :Arn)
end

#add_maintenance_group(group, config, parameters) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/cfnguardian/stacks/main.rb', line 188

def add_maintenance_group(group,config,parameters)
  group_name = "#{group}MaintenanceGroup"
  schedules = config.fetch('Schedules', {})
  logging = config.dig('Schedules', 'Debug').to_s

  topic = @template.SNS_Topic(group_name)
  topic.TopicName group_name
  topic.Tags([{ Key: 'Environment', Value: 'guardian' }])
  parameters[group_name] = Ref(group_name)

  if schedules.any?
    event = @template.Events_Rule("#{group_name}EnableEvent")
    event.Name "#{group_name}EnableEvent"
    event.ScheduleExpression "cron(#{schedules['Enable']})"
    event.Targets([{ 
      Arn: FnGetAtt('MaintenanceGroupCheckFunction', 'Arn'), 
      Id: "#{group_name}EnableTarget", 
      Input: {action:"enable_alarms", maintenance_group: group_name, logging: logging}.to_json
    }])

    event = @template.Events_Rule("#{group_name}DisableEvent")
    event.Name "#{group_name}DisableEvent"
    event.ScheduleExpression "cron(#{schedules['Disable']})"            
    event.Targets([{ 
      Arn: FnGetAtt('MaintenanceGroupCheckFunction', 'Arn'), 
      Id: "#{group_name}DisableTarget", 
      Input: {action:"disable_alarms", maintenance_group: group_name, logging: logging}.to_json
    }])
  end
end

#add_stack(name, url, stack_parameters, stack_id) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/cfnguardian/stacks/main.rb', line 174

def add_stack(name,url,stack_parameters,stack_id)
  @template.declare do
    CloudFormation_Stack(name) do
      Parameters stack_parameters
      TemplateURL url
      TimeoutInMinutes 15
      Tags([
        { Key: 'Name', Value: "guardian-stack-#{name}" },
        { Key: 'guardian:stack-id', Value: "stk#{stack_id}"}
      ])
    end
  end
end

#build_template(stacks, checks, topics, maintenance_groups, ssm_parameters) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/cfnguardian/stacks/main.rb', line 16

def build_template(stacks,checks,topics,maintenance_groups,ssm_parameters)     
  parameters = {}
     
  topics.each do |name, sns|
    parameter = @template.Parameter(name)
    parameter.Type 'String'
    parameter.Description "SNS topic ARN for #{name} notifications"
    parameter.Default sns
    parameters[name] = Ref(name)
  end

  if maintenance_groups.any?
    add_lambda(CfnGuardian::Models::MaintenanceGroupCheck.new(maintenance_groups))
    maintenance_groups.each {|group,config| add_maintenance_group(group,config,parameters)}
  end
  
  add_iam_role(ssm_parameters)
          
  checks.each {|check| parameters["#{check.name}Function#{check.environment}"] = add_lambda(check)}
  stacks.each {|stack| add_stack(stack['Name'],stack['TemplateURL'],parameters,stack['Reference'])}        
end