Class: Jets::Dotenv::Ssm

Inherits:
Object
  • Object
show all
Defined in:
lib/jets/dotenv/ssm.rb

Constant Summary collapse

SSM_VARIABLE_REGEXP =
/^ssm:(.*)/i

Instance Method Summary collapse

Constructor Details

#initialize(variables = {}) ⇒ Ssm

Returns a new instance of Ssm.



7
8
9
10
# File 'lib/jets/dotenv/ssm.rb', line 7

def initialize(variables={})
  @variables = variables
  @missing = []
end

Instance Method Details

#fetch_ssm_value(key, value) ⇒ Object



39
40
41
42
43
44
45
46
47
48
# File 'lib/jets/dotenv/ssm.rb', line 39

def fetch_ssm_value(key, value)
  return "fake-ssm-value" if ENV['JETS_BUILD_NO_INTERNET']

  name = ssm_name(key, value)
  response = ssm.get_parameter(name: name, with_decryption: true)
  response.parameter.value
rescue Aws::SSM::Errors::ParameterNotFound
  @missing << [key, value, name]
  ''
end

#interpolate!Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/jets/dotenv/ssm.rb', line 12

def interpolate!
  interpolated_variables = @variables.map do |key, value|
    if value[SSM_VARIABLE_REGEXP]
      value = fetch_ssm_value(key, $1)
    elsif value == "SSM"
      value = fetch_ssm_value(key, "SSM")
    end

    [key, value]
  end

  interpolated_variables.each do |key, value|
    ENV[key] = value
  end

  if @missing.empty?
    interpolated_variables.to_h.sort_by { |k,_| k }.to_h # success
  else
    message = "Error loading .env variables. No matching SSM parameters found for:\n".color(:red)
    message += @missing.map do |k,v,n|
      value = v == "SSM" ? v : "ssm:#{v}"
      "  #{k}=#{value} # ssm name: #{n}"
    end.join("\n")
    abort message
  end
end

#ssmObject



60
61
62
# File 'lib/jets/dotenv/ssm.rb', line 60

def ssm
  @ssm ||= Aws::SSM::Client.new
end

#ssm_name(key, value) ⇒ Object



50
51
52
53
54
55
56
57
58
# File 'lib/jets/dotenv/ssm.rb', line 50

def ssm_name(key, value)
  if value == "SSM"
    "/#{Jets.config.project_name}/#{Jets.env}/#{key}"
  else
    value.start_with?("/") ?
      value :
      "/#{Jets.config.project_name}/#{Jets.env}/#{value}"
  end
end