This is an automated email from the ASF dual-hosted git repository.
potiuk pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 8a1437e Refresh credentials for long-running pods on EKS (#17951)
8a1437e is described below
commit 8a1437e55ed50bcb9301c55c1217e9e66532f6ed
Author: Kamil BreguĊa <[email protected]>
AuthorDate: Wed Sep 29 22:25:53 2021 +0200
Refresh credentials for long-running pods on EKS (#17951)
---
.../aws/example_dags/example_eks_using_defaults.py | 7 +-
airflow/providers/amazon/aws/hooks/eks.py | 39 ++++++++--
.../providers/amazon/aws/utils/eks_get_token.py | 69 +++++++++++++++++
tests/providers/amazon/aws/hooks/test_eks.py | 90 ++++++++++++++++++++--
.../amazon/aws/utils/test_eks_get_token.py | 85 ++++++++++++++++++++
5 files changed, 273 insertions(+), 17 deletions(-)
diff --git
a/airflow/providers/amazon/aws/example_dags/example_eks_using_defaults.py
b/airflow/providers/amazon/aws/example_dags/example_eks_using_defaults.py
index 12a80fb..0f7d08c 100644
--- a/airflow/providers/amazon/aws/example_dags/example_eks_using_defaults.py
+++ b/airflow/providers/amazon/aws/example_dags/example_eks_using_defaults.py
@@ -26,9 +26,8 @@ from airflow.providers.amazon.aws.operators.eks import (
from airflow.providers.amazon.aws.sensors.eks import EKSClusterStateSensor,
EKSNodegroupStateSensor
from airflow.utils.dates import days_ago
-CLUSTER_NAME = 'eks-demo'
-NODEGROUP_SUFFIX = '-nodegroup'
-NODEGROUP_NAME = CLUSTER_NAME + NODEGROUP_SUFFIX
+CLUSTER_NAME = environ.get('EKS_CLUSTER_NAME', 'eks-demo')
+NODEGROUP_NAME = f'{CLUSTER_NAME}-nodegroup'
ROLE_ARN = environ.get('EKS_DEMO_ROLE_ARN',
'arn:aws:iam::123456789012:role/role_name')
SUBNETS = environ.get('EKS_DEMO_SUBNETS', 'subnet-12345ab
subnet-67890cd').split(' ')
VPC_CONFIG = {
@@ -74,7 +73,7 @@ with DAG(
pod_name="run_pod",
cluster_name=CLUSTER_NAME,
image="amazon/aws-cli:latest",
- cmds=["sh", "-c", "ls"],
+ cmds=["sh", "-c", "echo Test Airflow; date"],
labels={"demo": "hello_world"},
get_logs=True,
# Delete the pod when it reaches its final state, or the execution is
interrupted.
diff --git a/airflow/providers/amazon/aws/hooks/eks.py
b/airflow/providers/amazon/aws/hooks/eks.py
index 9559ca2..cf6ad3e 100644
--- a/airflow/providers/amazon/aws/hooks/eks.py
+++ b/airflow/providers/amazon/aws/hooks/eks.py
@@ -18,7 +18,7 @@
"""Interact with Amazon EKS, using the boto3 library."""
import base64
import json
-import re
+import sys
import tempfile
import warnings
from contextlib import contextmanager
@@ -35,6 +35,7 @@ from airflow.utils.json import AirflowJsonEncoder
DEFAULT_PAGINATION_TOKEN = ''
STS_TOKEN_EXPIRES_IN = 60
+AUTHENTICATION_API_VERSION = "client.authentication.k8s.io/v1alpha1"
_POD_USERNAME = 'aws'
_CONTEXT_NAME = 'aws'
@@ -385,8 +386,6 @@ class EKSHook(AwsBaseHook):
cluster_cert = cluster["cluster"]["certificateAuthority"]["data"]
cluster_ep = cluster["cluster"]["endpoint"]
- token = self._fetch_sts_token(cluster_id=eks_cluster_name)
-
cluster_config = {
"apiVersion": "v1",
"kind": "Config",
@@ -412,7 +411,33 @@ class EKSHook(AwsBaseHook):
{
"name": _POD_USERNAME,
"user": {
- "token": token,
+ "exec": {
+ "apiVersion": AUTHENTICATION_API_VERSION,
+ "command": sys.executable,
+ "args": [
+ "-m",
+
"airflow.providers.amazon.aws.utils.eks_get_token",
+ *(
+ ["--region-name", self.region_name]
+ if self.region_name is not None
+ else []
+ ),
+ *(
+ ["--aws-conn-id", self.aws_conn_id]
+ if self.aws_conn_id is not None
+ else []
+ ),
+ "--cluster-name",
+ eks_cluster_name,
+ ],
+ "env": [
+ {
+ "name": "AIRFLOW__LOGGING__LOGGING_LEVEL",
+ "value": "fatal",
+ }
+ ],
+ "interactiveMode": "Never",
+ }
},
}
],
@@ -424,7 +449,7 @@ class EKSHook(AwsBaseHook):
config_file.flush()
yield config_file.name
- def _fetch_sts_token(self, cluster_id: str) -> str:
+ def fetch_access_token_for_cluster(self, eks_cluster_name: str) -> str:
session = self.get_session()
service_id = self.conn.meta.service_model.service_id
sts_url = (
@@ -444,7 +469,7 @@ class EKSHook(AwsBaseHook):
'method': 'GET',
'url': sts_url,
'body': {},
- 'headers': {'x-k8s-aws-id': cluster_id},
+ 'headers': {'x-k8s-aws-id': eks_cluster_name},
'context': {},
}
@@ -458,4 +483,4 @@ class EKSHook(AwsBaseHook):
base64_url =
base64.urlsafe_b64encode(signed_url.encode('utf-8')).decode('utf-8')
# remove any base64 encoding padding:
- return 'k8s-aws-v1.' + re.sub(r'=*', '', base64_url)
+ return 'k8s-aws-v1.' + base64_url.rstrip("=")
diff --git a/airflow/providers/amazon/aws/utils/eks_get_token.py
b/airflow/providers/amazon/aws/utils/eks_get_token.py
new file mode 100644
index 0000000..00baef6
--- /dev/null
+++ b/airflow/providers/amazon/aws/utils/eks_get_token.py
@@ -0,0 +1,69 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import argparse
+import json
+from datetime import datetime, timedelta
+
+from airflow.providers.amazon.aws.hooks.eks import EKSHook
+
+# Presigned STS urls are valid for 15 minutes, set token expiration to 1
minute before it expires for
+# some cushion
+TOKEN_EXPIRATION_MINUTES = 14
+
+
+def get_expiration_time():
+ token_expiration = datetime.utcnow() +
timedelta(minutes=TOKEN_EXPIRATION_MINUTES)
+ return token_expiration.strftime('%Y-%m-%dT%H:%M:%SZ')
+
+
+def get_parser():
+ parser = argparse.ArgumentParser(description='Get a token for
authentication with an Amazon EKS cluster.')
+ parser.add_argument(
+ '--cluster-name', help='The name of the cluster to generate kubeconfig
file for.', required=True
+ )
+ parser.add_argument(
+ '--aws-conn-id',
+ help=(
+ 'The Airflow connection used for AWS credentials. '
+ 'If not specified or empty then the default boto3 behaviour is
used.'
+ ),
+ )
+ parser.add_argument(
+ '--region-name', help='AWS region_name. If not specified then the
default boto3 behaviour is used.'
+ )
+
+ return parser
+
+
+def main():
+ parser = get_parser()
+ args = parser.parse_args()
+ eks_hook = EKSHook(aws_conn_id=args.aws_conn_id,
region_name=args.region_name)
+ access_token = eks_hook.fetch_access_token_for_cluster(args.cluster_name)
+ access_token_expiration = get_expiration_time()
+ exec_credential_object = {
+ "kind": "ExecCredential",
+ "apiVersion": "client.authentication.k8s.io/v1alpha1",
+ "spec": {},
+ "status": {"expirationTimestamp": access_token_expiration, "token":
access_token},
+ }
+ print(json.dumps(exec_credential_object))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tests/providers/amazon/aws/hooks/test_eks.py
b/tests/providers/amazon/aws/hooks/test_eks.py
index cb5de11..3019d9d 100644
--- a/tests/providers/amazon/aws/hooks/test_eks.py
+++ b/tests/providers/amazon/aws/hooks/test_eks.py
@@ -16,6 +16,7 @@
# specific language governing permissions and limitations
# under the License.
#
+import sys
from copy import deepcopy
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Type
@@ -714,18 +715,52 @@ class TestEKSHooks:
class TestEKSHook:
-
@mock.patch('airflow.providers.amazon.aws.hooks.eks.EKSHook._fetch_sts_token')
@mock.patch('airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook.conn')
- def test_generate_config_file(self, mock_conn, mock_fetch_sts_token):
- mock_fetch_sts_token.return_value = 'STS-token'
+ @pytest.mark.parametrize(
+ "aws_conn_id, region_name, expected_args",
+ [
+ [
+ 'test-id',
+ 'test-region',
+ [
+ '-m',
+ 'airflow.providers.amazon.aws.utils.eks_get_token',
+ '--region-name',
+ 'test-region',
+ '--aws-conn-id',
+ 'test-id',
+ '--cluster-name',
+ 'test-cluster',
+ ],
+ ],
+ [
+ None,
+ 'test-region',
+ [
+ '-m',
+ 'airflow.providers.amazon.aws.utils.eks_get_token',
+ '--region-name',
+ 'test-region',
+ '--cluster-name',
+ 'test-cluster',
+ ],
+ ],
+ [
+ None,
+ None,
+ ['-m', 'airflow.providers.amazon.aws.utils.eks_get_token',
'--cluster-name', 'test-cluster'],
+ ],
+ ],
+ )
+ def test_generate_config_file(self, mock_conn, aws_conn_id, region_name,
expected_args):
mock_conn.describe_cluster.return_value = {
'cluster': {'certificateAuthority': {'data': 'test-cert'},
'endpoint': 'test-endpoint'}
}
- hook = EKSHook()
+ hook = EKSHook(aws_conn_id=aws_conn_id, region_name=region_name)
with hook.generate_config_file(
eks_cluster_name='test-cluster', pod_namespace='k8s-namespace'
) as config_file:
- config = yaml.load(Path(config_file).read_text())
+ config = yaml.safe_load(Path(config_file).read_text())
assert config == {
'apiVersion': 'v1',
'kind': 'Config',
@@ -743,9 +778,52 @@ class TestEKSHook:
],
'current-context': 'aws',
'preferences': {},
- 'users': [{'name': 'aws', 'user': {'token': 'STS-token'}}],
+ 'users': [
+ {
+ 'name': 'aws',
+ 'user': {
+ 'exec': {
+ 'apiVersion':
'client.authentication.k8s.io/v1alpha1',
+ 'args': expected_args,
+ 'command': sys.executable,
+ 'env': [{'name':
'AIRFLOW__LOGGING__LOGGING_LEVEL', 'value': 'fatal'}],
+ 'interactiveMode': 'Never',
+ }
+ },
+ }
+ ],
}
+ @mock.patch('airflow.providers.amazon.aws.hooks.eks.RequestSigner')
+ @mock.patch('airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook.conn')
+
@mock.patch('airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook.get_session')
+ def test_fetch_access_token_for_cluster(self, mock_get_session, mock_conn,
mock_signer):
+ mock_signer.return_value.generate_presigned_url.return_value =
'http://example.com'
+ mock_get_session.return_value.region_name = 'us-east-1'
+ hook = EKSHook()
+ token =
hook.fetch_access_token_for_cluster(eks_cluster_name='test-cluster')
+ mock_signer.assert_called_once_with(
+ service_id=mock_conn.meta.service_model.service_id,
+ region_name='us-east-1',
+ signing_name='sts',
+ signature_version='v4',
+
credentials=mock_get_session.return_value.get_credentials.return_value,
+ event_emitter=mock_get_session.return_value.events,
+ )
+
mock_signer.return_value.generate_presigned_url.assert_called_once_with(
+ request_dict={
+ 'method': 'GET',
+ 'url':
'https://sts.us-east-1.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15',
+ 'body': {},
+ 'headers': {'x-k8s-aws-id': 'test-cluster'},
+ 'context': {},
+ },
+ region_name='us-east-1',
+ expires_in=60,
+ operation_name='',
+ )
+ assert token == 'k8s-aws-v1.aHR0cDovL2V4YW1wbGUuY29t'
+
# Helper methods for repeated assert combinations.
def assert_all_arn_values_are_valid(expected_arn_values, pattern,
arn_under_test) -> None:
diff --git a/tests/providers/amazon/aws/utils/test_eks_get_token.py
b/tests/providers/amazon/aws/utils/test_eks_get_token.py
new file mode 100644
index 0000000..a1f2a8a
--- /dev/null
+++ b/tests/providers/amazon/aws/utils/test_eks_get_token.py
@@ -0,0 +1,85 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import contextlib
+import io
+import json
+import runpy
+from unittest import mock
+
+import pytest
+from freezegun import freeze_time
+
+
+class TestGetEksTtoken:
+ @mock.patch('airflow.providers.amazon.aws.hooks.eks.EKSHook')
+ @freeze_time("1995-02-14")
+ @pytest.mark.parametrize(
+ "args, expected_aws_conn_id, expected_region_name",
+ [
+ [
+ [
+ 'airflow.providers.amazon.aws.utils.eks_get_token',
+ '--region-name',
+ 'test-region',
+ '--aws-conn-id',
+ 'test-id',
+ '--cluster-name',
+ 'test-cluster',
+ ],
+ 'test-id',
+ 'test-region',
+ ],
+ [
+ [
+ 'airflow.providers.amazon.aws.utils.eks_get_token',
+ '--region-name',
+ 'test-region',
+ '--cluster-name',
+ 'test-cluster',
+ ],
+ None,
+ 'test-region',
+ ],
+ [
+ ['airflow.providers.amazon.aws.utils.eks_get_token',
'--cluster-name', 'test-cluster'],
+ None,
+ None,
+ ],
+ ],
+ )
+ def test_run(self, mock_eks_hook, args, expected_aws_conn_id,
expected_region_name):
+ (
+
mock_eks_hook.return_value.fetch_access_token_for_cluster.return_value
+ ) = 'k8s-aws-v1.aHR0cDovL2V4YW1wbGUuY29t'
+
+ with mock.patch('sys.argv', args),
contextlib.redirect_stdout(io.StringIO()) as temp_stdout:
+
runpy.run_module('airflow.providers.amazon.aws.utils.eks_get_token',
run_name='__main__')
+
+ assert {
+ 'apiVersion': 'client.authentication.k8s.io/v1alpha1',
+ 'kind': 'ExecCredential',
+ 'spec': {},
+ 'status': {
+ 'expirationTimestamp': '1995-02-14T00:14:00Z',
+ 'token': 'k8s-aws-v1.aHR0cDovL2V4YW1wbGUuY29t',
+ },
+ } == json.loads(temp_stdout.getvalue())
+ mock_eks_hook.assert_called_once_with(
+ aws_conn_id=expected_aws_conn_id, region_name=expected_region_name
+ )
+
mock_eks_hook.return_value.fetch_access_token_for_cluster.assert_called_once_with('test-cluster')