Class: Covalence::S3::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/covalence/core/state_stores/s3.rb

Instance Method Summary collapse

Constructor Details

#initialize(region: REGION) ⇒ Client

Returns a new instance of Client.



20
21
22
23
# File 'lib/covalence/core/state_stores/s3.rb', line 20

def initialize(region: REGION)
  @s3 = Aws::S3::Client.new(region: region)
  self.reset_cache
end

Instance Method Details

#get_cacheObject



29
30
31
# File 'lib/covalence/core/state_stores/s3.rb', line 29

def get_cache
  @cache.to_s
end

#get_doc(bucket, document) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/covalence/core/state_stores/s3.rb', line 33

def get_doc(bucket, document)
  @cache[bucket][document] ||= begin
    @s3.get_object(bucket: bucket, key: document).body.read
  rescue Aws::S3::Errors::ServiceError => err
    raise err, "Unable to retrieve document '#{document}' from bucket '#{bucket}'"
  end
end

#get_key(bucket, document, name) ⇒ Object



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
# File 'lib/covalence/core/state_stores/s3.rb', line 41

def get_key(bucket, document, name)
  begin
    doc = self.get_doc(bucket, document)
  rescue Aws::S3::Errors::ServiceError => err
    fail err.message + " and the key is: #{name}. Check your data files."
  end

  # Parse JSON response
  begin
    parsed = JSON.parse(doc)
  rescue JSON::ParserError => err
    fail "No results or unable to parse document '#{document}': " + err.message
  end

  # Determine whether the document is a Terraform state file
  tf_state = true if parsed.has_key?('terraform_version')

  # Return ID for the key specified
  if tf_state
    tf_vers = Gem::Version.new(parsed.fetch('terraform_version'))

    if tf_vers >= Gem::Version.new('0.12.0')
      root = parsed
    else
      root = parsed.fetch('modules')[0]
    end

    outputs = root.fetch('outputs')
    return outputs.fetch(name)
  end
  return parsed.fetch(name) if parsed.has_key?(name)
  fail "Requested key '#{name}' not found"
end

#reset_cacheObject



25
26
27
# File 'lib/covalence/core/state_stores/s3.rb', line 25

def reset_cache
  @cache = Hash.new{|h,k| h[k] = Hash.new}
end