Skip to content
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
7 changes: 5 additions & 2 deletions leverage/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class AwsCredsEntryPoint(CustomEntryPoint):
This works as a replacement of _prepare_container.
"""

def __init__(self, container):
def __init__(self, container, override_entrypoint=None):
if container.sso_enabled:
container._check_sso_token()
auth_method = f"{container.TF_SSO_ENTRYPOINT} -- "
Expand All @@ -102,7 +102,8 @@ def __init__(self, container):
else:
auth_method = ""

super(AwsCredsEntryPoint, self).__init__(container, entrypoint=auth_method)
new_entrypoint = f"{auth_method}{container.entrypoint if override_entrypoint is None else override_entrypoint}"
super(AwsCredsEntryPoint, self).__init__(container, entrypoint=new_entrypoint)

def __exit__(self, *args, **kwargs):
super(AwsCredsEntryPoint, self).__exit__(*args, **kwargs)
Expand All @@ -115,6 +116,8 @@ def __exit__(self, *args, **kwargs):
"AWS_CONFIG_FILE": self.container.environment["AWS_CONFIG_FILE"].replace(".aws", "tmp"),
}
)
# now return file ownership on the aws credentials files
self.container.change_file_ownership(self.container.guest_aws_credentials_dir)


class ExitError(Exit):
Expand Down
117 changes: 52 additions & 65 deletions leverage/container.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
import os
import pwd
import re
import webbrowser
from pathlib import Path
Expand All @@ -12,10 +13,11 @@
from docker import DockerClient
from docker.errors import APIError, NotFound
from docker.types import Mount
from typing import Tuple, Union, List

from leverage import __toolbox_version__
from leverage import logger
from leverage._utils import CustomEntryPoint, ExitError, ContainerSession
from leverage._utils import AwsCredsEntryPoint, CustomEntryPoint, ExitError, ContainerSession
from leverage.logger import console, raw_logger
from leverage.logger import get_script_log_level
from leverage.path import get_root_path
Expand Down Expand Up @@ -74,6 +76,8 @@ class LeverageContainer:
ACCOUNT_TFVARS = "account.tfvars"
BACKEND_TFVARS = "backend.tfvars"

SHELL = "/bin/bash"

def __init__(self, client):
"""Project related paths are determined and stored. Project configuration is loaded.

Expand Down Expand Up @@ -281,11 +285,11 @@ def _run(self, container, run_func):
self.client.api.stop(container)
self.client.api.remove_container(container)

def _start(self, command="/bin/sh", *args):
def _start(self, command: str, *args):
"""Create an interactive container, and run command with the given arguments.

Args:
command (str, optional): Command to run. Defaults to "/bin/sh".
command: Command to run.

Returns:
int: Execution exit code.
Expand All @@ -298,7 +302,7 @@ def run_func(client, container):

return self._run(container, run_func)

def _start_with_output(self, command="/bin/bash", *args):
def _start_with_output(self, command, *args):
"""
Same than _start but also returns the outputs (by dumping the logs) of the container.
"""
Expand All @@ -312,25 +316,15 @@ def run_func(client, container):

return self._run(container, run_func)

def start(self, command="/bin/sh", *arguments):
def start(self, command: str, *arguments) -> int:
"""Run command with the given arguments in an interactive container.

Args:
command (str, optional): Command. Defaults to "/bin/sh".

Returns:
int: Execution exit code.
Returns execution exit code.
"""
return self._start(command, *arguments)

def _exec(self, command="", *args):
def _exec(self, command: str, *args) -> Tuple[int, str]:
"""Create a non interactive container and execute command with the given arguments.

Args:
command (str, optional): Command. Defaults to "".

Returns:
int, str: Execution exit code and output.
Returns execution exit code and output.
"""
container = self._create_container(False, command, *args)

Expand All @@ -342,14 +336,9 @@ def run_func(client, container):

return self._run(container, run_func)

def exec(self, command="", *arguments):
def exec(self, command: str, *arguments) -> Tuple[int, str]:
"""Execute command with the given arguments in a container.

Args:
command (str, optional): Command. Defaults to "".

