Sha256: 4a91fb138d24c928d4234f8d2332253f810a1043b69b342b66536ce512ab6d7a

Contents?: true

Size: 1.7 KB

Versions: 13

Compression:

Stored size: 1.7 KB

Contents

require 'aws-sdk-ssm'

class Jets::Dotenv
  class Ssm
    SSM_VARIABLE_REGEXP = /^ssm:(.*)/i

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

    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

    def fetch_ssm_value(key, value)
      return "fake-ssm-value" if ENV['JETS_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]
      ''
    rescue Aws::SSM::Errors::ValidationException
      puts "ERROR: Invalid SSM parameter name: #{name.inspect}".color(:red)
      raise
    end

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

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

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
jets-5.0.13 lib/jets/dotenv/ssm.rb
jets-5.0.12 lib/jets/dotenv/ssm.rb
jets-5.0.11 lib/jets/dotenv/ssm.rb
jets-5.0.10 lib/jets/dotenv/ssm.rb
jets-5.0.9 lib/jets/dotenv/ssm.rb
jets-5.0.8 lib/jets/dotenv/ssm.rb
jets-5.0.7 lib/jets/dotenv/ssm.rb
jets-5.0.6 lib/jets/dotenv/ssm.rb
jets-5.0.5 lib/jets/dotenv/ssm.rb
jets-5.0.4 lib/jets/dotenv/ssm.rb
jets-5.0.3 lib/jets/dotenv/ssm.rb
jets-5.0.2 lib/jets/dotenv/ssm.rb
jets-5.0.1 lib/jets/dotenv/ssm.rb