Class: CfnGuardian::Validate

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/cfnguardian/validate.rb

Instance Method Summary collapse

Methods included from Logging

colors, included, logger, #logger, logger=

Constructor Details

#initialize(bucket) ⇒ Validate

Returns a new instance of Validate.



12
13
14
15
16
# File 'lib/cfnguardian/validate.rb', line 12

def initialize(bucket)
  @bucket = bucket
  @prefix = "validation"
  @client = Aws::CloudFormation::Client.new()
end

Instance Method Details

#validateObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/cfnguardian/validate.rb', line 18

def validate()
  success = []
  Dir["out/*.yaml"].each do |template|
    file_size_bytes = File.size(template)

    if file_size_bytes > 51200
      success << validate_s3(template)
    else
      success << validate_local(template)
    end
  end

  if success.include?(false)
    raise CfnGuardian::TemplateValidationError, "One or more templates failed to validate"
  end
end

#validate_local(path) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/cfnguardian/validate.rb', line 35

def validate_local(path)
  logger.info "Validating template #{path} locally"
  template = File.read path
  begin
    response = @client.validate_template({
      template_body: template
    })
  rescue Aws::CloudFormation::Errors::ValidationError => e
    logger.warn("template #{path} failed validation with error:\n====> #{e.message}")
    return false
  end
  return true
end

#validate_s3(path) ⇒ Object



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
# File 'lib/cfnguardian/validate.rb', line 49

def validate_s3(path)
  success = true
  logger.info "Validating template #{path} from s3 bucket #{@bucket}"
  
  template = File.read path
  md5 = Digest::MD5.hexdigest template
  prefix = "#{@prefix}/#{md5}"

  client = Aws::S3::Client.new()
  client.put_object({
    body: template,
    bucket: @bucket,
    key: prefix
  })
  logger.info("uploaded #{path} to s3://#{@bucket}/#{prefix}")
  
  begin
    response = @client.validate_template({
      template_url: "https://#{@bucket}.s3.amazonaws.com/#{prefix}"
    })
  rescue Aws::CloudFormation::Errors::ValidationError => e
    logger.warn("template #{path} failed validation with error:\n====> #{e.message}")
    success = false
  end

  client.put_object({
    bucket: @bucket,
    key: prefix
  })
  logger.debug("removed validated template s3://#{@bucket}/#{prefix}")
  
  return success
end