Returns:
int, str: Execution exit code and output/
Returns execution exit code and output.
"""
return self._exec(command, *arguments)

Expand Down Expand Up @@ -379,6 +368,22 @@ def get_location_type(self):
else:
return "not a project"

def change_ownership_cmd(self, path: Union[Path, str], recursive=True) -> str:
recursive = "-R " if recursive else ""
user_id = os.getuid()
group_id = os.getgid()

return f"chown {user_id}:{group_id} {recursive}{path}"

def change_file_ownership(self, path: Union[Path, str], recursive=True):
"""
Change the file/folder ownership from the internal docker user (usually root)
to the user executing the CLI.
"""
cmd = self.change_ownership_cmd(path, recursive=recursive)
with CustomEntryPoint(self, entrypoint=""):
self._exec(cmd)


class AWSCLIContainer(LeverageContainer):
"""Leverage Container specially tailored to run AWS CLI commands."""
Expand Down Expand Up @@ -420,6 +425,7 @@ def start(self, command, profile=""):
args = [] if not profile else ["--profile", profile]
return self._start(command, *args)

# FIXME: we have a context manager for this now, remove this method later!
def system_start(self, command):
"""Momentarily override the container's default entrypoint. To run arbitrary commands and not only AWS CLI ones."""
self.entrypoint = ""
Expand All @@ -431,6 +437,7 @@ def exec(self, command, profile=""):
args = [] if not profile else ["--profile", profile]
return self._exec(command, *args)

# FIXME: we have a context manager for this now, remove this method later!
def system_exec(self, command):
"""Momentarily override the container's default entrypoint. To run arbitrary commands and not only AWS CLI ones."""
self.entrypoint = ""
Expand Down Expand Up @@ -480,6 +487,8 @@ def sso_login(self) -> int:
# once submitted to the browser, the authentication finish and the lock is released
exit_code = self.client.api.wait(container)["StatusCode"]
raw_logger.info(self.docker_logs(container))
# now return ownership of the token file back to the user
self.change_file_ownership(self.guest_aws_credentials_dir)

return exit_code

Expand Down Expand Up @@ -530,21 +539,25 @@ def __init__(self, client):
Mount(source=(self.home / ".gitconfig").as_posix(), target="/etc/gitconfig", type="bind"),
]
# if you have set the tf plugin cache locally
if tf_cache_dir := os.getenv("TF_PLUGIN_CACHE_DIR"):
if self.tf_cache_dir:
# then mount it too into the container
self.environment["TF_PLUGIN_CACHE_DIR"] = tf_cache_dir
self.environment["TF_PLUGIN_CACHE_DIR"] = self.tf_cache_dir
# given that terraform use symlinks to point from the .terraform folder into the plugin folder
# we need to use the same directory inside the container
# otherwise symlinks will be broken once outside the container
# which will break terraform usage outside Leverage
self.mounts.append(Mount(source=tf_cache_dir, target=tf_cache_dir, type="bind"))
self.mounts.append(Mount(source=self.tf_cache_dir, target=self.tf_cache_dir, type="bind"))
if SSH_AUTH_SOCK is not None:
self.mounts.append(Mount(source=SSH_AUTH_SOCK, target="/ssh-agent", type="bind"))

self._backend_key = None

logger.debug(f"[bold cyan]Container configuration:[/bold cyan]\n{json.dumps(self.container_config, indent=2)}")

@property
def tf_cache_dir(self):
return os.getenv("TF_PLUGIN_CACHE_DIR")

def _guest_config_file(self, file):
"""Map config file in host to location in guest.

Expand Down Expand Up @@ -631,28 +644,6 @@ def _check_sso_token(self):

self.entrypoint = entrypoint

def _prepare_container(self):
"""Adjust entrypoint and environment variables for when SSO or MFA are used.
Note that SSO takes precedence over MFA when both are active."""
if self.sso_enabled:
self._check_sso_token()

self.entrypoint = f"{self.TF_SSO_ENTRYPOINT} -- {self.entrypoint}"

elif self.mfa_enabled:
self.entrypoint = f"{self.TF_MFA_ENTRYPOINT} -- {self.entrypoint}"

self.environment.update(
{
"AWS_SHARED_CREDENTIALS_FILE": self.environment.get("AWS_SHARED_CREDENTIALS_FILE").replace(
"tmp", ".aws"
),
"AWS_CONFIG_FILE": self.environment.get("AWS_CONFIG_FILE").replace("tmp", ".aws"),
}
)

logger.debug(f"[bold cyan]Running with entrypoint:[/bold cyan] {self.entrypoint}")

def check_for_layer_location(self):
"""Make sure the command is being ran at layer level. If not, bail."""
if self.cwd in (self.common_config_dir, self.account_config_dir):
Expand All @@ -671,9 +662,8 @@ def check_for_layer_location(self):
raise Exit(1)

def start(self, command, *arguments):
self._prepare_container()

return self._start(command, *arguments)
with AwsCredsEntryPoint(self, self.entrypoint):
return self._start(command, *arguments)

def start_in_layer(self, command, *arguments):
"""Run a command that can only be performed in layer level."""
Expand All @@ -682,10 +672,10 @@ def start_in_layer(self, command, *arguments):
return self.start(command, *arguments)

def exec(self, command, *arguments):
self._prepare_container()

return self._exec(command, *arguments)
with AwsCredsEntryPoint(self):
return self._exec(command, *arguments)

# FIXME: we have a context manager for this now, remove this method later!
def system_exec(self, command):
"""Momentarily override the container's default entrypoint. To run arbitrary commands and not only AWS CLI ones."""
original_entrypoint = self.entrypoint
Expand All @@ -700,9 +690,8 @@ def start_shell(self):
if self.mfa_enabled or self.sso_enabled:
self.check_for_layer_location()

