diff --git a/README.md b/README.md index 7480fac..dee3a0f 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,7 @@ Looked up values are cached based on a combination of their: * Path in the Vault URI * Vault Address * Namespace +* Field This means that you can call `vault_lookup::lookup()` multiple times for the same piece of data or refer to the same `Deferred` value multiple times and diff --git a/lib/puppet/functions/vault_lookup/lookup.rb b/lib/puppet/functions/vault_lookup/lookup.rb index 8edee07..ef060ee 100644 --- a/lib/puppet/functions/vault_lookup/lookup.rb +++ b/lib/puppet/functions/vault_lookup/lookup.rb @@ -83,7 +83,7 @@ def lookup(cache, # Check the cache. # The path, vault_addr, and namepsace fields could result in a different # secret value, so use them for the cache key. - cache_key = [path, vault_addr, namespace] + cache_key = [path, vault_addr, namespace, field] cache_hash = cache.retrieve(self) prior_result = cache_hash[cache_key] unless prior_result.nil? @@ -187,10 +187,16 @@ def get_secret(client:, uri:, token:, namespace:, key:) raise Puppet::Error, append_api_errors(message, secret_response) end begin - if key.nil? - JSON.parse(secret_response.body)['data'] + json_data = JSON.parse(secret_response.body) + puts "KEY=#{key} DATA=#{json_data}" + if key.nil? && json_data['data'].key?('data') + json_data['data']['data'] + elsif key.nil? + json_data['data'] + elsif json_data['data'].key?('data') + json_data['data']['data'][key] else - JSON.parse(secret_response.body)['data']['data'][key] + json_data['data'][key] end rescue StandardError raise Puppet::Error, 'Error parsing json secret data from vault response' diff --git a/spec/functions/lookup_spec.rb b/spec/functions/lookup_spec.rb index 5be02ba..cd91388 100644 --- a/spec/functions/lookup_spec.rb +++ b/spec/functions/lookup_spec.rb @@ -81,6 +81,10 @@ result_opts = function.execute('kv/test', 'vault_addr' => "http://127.0.0.1:#{port}") expect(result_opts).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive) expect(result_opts.unwrap).to eq('foo' => 'bar') + + result_field = function.execute('kv/test', 'vault_addr' => "http://127.0.0.1:#{port}", 'field' => 'foo') + expect(result_field).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive) + expect(result_field.unwrap).to eq('bar') end end @@ -97,6 +101,10 @@ result_opts = function.execute('kv/test', 'vault_addr' => "http://127.0.0.1:#{port}", 'cert_path_segment' => custom_auth_segment, 'field' => 'bar') expect(result_opts).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive) expect(result_opts.unwrap).to eq('baz') + + result_no_field = function.execute('kv/test', 'vault_addr' => "http://127.0.0.1:#{port}", 'cert_path_segment' => custom_auth_segment) + expect(result_no_field).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive) + expect(result_no_field.unwrap).to eq('bar' => 'baz') end end