Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deprecate Kubernetes client API version v1alpha1 #6476

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changes/next-release/enhancement-eksgettoken-91863.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"type": "enhancement",
"category": "eks get-token",
"description": "Add support for respecting API version found in KUBERNETES_EXEC_INFO environment variable"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"type": "enhancement",
"category": "eks update-kubeconfig",
"description": "Update default API version to v1beta1"
}
151 changes: 126 additions & 25 deletions awscli/customizations/eks/get_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import base64
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would also be great if we can get a changelog for this feature? You can use the scripts/new-change script to generate a changelog entry. For the type field, I'd recommend setting the type to enhancement and the category to eks get-token

import botocore
import json
import os
import sys

from datetime import datetime, timedelta
from botocore.signers import RequestSigner
Expand All @@ -26,6 +28,33 @@
AUTH_API_VERSION = "2011-06-15"
AUTH_SIGNING_VERSION = "v4"

ALPHA_API = "client.authentication.k8s.io/v1alpha1"
BETA_API = "client.authentication.k8s.io/v1beta1"
V1_API = "client.authentication.k8s.io/v1"

FULLY_SUPPORTED_API_VERSIONS = [
V1_API,
BETA_API,
]
DEPRECATED_API_VERSIONS = [
ALPHA_API,
]

ERROR_MSG_TPL = (
"{0} KUBERNETES_EXEC_INFO, defaulting to {1}. This is likely a "

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should it say "Error reading KUBERNETES_EXEC_INFO" instead of just "KUBERNETES_EXEC_INFO"

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will say Error parsing to start the sentence as the variable is being used as a template. Tests also confirm that too: https://github.com/aws/aws-cli/pull/6476/files#diff-ee0c03e30582b485e61dba3f70f956a6024118bdffe8657c476fee7f9ac655afR194.

"bug in your Kubernetes client. Please update your Kubernetes "
"client."
)
UNRECOGNIZED_MSG_TPL = (
"Unrecognized API version in KUBERNETES_EXEC_INFO, defaulting to "
"{0}. This is likely due to an outdated AWS "
"CLI. Please update your AWS CLI."
)
DEPRECATION_MSG_TPL = (
"Kubeconfig user entry is using deprecated API version {0}. Run "
"'aws eks update-kubeconfig' to update."
)

# Presigned url timeout in seconds
URL_TIMEOUT = 60

Expand All @@ -39,32 +68,40 @@
class GetTokenCommand(BasicCommand):
NAME = 'get-token'

DESCRIPTION = ("Get a token for authentication with an Amazon EKS cluster. "
"This can be used as an alternative to the "
"aws-iam-authenticator.")
DESCRIPTION = (
"Get a token for authentication with an Amazon EKS cluster. "
"This can be used as an alternative to the "
"aws-iam-authenticator."
)

ARG_TABLE = [
{
'name': 'cluster-name',
'help_text': ("Specify the name of the Amazon EKS cluster to create a token for."),
'required': True
'help_text': (
"Specify the name of the Amazon EKS cluster to create a token for."
),
'required': True,
},
{
'name': 'role-arn',
'help_text': ("Assume this role for credentials when signing the token."),
'required': False
}
'help_text': (
"Assume this role for credentials when signing the token."
),
'required': False,
},
]

def get_expiration_time(self):
token_expiration = datetime.utcnow() + timedelta(minutes=TOKEN_EXPIRATION_MINS)
token_expiration = datetime.utcnow() + timedelta(
minutes=TOKEN_EXPIRATION_MINS
)
return token_expiration.strftime('%Y-%m-%dT%H:%M:%SZ')

def _run_main(self, parsed_args, parsed_globals):
client_factory = STSClientFactory(self._session)
sts_client = client_factory.get_sts_client(
region_name=parsed_globals.region,
role_arn=parsed_args.role_arn)
region_name=parsed_globals.region, role_arn=parsed_args.role_arn
)
token = TokenGenerator(sts_client).get_token(parsed_args.cluster_name)

# By default STS signs the url for 15 minutes so we are creating a
Expand All @@ -74,28 +111,94 @@ def _run_main(self, parsed_args, parsed_globals):

full_object = {
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"apiVersion": self.discover_api_version(),
"spec": {},
"status": {
"expirationTimestamp": token_expiration,
"token": token
}
"token": token,
},
}

uni_print(json.dumps(full_object))
uni_print('\n')
return 0

def discover_api_version(self):
"""
Parses the KUBERNETES_EXEC_INFO environment variable and returns the
API version. If the environment variable is empty, malformed, or
invalid, return the v1alpha1 response and print a message to stderr.

If the v1alpha1 API is specified explicitly, a message is printed to
stderr with instructions to update.

:return: The client authentication API version
:rtype: string
"""
# At the time Kubernetes v1.29 is released upstream (approx Dec 2023),
# "v1beta1" will be removed. At or around that time, EKS will likely
# support v1.22 through v1.28, in which client API version "v1beta1"
# will be supported by all EKS versions.
fallback_api_version = ALPHA_API

