Skip to content

Commit 8dbfe0a

Browse files
committed
fix: validate that contexts exists before trying to build client
1 parent 3c240ae commit 8dbfe0a

3 files changed

Lines changed: 27 additions & 1 deletion

File tree

lib/krane/kubeclient_builder.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,9 @@ def validate_config_files!
135135

136136
def build_kubeclient(api_version:, context:, endpoint_path: nil)
137137
validate_config_files!
138-
@kubeclient_configs ||= @kubeconfig_files.map { |f| Kubeclient::Config.read(f) }
138+
@kubeclient_configs ||= @kubeconfig_files
139+
.select { |f| config_has_contexts?(f) }
140+
.map { |f| Kubeclient::Config.read(f) }
139141
# Find a context defined in kube conf files that matches the input context by name
140142
config = @kubeclient_configs.find { |c| c.contexts.include?(context) }
141143
raise ContextMissingError.new(context, @kubeconfig_files) unless config
@@ -154,5 +156,10 @@ def build_kubeclient(api_version:, context:, endpoint_path: nil)
154156
client.discover
155157
client
156158
end
159+
160+
def config_has_contexts?(file_path)
161+
config = YAML.safe_load(File.read(file_path))
162+
config["contexts"].is_a?(Array) && config["contexts"].any?
163+
end
157164
end
158165
end
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
apiVersion: v1
2+
clusters: null
3+
contexts: null
4+
current-context: something
5+
kind: Config
6+
preferences: {}
7+
users: null

test/unit/krane/kubeclient_builder_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,4 +64,16 @@ def test_build_client_from_multiple_config_files
6464
assert(!client.nil?, "Expected Kubeclient is built for context " \
6565
"#{context_name} with success.")
6666
end
67+
68+
def test_empty_contexts_kubeconfig_file
69+
# Should ignore kubeconfig files with no contexts defined
70+
Kubeclient::Client.any_instance.stubs(:discover)
71+
empty_config = File.join(__dir__, '../../fixtures/kube-config/empty_config.yml')
72+
dummy_config = File.join(__dir__, '../../fixtures/kube-config/dummy_config.yml')
73+
74+
# When combined with a valid config, the empty one is silently ignored
75+
kubeclient_builder = Krane::KubeclientBuilder.new(kubeconfig: "#{empty_config}:#{dummy_config}")
76+
client = kubeclient_builder.build_v1_kubeclient("docker-for-desktop")
77+
assert(!client.nil?, "Expected Kubeclient to be built successfully, ignoring empty config")
78+
end
6779
end

0 commit comments

Comments
 (0)