require "active_support/configurable" require "net/http" require "json" require 'yaml' if defined? ::Rails require 'muchkeys/rails' end module Muchkeys class InvalidKey < StandardError; end class CLIOptionsError < StandardError; end class KeyNotSet < StandardError; end class UnknownApplication < StandardError; end class AmbigousPath < StandardError; end autoload :KeyValidator, 'muchkeys/key_validator' autoload :ApplicationClient, 'muchkeys/application_client' autoload :Secret, 'muchkeys/secret' autoload :CLI, 'muchkeys/cli' autoload :ConsulClient, 'muchkeys/consul_client' include ActiveSupport::Configurable config_accessor :application_name config_accessor :consul_url do 'http://localhost:8500' end config_accessor :private_key config_accessor :public_key config_accessor :application_name config_accessor :secrets_hint config_accessor :search_paths do %w(git/%{application_name}/secrets git/%{application_name}/config git/shared/secrets git/shared/config) end def self.env_keys # parse all environments found in .env and populate them from consul if defined? ::Rails check_dir = ::Rails.root else check_dir = Pathname.getwd end unless File.exists?(check_dir.join(".env")) raise IOError, ".env files are required for Muchkeys ENV injection to work" end File.read(check_dir.join(".env")).each_line.select(&:presence).map { |x| x.split("=")[0] } end def self.configure_from_yaml(file) app_config = YAML.load(File.read(file)).with_indifferent_access Muchkeys.configure do |config| config.application_name = app_config[:application_name] if app_config.has_key?(:application_name) config.consul_url = app_config[:consul_url] if app_config.has_key?(:consul_url) config.keys_dir = app_config[:keys_dir] if app_config.has_key?(:keys_dir) config.private_key = app_config[:private_key] if app_config.has_key?(:private_key) config.public_key = app_config[:public_key] if app_config.has_key?(:public_key) config.search_paths = app_config[:search_paths] if app_config.has_key?(:search_paths) config.secrets_hint = app_config[:secrets_hint] if app_config.has_key?(:secrets_hint) end end def self.populate_environment!(*required_keys) app = ApplicationClient.new(config) app.verify_keys(*required_keys) app.known_keys.each do |key| ENV[key] ||= app.first(key) end nil end end