error_prefixes = {
"error": "Error parsing",
"empty": "Empty",
}

exec_info_raw = os.environ.get("KUBERNETES_EXEC_INFO", "")
if not exec_info_raw:
# All kube clients should be setting this. Otherewise, we'll return
# the fallback and write an error.
uni_print(
ERROR_MSG_TPL.format(
error_prefixes["empty"],
fallback_api_version,
),
sys.stderr,
)
uni_print("\n", sys.stderr)
return fallback_api_version
try:
exec_info = json.loads(exec_info_raw)
except json.JSONDecodeError:
# The environment variable was malformed
uni_print(
ERROR_MSG_TPL.format(
error_prefixes["error"],
fallback_api_version,
),
sys.stderr,
)
uni_print("\n", sys.stderr)
return fallback_api_version

api_version_raw = exec_info.get("apiVersion")
if api_version_raw in FULLY_SUPPORTED_API_VERSIONS:
return api_version_raw
elif api_version_raw in DEPRECATED_API_VERSIONS:
uni_print(DEPRECATION_MSG_TPL.format(ALPHA_API), sys.stderr)
uni_print("\n", sys.stderr)
return api_version_raw
else:
uni_print(
UNRECOGNIZED_MSG_TPL.format(fallback_api_version),
sys.stderr,
)
uni_print("\n", sys.stderr)
return fallback_api_version


class TokenGenerator(object):
def __init__(self, sts_client):
self._sts_client = sts_client

def get_token(self, cluster_name):
""" Generate a presigned url token to pass to kubectl. """
"""Generate a presigned url token to pass to kubectl."""
url = self._get_presigned_url(cluster_name)
token = TOKEN_PREFIX + base64.urlsafe_b64encode(
url.encode('utf-8')).decode('utf-8').rstrip('=')
url.encode('utf-8')
).decode('utf-8').rstrip('=')
return token

def _get_presigned_url(self, cluster_name):
Expand All @@ -112,9 +215,7 @@ def __init__(self, session):
self._session = session

def get_sts_client(self, region_name=None, role_arn=None):
client_kwargs = {
'region_name': region_name
}
client_kwargs = {'region_name': region_name}
if role_arn is not None:
creds = self._get_role_credentials(region_name, role_arn)
client_kwargs['aws_access_key_id'] = creds['AccessKeyId']
Expand All @@ -127,18 +228,17 @@ def get_sts_client(self, region_name=None, role_arn=None):
def _get_role_credentials(self, region_name, role_arn):
sts = self._session.create_client('sts', region_name)
return sts.assume_role(
RoleArn=role_arn,
RoleSessionName='EKSGetTokenAuth'
RoleArn=role_arn, RoleSessionName='EKSGetTokenAuth'
)['Credentials']

def _register_cluster_name_handlers(self, sts_client):
sts_client.meta.events.register(
'provide-client-params.sts.GetCallerIdentity',
self._retrieve_cluster_name
self._retrieve_cluster_name,
)
sts_client.meta.events.register(
'before-sign.sts.GetCallerIdentity',
self._inject_cluster_name_header
self._inject_cluster_name_header,
)

def _retrieve_cluster_name(self, params, context, **kwargs):
Expand All @@ -147,5 +247,6 @@ def _retrieve_cluster_name(self, params, context, **kwargs):

def _inject_cluster_name_header(self, request, **kwargs):
if 'eks_cluster' in request.context:
request.headers[
CLUSTER_NAME_HEADER] = request.context['eks_cluster']
request.headers[CLUSTER_NAME_HEADER] = request.context[
'eks_cluster'
]
9 changes: 4 additions & 5 deletions awscli/customizations/eks/update_kubeconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,9 @@

DEFAULT_PATH = os.path.expanduser("~/.kube/config")

# Use the endpoint for kubernetes 1.10
# To get the most recent endpoint we will need to
# Do a check on the cluster's version number
API_VERSION = "client.authentication.k8s.io/v1alpha1"
# At the time EKS no longer supports Kubernetes v1.21 (probably ~Dec 2023),
# this can be safely changed to default to writing "v1"
API_VERSION = "client.authentication.k8s.io/v1beta1"

class UpdateKubeconfigCommand(BasicCommand):
NAME = 'update-kubeconfig'
Expand Down Expand Up @@ -306,7 +305,7 @@ def get_user_entry(self):
"--cluster-name",
self._cluster_name,
]),
("command", "aws")
("command", "aws"),
]))
]))
])
Expand Down
2 changes: 1 addition & 1 deletion awscli/examples/eks/get-token.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Output::

{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"apiVersion": "client.authentication.k8s.io/v1beta1",
"spec": {},
"status": {
"expirationTimestamp": "2019-08-14T18:44:27Z",
Expand Down
Loading