self.entrypoint = ""
self._prepare_container()
self._start()
with AwsCredsEntryPoint(self, override_entrypoint=""):
self._start(self.SHELL)

def set_backend_key(self, skip_validation=False):
# Scenarios:
Expand Down Expand Up @@ -774,9 +763,8 @@ def __init__(self, client):
logger.debug(f"[bold cyan]Container configuration:[/bold cyan]\n{json.dumps(self.container_config, indent=2)}")

def start(self, *arguments):
self._prepare_container()

return self._start("", *arguments)
with AwsCredsEntryPoint(self):
return self._start("", *arguments)

def start_in_layer(self, *arguments):
"""Run a command that can only be performed in layer level."""
Expand All @@ -785,6 +773,5 @@ def start_in_layer(self, *arguments):
return self.start(*arguments)

def exec(self, command, *arguments):
self._prepare_container()

return self._exec(command, *arguments)
with AwsCredsEntryPoint(self):
return self._exec(command, *arguments)
24 changes: 6 additions & 18 deletions leverage/containers/kubectl.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import os
import pwd
from pathlib import Path

from click.exceptions import Exit
Expand Down Expand Up @@ -37,48 +35,38 @@ def __init__(self, client):
)

def start_shell(self):
with AwsCredsEntryPoint(self):
self._start("/bin/bash")
with AwsCredsEntryPoint(self, override_entrypoint=""):
self._start(self.SHELL)

def configure(self):
# make sure we are on the cluster layer
self.check_for_layer_location()

logger.info("Retrieving k8s cluster information...")
# generate the command that will configure the new cluster
with AwsCredsEntryPoint(self):
with AwsCredsEntryPoint(self, override_entrypoint=""):
add_eks_cluster_cmd = self._get_eks_kube_config()
# and the command that will set the proper ownership on the config file (otherwise the owner will be "root")
change_owner_cmd = self._change_kube_file_owner_cmd()
change_owner_cmd = self.change_ownership_cmd(self.KUBECTL_CONFIG_FILE, recursive=False)
full_cmd = chain_commands([add_eks_cluster_cmd, change_owner_cmd])

logger.info("Configuring context...")
with AwsCredsEntryPoint(self):
with AwsCredsEntryPoint(self, override_entrypoint=""):
exit_code = self._start(full_cmd)
if exit_code:
raise Exit(exit_code)

logger.info("Done.")

def _get_eks_kube_config(self) -> str:
exit_code, output = self._start_with_output(f"{self.TF_BINARY} output -no-color")
exit_code, output = self._start_with_output(f"{self.TF_BINARY} output -no-color") # TODO: override on CM?
if exit_code:
logger.error(output)
raise Exit(exit_code)

aws_eks_cmd = next(op for op in output.split("\r\n") if op.startswith("aws eks update-kubeconfig"))
return aws_eks_cmd + f" --region {self.region}"

def _get_user_group_id(self, user_id) -> int:
user = pwd.getpwuid(user_id)
return user.pw_gid

def _change_kube_file_owner_cmd(self) -> str:
user_id = os.getuid()
group_id = self._get_user_group_id(user_id)

return f"chown {user_id}:{group_id} {self.KUBECTL_CONFIG_FILE}"

def check_for_layer_location(self):
super(KubeCtlContainer, self).check_for_layer_location()
# assuming the "cluster" layer will contain the expected EKS outputs
Expand Down
2 changes: 0 additions & 2 deletions leverage/modules/aws.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import webbrowser

import click
from click.exceptions import Exit

Expand Down
Loading