Skip to content

Commit

Permalink
Merge pull request #1136 from aidanharan/secrets-files-not-found-message
Browse files Browse the repository at this point in the history
Updated secrets error message if secrets files do not exist
  • Loading branch information
djmb authored Oct 23, 2024
2 parents 53dad5f + c320343 commit 35075e2
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
17 changes: 11 additions & 6 deletions lib/kamal/secrets.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
require "dotenv"

class Kamal::Secrets
attr_reader :secrets_files

Kamal::Secrets::Dotenv::InlineCommandSubstitution.install!

def initialize(destination: nil)
@secrets_files = \
[ ".kamal/secrets-common", ".kamal/secrets#{(".#{destination}" if destination)}" ].select { |f| File.exist?(f) }
@destination = destination
@mutex = Mutex.new
end

Expand All @@ -17,21 +14,29 @@ def [](key)
secrets.fetch(key)
end
rescue KeyError
if secrets_files
if secrets_files.present?
raise Kamal::ConfigurationError, "Secret '#{key}' not found in #{secrets_files.join(", ")}"
else
raise Kamal::ConfigurationError, "Secret '#{key}' not found, no secret files provided"
raise Kamal::ConfigurationError, "Secret '#{key}' not found, no secret files (#{secrets_filenames.join(", ")}) provided"
end
end

def to_h
secrets
end

def secrets_files
@secrets_files ||= secrets_filenames.select { |f| File.exist?(f) }
end

private
def secrets
@secrets ||= secrets_files.inject({}) do |secrets, secrets_file|
secrets.merge!(::Dotenv.parse(secrets_file))
end
end

def secrets_filenames
[ ".kamal/secrets-common", ".kamal/secrets#{(".#{@destination}" if @destination)}" ]
end
end
14 changes: 14 additions & 0 deletions test/secrets_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,18 @@ class SecretsTest < ActiveSupport::TestCase
assert_equal "JKL", Kamal::Secrets.new(destination: "nodest")["SECRET2"]
end
end

test "no secrets files" do
with_test_secrets do
error = assert_raises(Kamal::ConfigurationError) do
Kamal::Secrets.new["SECRET"]
end
assert_equal "Secret 'SECRET' not found, no secret files (.kamal/secrets-common, .kamal/secrets) provided", error.message

error = assert_raises(Kamal::ConfigurationError) do
Kamal::Secrets.new(destination: "dest")["SECRET"]
end
assert_equal "Secret 'SECRET' not found, no secret files (.kamal/secrets-common, .kamal/secrets.dest) provided", error.message
end
end
end

0 comments on commit 35075e2

Please sign in to comment.