Class: SecretsManager::Manager

Inherits:
Object
  • Object
show all
Defined in:
lib/secrets-manager.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client: nil) ⇒ Manager

Returns a new instance of Manager.



40
41
42
43
# File 'lib/secrets-manager.rb', line 40

def initialize(client: nil)
  @cache = Cache.new
  @aws_client = client
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



38
39
40
# File 'lib/secrets-manager.rb', line 38

def cache
  @cache
end

Instance Method Details

#[](path) ⇒ Object



79
80
81
# File 'lib/secrets-manager.rb', line 79

def [](path)
  fetch(path)
end

#clientObject



49
50
51
52
53
54
55
56
# File 'lib/secrets-manager.rb', line 49

def client
  return @aws_client if @aws_client

  @_client ||= Aws::SecretsManager::Client.new({
    region: ENV.fetch('AWS_SECRETS_REGION', 'us-east-1'),
    credentials: Aws::Credentials.new(ENV['AWS_SECRETS_KEY'], ENV['AWS_SECRETS_SECRET'])
  })
end

#fetch(secret_path) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/secrets-manager.rb', line 58

def fetch(secret_path)
  if secret_path.start_with?("global")
    resolved_path = secret_path
  else
    resolved_path = secret_env + '/' + secret_path
  end

  cached_value = cache.find(resolved_path)
  return cached_value if cached_value

  response = client.get_secret_value(secret_id: resolved_path)
  return nil unless response && response.secret_string
  object = JSON.parse(response.secret_string, symbolize_names: true)

  value = parse_value(object)
  cache.set(resolved_path, value, parse_ttl(object))
  return value
rescue Aws::SecretsManager::Errors::ResourceNotFoundException => e
  raise SecretsManager::SecretNotFound, "Could not find secret with path #{resolved_path}"
end

#secret_envObject



45
46
47
# File 'lib/secrets-manager.rb', line 45

def secret_env
  ENV['AWS_SECRETS_ENV'] || ENV['RACK_ENV'] || 'development'
end