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

feat(eks): Allow helm pull from OCI repositories #18547

Merged
merged 13 commits into from Feb 24, 2022
18 changes: 18 additions & 0 deletions packages/@aws-cdk/aws-eks/README.md
Expand Up @@ -1144,6 +1144,24 @@ cluster.addHelmChart('test-chart', {
});
```

### OCI Charts

OCI charts are also supported. Before executing ensure the handler lambda has the required ECR IAM permissions.
Copy link
Contributor

Choose a reason for hiding this comment

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

What are the required permissions? Can we automate that for the user?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

They would be ecr repository permissions to be able to log in. Ideally, it
should be present on the lambda.

Copy link
Contributor

Choose a reason for hiding this comment

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

The handler role is this one:

this.handlerRole = handler.role!;

You will need to add the ecr:GetAuthorizationToken permission to it

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@otaviomacedo , Done. please review

Copy link
Contributor

Choose a reason for hiding this comment

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

Looks good. But the tests have to be updated now.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@otaviomacedo , When I am trying to run tests from aws-eks directory. It appears to be not picking up tests at all or giving other errors. Could you advise me on the correct steps to execute tests?

Copy link
Contributor

Choose a reason for hiding this comment

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

yarn build && yarn test should be the only thing you need. Another thing you can try is to build the whole transitive closure before running the test:

 aws-eks $ ../../../scripts/buildup

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@otaviomacedo , the tests are now complete. Could we please merge this ?

Copy link

Choose a reason for hiding this comment

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

@otaviomacedo , Could you please review?. Thanks

Also replace the `${VARS}` with appropriate values.

```ts
declare const cluster: eks.Cluster;
// option 1: use a construct
new eks.HelmChart(this, 'MyOCIChart', {
cluster,
chart: 'some-chart',
repository: 'oci://${ACCOUNT_ID}.dkr.ecr.${ACCOUNT_REGION}.amazonaws.com/${REPO_NAME}',
namespace: 'oci',
version: '0.0.1'
});

```

Helm charts are implemented as CloudFormation resources in CDK.
This means that if the chart is deleted from your code (or the stack is
deleted), the next `cdk deploy` will issue a `helm uninstall` command and the
Expand Down
63 changes: 62 additions & 1 deletion packages/@aws-cdk/aws-eks/lib/kubectl-handler/helm/__init__.py
@@ -1,8 +1,10 @@
import json
import logging
import os
import re
import subprocess
import shutil
import tempfile
import zipfile
from urllib.parse import urlparse, unquote

Expand Down Expand Up @@ -78,13 +80,71 @@ def helm_handler(event, context):
# future work: support versions from s3 assets
chart = get_chart_asset_from_url(chart_asset_url)

if repository.startswith('oci://'):
assert(repository is not None)
tmpdir = tempfile.TemporaryDirectory()
chart_dir = get_chart_from_oci(tmpdir.name, release, repository, version)
chart = chart_dir

helm('upgrade', release, chart, repository, values_file, namespace, version, wait, timeout, create_namespace)
elif request_type == "Delete":
try:
helm('uninstall', release, namespace=namespace, timeout=timeout)
except Exception as e:
logger.info("delete error: %s" % e)


def get_oci_cmd(repository, version):

cmnd = []
pattern = '\d+.dkr.ecr.[a-z]+-[a-z]+-\d.amazonaws.com'

registry = repository.rsplit('/', 1)[0].replace('oci://', '')

if re.fullmatch(pattern, registry) is not None:
region = registry.replace('.amazonaws.com', '').split('.')[-1]
cmnd = [
f"aws ecr get-login-password --region {region} | " \
f"helm registry login --username AWS --password-stdin {registry}; helm pull {repository} --version {version} --untar"
]
else:
logger.info("Non AWS OCI repository found")
cmnd = ['HELM_EXPERIMENTAL_OCI=1', 'helm', 'pull', repository, '--version', version, '--untar']

return cmnd


def get_chart_from_oci(tmpdir, release, repository = None, version = None):

cmnd = get_oci_cmd(repository, version)

maxAttempts = 3
retry = maxAttempts
while retry > 0:
try:
logger.info(cmnd)
env = get_env_with_oci_flag()
output = subprocess.check_output(cmnd, stderr=subprocess.STDOUT, cwd=tmpdir, env=env, shell=True)
logger.info(output)

return os.path.join(tmpdir, release)
except subprocess.CalledProcessError as exc:
output = exc.output
if b'Broken pipe' in output:
retry = retry - 1
logger.info("Broken pipe, retries left: %s" % retry)
else:
raise Exception(output)
raise Exception(f'Operation failed after {maxAttempts} attempts: {output}')


def get_env_with_oci_flag():
env = os.environ.copy()
env['HELM_EXPERIMENTAL_OCI'] = '1'

return env


def helm(verb, release, chart = None, repo = None, file = None, namespace = None, version = None, wait = False, timeout = None, create_namespace = None):
import subprocess

Expand Down Expand Up @@ -113,7 +173,8 @@ def helm(verb, release, chart = None, repo = None, file = None, namespace = None
retry = maxAttempts
while retry > 0:
try:
output = subprocess.check_output(cmnd, stderr=subprocess.STDOUT, cwd=outdir)
env = get_env_with_oci_flag()
output = subprocess.check_output(cmnd, stderr=subprocess.STDOUT, cwd=outdir, env=env)
logger.info(output)
return
except subprocess.CalledProcessError as exc:
Expand Down