| 1 | package Kubernetes::REST::Kubeconfig; | ||
| 2 | # ABSTRACT: Parse kubeconfig files and create Kubernetes::REST instances | ||
| 3 | our $VERSION = '1.108'; | ||
| 4 | use Moo; | ||
| 5 | use Carp qw(croak); | ||
| 6 | use Config (); | ||
| 7 | use YAML::XS (); | ||
| 8 | use Path::Tiny qw(path); | ||
| 9 | use MIME::Base64 qw(decode_base64); | ||
| 10 | use Kubernetes::REST; | ||
| 11 | use Kubernetes::REST::Server; | ||
| 12 | use Kubernetes::REST::AuthToken; | ||
| 13 | use Kubernetes::REST::AuthTokenFile; | ||
| 14 | use namespace::clean; | ||
| 15 | |||
| 16 | |||
| 17 | has kubeconfig_path => ( | ||
| 18 | is => 'ro', | ||
| 19 | default => sub { $_[0]->_default_kubeconfig_path }, | ||
| 20 | ); | ||
| 21 | |||
| 22 | |||
| 23 | sub _default_kubeconfig_path { | ||
| 24 | my $self = shift; | ||
| 25 | return $ENV{KUBECONFIG} if defined $ENV{KUBECONFIG} and length $ENV{KUBECONFIG}; | ||
| 26 | return undef unless defined $ENV{HOME} and length $ENV{HOME}; | ||
| 27 | return "$ENV{HOME}/.kube/config"; | ||
| 28 | } | ||
| 29 | |||
| 30 | my $PATH_SEP = $Config::Config{path_sep} || ':'; | ||
| 31 | |||
| 32 | has kubeconfig_paths => ( | ||
| 33 | is => 'lazy', | ||
| 34 | init_arg => undef, | ||
| 35 | builder => sub { | ||
| 36 | my $self = shift; | ||
| 37 | my $path = $self->kubeconfig_path; | ||
| 38 | return [] unless defined $path; | ||
| 39 | my @entries = ref $path eq 'ARRAY' ? @$path : split /\Q$PATH_SEP\E/, $path, -1; | ||
| 40 | return [ grep { defined and length } @entries ]; | ||
| 41 | }, | ||
| 42 | ); | ||
| 43 | |||
| 44 | |||
| 45 | has context_name => ( | ||
| 46 | is => 'ro', | ||
| 47 | predicate => 1, | ||
| 48 | ); | ||
| 49 | |||
| 50 | |||
| 51 | has refresh_token_files => ( | ||
| 52 | is => 'ro', | ||
| 53 | default => sub { 1 }, | ||
| 54 | ); | ||
| 55 | |||
| 56 | |||
| 57 | has _config => ( | ||
| 58 | is => 'lazy', | ||
| 59 | builder => sub { | ||
| 60 | my $self = shift; | ||
| 61 | my @configs; | ||
| 62 | for my $path (@{ $self->kubeconfig_paths }) { | ||
| 63 | # A file the list names but that is not there is not an error, the | ||
| 64 | # same way it is not one for kubectl. | ||
| 65 | next unless -f $path; | ||
| 66 | my $config = YAML::XS::LoadFile($path); | ||
| 67 | next unless ref $config eq 'HASH'; | ||
| 68 | # While the file is being read is the only place where its own | ||
| 69 | # directory is still known: the merge below keeps whole entries but | ||
| 70 | # not where they came from, and with several files merged that | ||
| 71 | # directory differs per entry. | ||
| 72 | push @configs, $self->_resolve_file_references($config, $path); | ||
| 73 | } | ||
| 74 | return undef unless @configs; | ||
| 75 | return $self->_merge_configs(@configs); | ||
| 76 | }, | ||
| 77 | ); | ||
| 78 | |||
| 79 | # The file references a kubeconfig entry can hold, per section: the key of the | ||
| 80 | # entry body, and the fields in it that name a file. The *-data twins hold | ||
| 81 | # base64 content rather than a path and are none of this code's business, and | ||
| 82 | # neither is an exec plugin's command, which is looked up in PATH. | ||
| 83 | my %FILE_REFERENCES = ( | ||
| 84 | clusters => { body => 'cluster', fields => ['certificate-authority'] }, | ||
| 85 | users => { body => 'user', fields => [qw(client-certificate client-key tokenFile)] }, | ||
| 86 | ); | ||
| 87 | |||
| 88 | sub _resolve_file_references { | ||
| 89 | my ($self, $config, $file) = @_; | ||
| 90 | |||
| 91 | # Absolute, so the result survives a later chdir - the file itself may well | ||
| 92 | # have been named relatively. | ||
| 93 | my $dir = path($file)->absolute->parent; | ||
| 94 | |||
| 95 | for my $section (sort keys %FILE_REFERENCES) { | ||
| 96 | my $spec = $FILE_REFERENCES{$section}; | ||
| 97 | for my $entry (@{ $config->{$section} // [] }) { | ||
| 98 | next unless ref $entry eq 'HASH'; | ||
| 99 | my $body = $entry->{ $spec->{body} }; | ||
| 100 | next unless ref $body eq 'HASH'; | ||
| 101 | for my $field (@{ $spec->{fields} }) { | ||
| 102 | my $value = $body->{$field}; | ||
| 103 | next unless defined $value and !ref $value and length $value; | ||
| 104 | next if path($value)->is_absolute; | ||
| 105 | $body->{$field} = $dir->child($value)->stringify; | ||
| 106 | } | ||
| 107 | } | ||
| 108 | } | ||
| 109 | |||
| 110 | return $config; | ||
| 111 | } | ||
| 112 | |||
| 113 | # The sections keyed by name, which are unioned; everything else is a plain | ||
| 114 | # top-level key taken from the first file that has it. | ||
| 115 | my @NAMED_SECTIONS = qw(clusters contexts users); | ||
| 116 | my %IS_NAMED_SECTION = map { $_ => 1 } @NAMED_SECTIONS; | ||
| 117 | |||
| 118 | sub _merge_configs { | ||
| 119 | my ($self, @configs) = @_; | ||
| 120 | |||
| 121 | my (%merged, %seen); | ||
| 122 | for my $config (@configs) { | ||
| 123 | for my $section (@NAMED_SECTIONS) { | ||
| 124 | for my $entry (@{ $config->{$section} // [] }) { | ||
| 125 | next unless ref $entry eq 'HASH' and defined $entry->{name}; | ||
| 126 | next if $seen{$section}{ $entry->{name} }++; | ||
| 127 | push @{ $merged{$section} }, $entry; | ||
| 128 | } | ||
| 129 | } | ||
| 130 | for my $key (grep { !$IS_NAMED_SECTION{$_} } keys %$config) { | ||
| 131 | next if exists $merged{$key}; | ||
| 132 | my $value = $config->{$key}; | ||
| 133 | next unless defined $value; | ||
| 134 | next if !ref $value and !length $value; | ||
| 135 | $merged{$key} = $value; | ||
| 136 | } | ||
| 137 | } | ||
| 138 | |||
| 139 | return \%merged; | ||
| 140 | } | ||
| 141 | |||
| 142 | sub _kubeconfig_paths_string { | ||
| 143 | my $self = shift; | ||
| 144 | my $paths = $self->kubeconfig_paths; | ||
| 145 | return join($PATH_SEP, @$paths) if @$paths; | ||
| 146 | return 'neither KUBECONFIG nor HOME is set'; | ||
| 147 | } | ||
| 148 | |||
| 149 | sub _not_found_error { | ||
| 150 | my $self = shift; | ||
| 151 | return 'Kubeconfig not found: ' . $self->_kubeconfig_paths_string; | ||
| 152 | } | ||
| 153 | |||
| 154 | # The two ways a lookup fails before a single name is compared: the kubeconfig | ||
| 155 | # defines no such section at all, or there is no name to look for. Both used to | ||
| 156 | # reach _find_by_name, which compared against undef and croaked "not found: " | ||
| 157 | # with nothing behind the colon - an unusable kubeconfig, described in a way | ||
| 158 | # nobody can act on. | ||
| 159 | sub _assert_lookup { | ||
| 160 | my ($self, $config, $section, $name, $missing_name_error) = @_; | ||
| 161 | my $entries = $config->{$section}; | ||
| 162 | croak "kubeconfig defines no $section: " . $self->_kubeconfig_paths_string | ||
| 163 | unless ref $entries eq 'ARRAY' and @$entries; | ||
| 164 | croak "$missing_name_error: " . $self->_kubeconfig_paths_string | ||
| 165 | unless defined $name and length $name; | ||
| 166 | return; | ||
| 167 | } | ||
| 168 | |||
| 169 | sub current_context_name { | ||
| 170 | my $self = shift; | ||
| 171 | |||
| 172 | |||
| 173 | return $self->context_name if $self->has_context_name; | ||
| 174 | my $config = $self->_config | ||
| 175 | or croak $self->_not_found_error; | ||
| 176 | return $config->{'current-context'}; | ||
| 177 | } | ||
| 178 | |||
| 179 | sub contexts { | ||
| 180 | my $self = shift; | ||
| 181 | |||
| 182 | |||
| 183 | my $config = $self->_config | ||
| 184 | or croak $self->_not_found_error; | ||
| 185 | return [ map { $_->{name} } @{$config->{contexts} // []} ]; | ||
| 186 | } | ||
| 187 | |||
| 188 | sub _find_by_name { | ||
| 189 | my ($self, $list, $name) = @_; | ||
| 190 | for my $item (@{$list // []}) { | ||
| 191 | return $item if $item->{name} eq $name; | ||
| 192 | } | ||
| 193 | return undef; | ||
| 194 | } | ||
| 195 | |||
| 196 | sub context { | ||
| 197 | my ($self, $name) = @_; | ||
| 198 | |||
| 199 | |||
| 200 | my $config = $self->_config | ||
| 201 | or croak $self->_not_found_error; | ||
| 202 | $name //= $self->current_context_name; | ||
| 203 | $self->_assert_lookup($config, 'contexts', $name, | ||
| 204 | 'kubeconfig has no current-context set'); | ||
| 205 | my $ctx = $self->_find_by_name($config->{contexts}, $name) | ||
| 206 | or croak "Context not found: $name"; | ||
| 207 | return $ctx->{context}; | ||
| 208 | } | ||
| 209 | |||
| 210 | sub cluster { | ||
| 211 | my ($self, $name) = @_; | ||
| 212 | |||
| 213 | |||
| 214 | my $config = $self->_config | ||
| 215 | or croak $self->_not_found_error; | ||
| 216 | $self->_assert_lookup($config, 'clusters', $name, 'no cluster name given'); | ||
| 217 | my $cluster = $self->_find_by_name($config->{clusters}, $name) | ||
| 218 | or croak "Cluster not found: $name"; | ||
| 219 | return $cluster->{cluster}; | ||
| 220 | } | ||
| 221 | |||
| 222 | sub user { | ||
| 223 | my ($self, $name) = @_; | ||
| 224 | |||
| 225 | |||
| 226 | my $config = $self->_config | ||
| 227 | or croak $self->_not_found_error; | ||
| 228 | $self->_assert_lookup($config, 'users', $name, 'no user name given'); | ||
| 229 | my $user = $self->_find_by_name($config->{users}, $name) | ||
| 230 | or croak "User not found: $name"; | ||
| 231 | return $user->{user}; | ||
| 232 | } | ||
| 233 | |||
| 234 | sub _resolve_cert { | ||
| 235 | my ($self, $hash, $key) = @_; | ||
| 236 | |||
| 237 | my $data_key = "${key}-data"; | ||
| 238 | if (my $data = $hash->{$data_key}) { | ||
| 239 | return (pem => decode_base64($data)); | ||
| 240 | } | ||
| 241 | |||
| 242 | if (my $file = $hash->{$key}) { | ||
| 243 | return (file => $file); | ||
| 244 | } | ||
| 245 | |||
| 246 | return (); | ||
| 247 | } | ||
| 248 | |||
| 249 | sub api { | ||
| 250 | my ($self, $context_name) = @_; | ||
| 251 | |||
| 252 | |||
| 253 | # If no kubeconfig, try in-cluster | ||
| 254 | unless ($self->_config) { | ||
| 255 | return $self->_in_cluster_api | ||
| 256 | // croak $self->_not_found_error . " and not running in-cluster"; | ||
| 257 | } | ||
| 258 | |||
| 259 | $context_name //= $self->current_context_name; | ||
| 260 | my $ctx = $self->context($context_name); | ||
| 261 | my $cluster = $self->cluster($ctx->{cluster}); | ||
| 262 | my $user = $self->user($ctx->{user}); | ||
| 263 | |||
| 264 | # Build server config | ||
| 265 | my %server = ( | ||
| 266 | endpoint => $cluster->{server}, | ||
| 267 | ); | ||
| 268 | |||
| 269 | if (my %ca = $self->_resolve_cert($cluster, 'certificate-authority')) { | ||
| 270 | $server{ $ca{pem} ? 'ssl_ca_pem' : 'ssl_ca_file' } = $ca{pem} // $ca{file}; | ||
| 271 | } | ||
| 272 | |||
| 273 | if ($cluster->{'insecure-skip-tls-verify'}) { | ||
| 274 | $server{ssl_verify_server} = 0; | ||
| 275 | } else { | ||
| 276 | $server{ssl_verify_server} = 1; | ||
| 277 | } | ||
| 278 | |||
| 279 | if (my %cert = $self->_resolve_cert($user, 'client-certificate')) { | ||
| 280 | $server{ $cert{pem} ? 'ssl_cert_pem' : 'ssl_cert_file' } = $cert{pem} // $cert{file}; | ||
| 281 | } | ||
| 282 | |||
| 283 | if (my %key = $self->_resolve_cert($user, 'client-key')) { | ||
| 284 | $server{ $key{pem} ? 'ssl_key_pem' : 'ssl_key_file' } = $key{pem} // $key{file}; | ||
| 285 | } | ||
| 286 | |||
| 287 | # Build credentials | ||
| 288 | my $credentials; | ||
| 289 | if (my $token = $user->{token}) { | ||
| 290 | $credentials = Kubernetes::REST::AuthToken->new(token => $token); | ||
| 291 | } elsif (my $token_file = $user->{tokenFile}) { | ||
| 292 | $credentials = $self->_token_file_credential( | ||
| 293 | $token_file, "tokenFile of user '$ctx->{user}'" | ||
| 294 | ); | ||
| 295 | } elsif (my $exec = $user->{exec}) { | ||
| 296 | $credentials = $self->_exec_credential($exec); | ||
| 297 | } else { | ||
| 298 | # No token auth, might be using client certs only | ||
| 299 | $credentials = Kubernetes::REST::AuthToken->new(token => ''); | ||
| 300 | } | ||
| 301 | |||
| 302 | return Kubernetes::REST->new( | ||
| 303 | server => Kubernetes::REST::Server->new(%server), | ||
| 304 | credentials => $credentials, | ||
| 305 | ); | ||
| 306 | } | ||
| 307 | |||
| 308 | # Credentials for a file holding a bearer token: a user's tokenFile, or the | ||
| 309 | # service account token mounted into a pod. Both are written by something else | ||
| 310 | # - the kubelet, a login helper - and both are rotated under a running process, | ||
| 311 | # so both get credentials that notice. | ||
| 312 | sub _token_file_credential { | ||
| 313 | my ($self, $file, $what) = @_; | ||
| 314 | |||
| 315 | return Kubernetes::REST::AuthTokenFile->new( | ||
| 316 | file => $file, | ||
| 317 | description => $what, | ||
| 318 | refresh => $self->refresh_token_files ? 1 : 0, | ||
| 319 | ); | ||
| 320 | } | ||
| 321 | |||
| 322 | sub _exec_credential { | ||
| 323 | my ($self, $exec) = @_; | ||
| 324 | |||
| 325 | my $cmd = $exec->{command}; | ||
| 326 | my @args = @{$exec->{args} // []}; | ||
| 327 | |||
| 328 | # Set up environment | ||
| 329 | local %ENV = %ENV; | ||
| 330 | for my $env (@{$exec->{env} // []}) { | ||
| 331 | $ENV{$env->{name}} = $env->{value}; | ||
| 332 | } | ||
| 333 | |||
| 334 | my $output = `$cmd @args`; | ||
| 335 | croak "exec credential command failed: $cmd" if $?; | ||
| 336 | |||
| 337 | my $cred = YAML::XS::Load($output); | ||
| 338 | my $token = $cred->{status}{token} | ||
| 339 | or croak "exec credential did not return token"; | ||
| 340 | |||
| 341 | return Kubernetes::REST::AuthToken->new(token => $token); | ||
| 342 | } | ||
| 343 | |||
| 344 | my $SA_TOKEN = '/var/run/secrets/kubernetes.io/serviceaccount/token'; | ||
| 345 | my $SA_CA = '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt'; | ||
| 346 | |||
| 347 | sub _in_cluster_api { | ||
| 348 | my ($self) = @_; | ||
| 349 | return undef unless -f $SA_TOKEN; | ||
| 350 | |||
| 351 | my $host = $ENV{KUBERNETES_SERVICE_HOST} // 'kubernetes.default.svc'; | ||
| 352 | my $port = $ENV{KUBERNETES_SERVICE_PORT} // '443'; | ||
| 353 | |||
| 354 | return Kubernetes::REST->new( | ||
| 355 | server => Kubernetes::REST::Server->new( | ||
| 356 | endpoint => "https://$host:$port", | ||
| 357 | ssl_ca_file => $SA_CA, | ||
| 358 | ssl_verify_server => 1, | ||
| 359 | ), | ||
| 360 | credentials => $self->_token_file_credential( | ||
| 361 | $SA_TOKEN, 'service account token' | ||
| 362 | ), | ||
| 363 | ); | ||
| 364 | } | ||
| 365 | |||
| 366 | 1; | ||
| 367 | |||
| 368 | __END__ | ||
| 369 | |||
| 370 | =pod | ||
| 371 | |||
| 372 | =encoding UTF-8 | ||
| 373 | |||
| 374 | =head1 NAME | ||
| 375 | |||
| 376 | Kubernetes::REST::Kubeconfig - Parse kubeconfig files and create Kubernetes::REST instances | ||
| 377 | |||
| 378 | =head1 VERSION | ||
| 379 | |||
| 380 | version 1.108 | ||
| 381 | |||
| 382 | =head1 SYNOPSIS | ||
| 383 | |||
| 384 | use Kubernetes::REST::Kubeconfig; | ||
| 385 | |||
| 386 | # Use default kubeconfig and current context | ||
| 387 | my $kc = Kubernetes::REST::Kubeconfig->new; | ||
| 388 | my $api = $kc->api; | ||
| 389 | |||
| 390 | # Specify kubeconfig and context | ||
| 391 | my $kc = Kubernetes::REST::Kubeconfig->new( | ||
| 392 | kubeconfig_path => '/path/to/kubeconfig', | ||
| 393 | context_name => 'my-cluster', | ||
| 394 | ); | ||
| 395 | |||
| 396 | # Several kubeconfigs, merged the way kubectl merges $KUBECONFIG | ||
| 397 | my $kc = Kubernetes::REST::Kubeconfig->new( | ||
| 398 | kubeconfig_path => '/etc/kube/base:/home/me/.kube/extra', | ||
| 399 | ); | ||
| 400 | my $kc = Kubernetes::REST::Kubeconfig->new( | ||
| 401 | kubeconfig_path => [ '/etc/kube/base', '/home/me/.kube/extra' ], | ||
| 402 | ); | ||
| 403 | |||
| 404 | # List available contexts | ||
| 405 | my $contexts = $kc->contexts; | ||
| 406 | |||
| 407 | # Get API for specific context | ||
| 408 | my $api = $kc->api('production'); | ||
| 409 | |||
| 410 | # Inside a Kubernetes pod: no kubeconfig needed, auto-detects service account | ||
| 411 | my $api = Kubernetes::REST::Kubeconfig->new->api; | ||
| 412 | |||
| 413 | =head1 DESCRIPTION | ||
| 414 | |||
| 415 | Parses Kubernetes kubeconfig files (typically C<~/.kube/config>) and creates configured L<Kubernetes::REST> instances. | ||
| 416 | |||
| 417 | Several kubeconfig files can be given at once - as the C<:>-separated list | ||
| 418 | C<kubectl> expects in C<KUBECONFIG>, or as an arrayref - and are merged into | ||
| 419 | one configuration the way C<kubectl> merges them. See L</MERGING>. | ||
| 420 | |||
| 421 | When no kubeconfig file is found, automatically falls back to in-cluster | ||
| 422 | authentication using the pod's service account token. | ||
| 423 | |||
| 424 | Supports: | ||
| 425 | |||
| 426 | =over 4 | ||
| 427 | |||
| 428 | =item * Multiple clusters and contexts | ||
| 429 | |||
| 430 | =item * Merging several kubeconfig files, C<kubectl>-style | ||
| 431 | |||
| 432 | =item * Token authentication, inline or from a C<tokenFile> | ||
| 433 | |||
| 434 | =item * Client certificate authentication | ||
| 435 | |||
| 436 | =item * Inline certificate data (base64 encoded) | ||
| 437 | |||
| 438 | =item * External certificate files | ||
| 439 | |||
| 440 | =item * Exec-based credential plugins | ||
| 441 | |||
| 442 | =item * In-cluster service account auto-detection | ||
| 443 | |||
| 444 | =back | ||
| 445 | |||
| 446 | =head2 kubeconfig_path | ||
| 447 | |||
| 448 | Path to the kubeconfig file: a single path, a C<$Config{path_sep}>-separated | ||
| 449 | list of paths (C<:> on Unix, C<;> on Win32), or an arrayref of paths. A list is | ||
| 450 | merged as described in L</MERGING>; a single path behaves exactly as it always | ||
| 451 | has. | ||
| 452 | |||
| 453 | Defaults to the C<KUBECONFIG> environment variable if it is set and not empty, | ||
| 454 | otherwise to C<~/.kube/config>. With neither C<KUBECONFIG> nor C<HOME> set | ||
| 455 | there is no path to guess, and the default is C<undef>: L</api> then goes | ||
| 456 | straight to in-cluster authentication, and every method that needs a file | ||
| 457 | croaks naming the two missing variables instead of reaching for C</.kube/config>. | ||
| 458 | |||
| 459 | The split list, without empty entries, is L</kubeconfig_paths>. | ||
| 460 | |||
| 461 | =head2 kubeconfig_paths | ||
| 462 | |||
| 463 | Arrayref of the individual kubeconfig paths L</kubeconfig_path> names, in the | ||
| 464 | order they are merged, with empty entries removed. Derived from | ||
| 465 | C<kubeconfig_path> and not settable on its own. Empty when neither | ||
| 466 | C<KUBECONFIG> nor C<HOME> is set. | ||
| 467 | |||
| 468 | The paths are not checked for existence here - see L</MERGING> for what happens | ||
| 469 | to entries that are not there. | ||
| 470 | |||
| 471 | =head2 context_name | ||
| 472 | |||
| 473 | Optional. The context name to use. If not specified, uses the current-context from the kubeconfig. | ||
| 474 | |||
| 475 | =head2 refresh_token_files | ||
| 476 | |||
| 477 | Whether a token that comes from a file - a user's C<tokenFile>, or the service | ||
| 478 | account token of the in-cluster fallback - is re-read when the file changes. | ||
| 479 | True by default; see L</TOKEN FILES AND ROTATION>. | ||
| 480 | |||
| 481 | Set it to false and such a token is read once, when L</api> builds the client, | ||
| 482 | and never again, which is what this module did before it could refresh. | ||
| 483 | |||
| 484 | my $kc = Kubernetes::REST::Kubeconfig->new(refresh_token_files => 0); | ||
| 485 | |||
| 486 | It reaches every client this object builds. A caller who wants it per client | ||
| 487 | can build a second C<Kubernetes::REST::Kubeconfig> - they are cheap, and the | ||
| 488 | kubeconfig is only read when a client is actually built. | ||
| 489 | |||
| 490 | =head2 current_context_name | ||
| 491 | |||
| 492 | my $name = $kc->current_context_name; | ||
| 493 | |||
| 494 | Returns the current context name (either from C<context_name> attribute or from the kubeconfig's C<current-context>). With several kubeconfig files merged, C<current-context> is the one from the first file that sets it. | ||
| 495 | |||
| 496 | =head2 contexts | ||
| 497 | |||
| 498 | my $contexts = $kc->contexts; | ||
| 499 | |||
| 500 | Returns an arrayref of all available context names from the kubeconfig, or from every merged kubeconfig. | ||
| 501 | |||
| 502 | =head2 context | ||
| 503 | |||
| 504 | my $ctx = $kc->context; | ||
| 505 | my $ctx = $kc->context('production'); | ||
| 506 | |||
| 507 | Look up a context entry by name and return its C<context> hashref (with C<cluster>, C<user>, and optional C<namespace> keys). Defaults to C<current_context_name> when C<$name> is omitted. Croaks if the context is not found, and, before it gets that far, with a message naming the kubeconfig if the kubeconfig defines no contexts at all or has no C<current-context> to fall back to. | ||
| 508 | |||
| 509 | =head2 cluster | ||
| 510 | |||
| 511 | my $cluster = $kc->cluster('prod-cluster'); | ||
| 512 | |||
| 513 | Look up a cluster entry by name and return its C<cluster> hashref (with keys such as C<server>, C<certificate-authority>/C<certificate-authority-data>, and C<insecure-skip-tls-verify>). Croaks if the cluster is not found, and, before it gets that far, with a message naming the kubeconfig if the kubeconfig defines no clusters at all or no name was given. | ||
| 514 | |||
| 515 | =head2 user | ||
| 516 | |||
| 517 | my $user = $kc->user('token-user'); | ||
| 518 | |||
| 519 | Look up a user entry by name and return its C<user> hashref (with keys such as C<token>, C<client-certificate>/C<client-certificate-data>, C<client-key>/C<client-key-data>, or C<exec>). Croaks if the user is not found, and, before it gets that far, with a message naming the kubeconfig if the kubeconfig defines no users at all or no name was given. | ||
| 520 | |||
| 521 | =head2 api | ||
| 522 | |||
| 523 | my $api = $kc->api; | ||
| 524 | my $api = $kc->api('production'); | ||
| 525 | |||
| 526 | Create a L<Kubernetes::REST> instance (with a L<Kubernetes::REST::Server> built from the cluster entry and credentials built from the user entry) configured from the kubeconfig. If C<$context_name> is provided, uses that context; otherwise uses the current context. | ||
| 527 | |||
| 528 | Certificate and key material can come from either an inline base64 C<*-data> field or a plain file-path field in the kubeconfig. Inline data is decoded and passed to L<Kubernetes::REST::Server> as an in-memory PEM string (C<ssl_ca_pem>/C<ssl_cert_pem>/C<ssl_key_pem>) rather than written to a temporary file, so the returned L<Kubernetes::REST> instance keeps working after this C<Kubernetes::REST::Kubeconfig> object is garbage-collected. A file path is passed on as C<ssl_ca_file>/C<ssl_cert_file>/C<ssl_key_file>, absolute: a relative one is resolved against the directory of the kubeconfig that defined the entry, see L</MERGING>. | ||
| 529 | |||
| 530 | User authentication is resolved in this order: a plain C<token> field; a C<tokenFile>, whose content is the bearer token; an C<exec> block (kubectl's exec-credential-plugin mechanism, used for e.g. cloud IAM auth), which runs the configured C<command> (with C<args> and any C<env> entries applied to the child process) and reads C<status.token> from its output (parsed as YAML, which also accepts the JSON that real exec plugins emit); otherwise an empty token, for setups that authenticate via client certificate alone. | ||
| 531 | |||
| 532 | That order is C<kubectl>'s. An inline C<token> wins over a C<tokenFile> - client-go's C<getUserIdentificationPartialConfig> reads the file only when there is no inline token - and either of them wins over an C<exec> block, which C<kubectl> skips whenever a request already carries an C<Authorization> header. An C<exec> plugin is therefore not run at all when the user also has a token or a token file. | ||
| 533 | |||
| 534 | A C<tokenFile> that cannot be read, or that holds nothing but whitespace, is a fatal error naming the user and the file. It is deliberately not a fall-through to the next mechanism: a kubeconfig saying where its token lives is a statement about how this user authenticates, and quietly carrying on would produce a 401 from the cluster with nothing pointing at the file. Leading and trailing whitespace is stripped - such files almost always end in a newline, and a newline in an C<Authorization> header does not reach the server as intended. | ||
| 535 | |||
| 536 | A C<tokenFile> is handed to L<Kubernetes::REST> as a L<Kubernetes::REST::AuthTokenFile>, which reads the file again when it changes, so a rotated token is picked up without rebuilding the client. The in-cluster service account token works the same way. See L</TOKEN FILES AND ROTATION>, and L</refresh_token_files> to turn it off. | ||
| 537 | |||
| 538 | Falls back to in-cluster service account authentication when no kubeconfig | ||
| 539 | file is found - none of the merged paths exists, or there is no path at all | ||
| 540 | because neither C<KUBECONFIG> nor C<HOME> is set - and the pod has a mounted | ||
| 541 | token at | ||
| 542 | C</var/run/secrets/kubernetes.io/serviceaccount/token>. In that case the API | ||
| 543 | server address comes from the C<KUBERNETES_SERVICE_HOST>/C<KUBERNETES_SERVICE_PORT> | ||
| 544 | environment variables (defaulting to C<kubernetes.default.svc:443>), and the | ||
| 545 | cluster CA is read from C</var/run/secrets/kubernetes.io/serviceaccount/ca.crt>. | ||
| 546 | |||
| 547 | =head1 MERGING | ||
| 548 | |||
| 549 | C<KUBECONFIG> is a C<PATH>-style list of kubeconfig files, not a single path - | ||
| 550 | C<:>-separated everywhere except on Win32, where it is C<;>-separated, the same | ||
| 551 | separator Perl reports in C<$Config{path_sep}>. C<kubectl> merges every file in | ||
| 552 | that list into one configuration, and so does this module: | ||
| 553 | |||
| 554 | =over 4 | ||
| 555 | |||
| 556 | =item * Clusters, contexts and users are unioned by name. The B<first> file | ||
| 557 | that defines a given name wins; later definitions of that same name are | ||
| 558 | discarded, they do not overwrite fields. | ||
| 559 | |||
| 560 | =item * C<current-context> comes from the first file in the list that sets one, | ||
| 561 | as does every other top-level key (C<apiVersion>, C<kind>, C<preferences>). | ||
| 562 | |||
| 563 | =item * Entries that name a file that does not exist are skipped silently, | ||
| 564 | which is what C<kubectl> does - a list assembled by a shell profile or by | ||
| 565 | C<direnv> routinely mentions files that are not there. So are empty entries, so | ||
| 566 | C</a::/b> and a trailing C<:> are harmless. | ||
| 567 | |||
| 568 | =item * Relative entries in the list itself are resolved against the current | ||
| 569 | working directory. | ||
| 570 | |||
| 571 | =back | ||
| 572 | |||
| 573 | If no file in the list exists, the configuration is empty and L</api> falls | ||
| 574 | back to in-cluster authentication exactly as it does for a single missing file. | ||
| 575 | |||
| 576 | =head2 Relative paths inside a kubeconfig | ||
| 577 | |||
| 578 | The file references an entry holds - C<certificate-authority> on a cluster, | ||
| 579 | C<client-certificate>, C<client-key> and C<tokenFile> on a user - are resolved | ||
| 580 | against the directory of the kubeconfig file that defines that entry, the way | ||
| 581 | C<kubectl> resolves them, and not against the current working directory. | ||
| 582 | |||
| 583 | With several files merged that directory is a property of the entry, not of the | ||
| 584 | configuration: a cluster that won from F</a/config> resolves its CA against | ||
| 585 | F</a> even when the current context came from F</b/config>. Resolution | ||
| 586 | therefore happens as each file is read, before anything is merged, so what | ||
| 587 | L</cluster>, L</user> and L</api> hand back are absolute paths that keep | ||
| 588 | pointing at the same file after a C<chdir>. | ||
| 589 | |||
| 590 | An absolute reference is passed through untouched, and so is the inline base64 | ||
| 591 | of the C<*-data> fields, which names no file. A leading C<~> is not expanded - | ||
| 592 | it is an ordinary directory name, exactly as it is for C<kubectl>, and resolves | ||
| 593 | like any other relative path. An C<exec> plugin's C<command> is not a file | ||
| 594 | reference in this sense either: it is looked up in C<PATH> and is left alone. | ||
| 595 | |||
| 596 | =head1 TOKEN FILES AND ROTATION | ||
| 597 | |||
| 598 | Kubernetes rotates the files a token can come from. The kubelet replaces a | ||
| 599 | projected service account token well before it expires, and a client that read | ||
| 600 | the file once at startup would go on sending a token that has stopped being | ||
| 601 | valid while a good one sits in the file next to it. | ||
| 602 | |||
| 603 | A token that comes from a file - a user's C<tokenFile>, or the service account | ||
| 604 | token of the in-cluster fallback - is therefore not handed over as a fixed | ||
| 605 | string. L</api> builds a L<Kubernetes::REST::AuthTokenFile>, which reads the | ||
| 606 | file again whenever it has changed. There is no timer and no interval to | ||
| 607 | configure: the trigger is the file itself, and a client picks up a new token on | ||
| 608 | the first request after the rotation. | ||
| 609 | |||
| 610 | What "changed" means, and what it costs, is | ||
| 611 | L<Kubernetes::REST::AuthTokenFile/token>: one C<stat> per request, comparing | ||
| 612 | device, inode, size and modification time, so the C<..data> symlink swap the | ||
| 613 | kubelet performs is seen as the different file it is. A read that fails after a | ||
| 614 | successful one - the file gone for a moment mid-rotation - keeps the last good | ||
| 615 | token rather than breaking the client. Only the first read, when the client is | ||
| 616 | built, is fatal. | ||
| 617 | |||
| 618 | Set L</refresh_token_files> to false to switch this off. The token is then read | ||
| 619 | exactly once, when C<api()> builds the client, and never again: no C<stat> per | ||
| 620 | request, and the client stops working when that token expires, until something | ||
| 621 | builds it anew. | ||
| 622 | |||
| 623 | An inline C<token> in the kubeconfig is unaffected either way - there is no | ||
| 624 | file to watch, and it is used exactly as it is written. | ||
| 625 | |||
| 626 | =head1 SEE ALSO | ||
| 627 | |||
| 628 | =over | ||
| 629 | |||
| 630 | =item * L<Kubernetes::REST> - Main API client | ||
| 631 | |||
| 632 | =item * L<Kubernetes::REST::Server> - Server configuration | ||
| 633 | |||
| 634 | =item * L<Kubernetes::REST::AuthToken> - Authentication credentials | ||
| 635 | |||
| 636 | =back | ||
| 637 | |||
| 638 | =head1 SUPPORT | ||
| 639 | |||
| 640 | =head2 Issues | ||
| 641 | |||
| 642 | Please report bugs and feature requests on GitHub at | ||
| 643 | L<https://github.com/pplu/kubernetes-rest/issues>. | ||
| 644 | |||
| 645 | =head2 IRC | ||
| 646 | |||
| 647 | Join C<#kubernetes> on C<irc.perl.org> or message Getty directly. | ||
| 648 | |||
| 649 | =head1 CONTRIBUTING | ||
| 650 | |||
| 651 | Contributions are welcome! Please fork the repository and submit a pull request. | ||
| 652 | |||
| 653 | =head1 AUTHORS | ||
| 654 | |||
| 655 | =over 4 | ||
| 656 | |||
| 657 | =item * | ||
| 658 | |||
| 659 | Torsten Raudssus <getty@cpan.org> | ||
| 660 | |||
| 661 | =item * | ||
| 662 | |||
| 663 | Jose Luis Martinez Torres <jlmartin@cpan.org> | ||
| 664 | |||
| 665 | =back | ||
| 666 | |||
| 667 | =head1 COPYRIGHT AND LICENSE | ||
| 668 | |||
| 669 | This software is Copyright (c) 2019-2026 by Jose Luis Martinez Torres <jlmartin@cpan.org>. | ||
| 670 | |||
| 671 | This is free software, licensed under: | ||
| 672 | |||
| 673 | The Apache License, Version 2.0, January 2004 | ||
| 674 | |||
| 675 | =cut |