def confhello(): values = conf.load() use_verbose_hello = values.get("USE_VERBOSE_HELLO", "true").lower() == "true" if use_verbose_hello: print("This is a way too long hello for anyone to say") else: print("Hello")
def test_load_config(monkeypatch, click_context, tmp_path, write_files, expected_values): with click_context(): root_dir = tmp_path account_dir = tmp_path / "account" account_dir.mkdir() monkeypatch.setattr("leverage.conf.get_root_path", lambda: root_dir.as_posix()) monkeypatch.setattr("leverage.conf.get_working_path", lambda: account_dir.as_posix()) if write_files: (root_dir / "build.env").write_text(ROOT_ENV_FILE) (account_dir / "build.env").write_text(ACC_ENV_FILE) loaded_values = load() assert dict(loaded_values) == expected_values
def config(): '''Show config''' print(conf.load())
import subprocess import os from leverage import path from leverage import conf # Get build config variables env = conf.load() # Set project name project = env.get("PROJECT", "") if project == "": raise Exception("Project is not set") # Enable MFA support? mfa_enabled = True if env.get("MFA_ENABLED", "true").lower() == "true" else False # Use TTY use_tty = True if env.get("USE_TTY", "false").lower() == "true" else False # Set default entrypoint, use the mfa entrypoint if mfa is enabled docker_entrypoint = env.get("TERRAFORM_ENTRYPOINT", "/bin/terraform") if mfa_enabled: docker_entrypoint = env.get("TERRAFORM_MFA_ENTRYPOINT", docker_entrypoint) # Set docker image, workdir, and other default arguments docker_image = "%s:%s" % (env.get("TERRAFORM_IMAGE_NAME"), env.get("TERRAFORM_IMAGE_TAG")) docker_workdir = "/go/src/project" docker_cmd = [ "docker", "run", "--security-opt=label:disable", "--rm", "--workdir=%s" % docker_workdir
def run(entrypoint=TERRAFORM_BINARY, command="", args=None, enable_mfa=True, interactive=True): """ Run a command on a Leverage docker container. Args: entrypoint (str, optional): Entrypoint to use in the container, overrides the one defined in the image. Defaults to `/bin/terraform`. command (str, optional): Command to run. Defaults to "". args (list(str)), optional): Command arguments. Defaults to None. enable_mfa (bool, optional): Whether to enable multi factor authentication. Defaults to True. interactive (bool, optional): If set to False, container will be run in the background and its output grabbed after its execution ends, otherwise access to the container terminal will be given. Defaults to True Returns: int, str: Container exit code and output when interactive is false, otherwise 0, None. """ try: docker_client = DockerClient(base_url="unix://var/run/docker.sock") except: logger.error( "Docker daemon doesn't seem to be responding. " "Please check it is up and running correctly before re-running the command." ) raise Exit(1) env = conf.load() logger.debug( f"[bold cyan]Env config values:[/bold cyan]\n{json.dumps(env, indent=2)}" ) project = env.get("PROJECT", False) if not project: logger.error("Project name has not been set. Exiting.") raise Exit(1) aws_credentials_directory = Path(HOME) / ".aws" / project if not aws_credentials_directory.exists(): aws_credentials_directory.mkdir(parents=True) terraform_image_tag = env.get("TERRAFORM_IMAGE_TAG", DEFAULT_IMAGE_TAG) ensure_image(docker_client=docker_client, image=TERRAFORM_IMAGE, tag=terraform_image_tag) mounts = [ Mount(target=WORKING_DIR, source=CWD, type="bind"), Mount(target="/root/.ssh", source=f"{HOME}/.ssh", type="bind"), # SSH keys for Ansible Mount(target="/etc/gitconfig", source=f"{HOME}/.gitconfig", type="bind"), # Git user configuration Mount(target=f"/root/tmp/{project}", source=f"{HOME}/.aws/{project}", type="bind") ] if Path(str(CONFIG)).exists() and Path(str(ACCOUNT_CONFIG)).exists(): mounts.extend([ Mount(target="/common-config", source=CONFIG, type="bind"), Mount(target="/config", source=ACCOUNT_CONFIG, type="bind") ]) environment = { "AWS_SHARED_CREDENTIALS_FILE": f"/root/.aws/{project}/credentials", "AWS_CONFIG_FILE": f"/root/.aws/{project}/config", "BACKEND_CONFIG_FILE": BACKEND_TFVARS, "COMMON_CONFIG_FILE": COMMON_TFVARS, "SRC_AWS_CONFIG_FILE": f"/root/tmp/{project}/config", "SRC_AWS_SHARED_CREDENTIALS_FILE": f"/root/tmp/{project}/credentials", "AWS_CACHE_DIR": f"/root/tmp/{project}/cache", "MFA_SCRIPT_LOG_LEVEL": get_mfa_script_log_level() } if entrypoint == TERRAFORM_BINARY: enable_mfa = enable_mfa and env.get("MFA_ENABLED") == "true" if enable_mfa: # A layer is a directory with .tf files inside if not list(Path(CWD).glob("*.tf")): logger.error( "This command can only run at [bold]layer[/bold] level.") raise Exit(1) if command or entrypoint != TERRAFORM_BINARY: entrypoint = f"{TERRAFORM_MFA_ENTRYPOINT} -- {entrypoint}" else: entrypoint = TERRAFORM_MFA_ENTRYPOINT else: environment.update({ "AWS_CONFIG_FILE": f"/root/tmp/{project}/config", "AWS_SHARED_CREDENTIALS_FILE": f"/root/tmp/{project}/credentials" }) args = [] if args is None else args command = " ".join([command] + args) host_config = docker_client.api.create_host_config( mounts=mounts, security_opt=["label:disable"]) container_params = { "image": f"{TERRAFORM_IMAGE}:{terraform_image_tag}", "environment": environment, "entrypoint": entrypoint, "working_dir": WORKING_DIR, "host_config": host_config, "command": command } try: container = docker_client.api.create_container(**container_params, stdin_open=True, tty=True) except APIError as exc: logger.exception("Error creating container:", exc_info=exc) raise Exit(1) logger.debug( f"[bold cyan]Container parameters:[/bold cyan]\n{json.dumps(container_params, indent=2)}" ) container_output = None container_exit_code = 0 try: if interactive: dockerpty.start(client=docker_client.api, container=container) container_exit_code = docker_client.api.inspect_container( container)["State"]["ExitCode"] else: docker_client.api.start(container) container_exit_code = docker_client.api.wait( container)["StatusCode"] container_output = docker_client.api.logs(container).decode( "utf-8") except APIError as exc: logger.exception("Error during container execution:", exc_info=exc) finally: docker_client.api.stop(container) docker_client.api.remove_container(container) return container_exit_code, container_output