Skip to content

Commit

Permalink
Merge branch 'master' of github.com:binbashar/leverage into 599-kubec…
Browse files Browse the repository at this point in the history
…onfig-helper
  • Loading branch information
Franr committed Feb 10, 2025
2 parents ffc191b + 9cbfa4c commit a0cc46b
Show file tree
Hide file tree
Showing 17 changed files with 47 additions and 15 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tests-integration.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ jobs:
run: |
mkdir -p ../theadamproject
# These are later mounted in the container
mkdir ~/.ssh && touch ~/.gitconfig
mkdir ~/.ssh
- name: Project Init
run: |
Expand Down
2 changes: 0 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ RUN git clone https://github.com/bats-core/bats-assert.git

# Needed as is mounted later on
RUN mkdir /root/.ssh
# Needed for git to run propertly
RUN touch /root/.gitconfig

RUN curl -sSL https://install.python-poetry.org | POETRY_HOME=/usr/local POETRY_VERSION=1.8.2 python3 -

Expand Down
1 change: 1 addition & 0 deletions leverage/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Binbash Leverage Command-line tool.
"""

# pylint: disable=wrong-import-position

__version__ = "0.0.0"
Expand Down
1 change: 1 addition & 0 deletions leverage/_internals.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Definitions for internal use of the cli.
"""

from functools import wraps

import click
Expand Down
18 changes: 18 additions & 0 deletions leverage/_utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
"""
General use utilities.
"""

from pathlib import Path
from subprocess import run
from subprocess import PIPE

import hcl2
import lark
from click.exceptions import Exit
from configupdater import ConfigUpdater
from docker import DockerClient
Expand Down Expand Up @@ -112,6 +116,20 @@ def __init__(self, exit_code: int, error_description: str):
super(ExitError, self).__init__(exit_code)


def parse_tf_file(file: Path):
"""
Open and parse an HCL file.
In case of a parsing error, raise a user-friendly error.
"""
with open(file) as f:
try:
parsed = hcl2.load(f)
except lark.exceptions.UnexpectedInput:
raise ExitError(1, f"There is a parsing error with the {f.name} file. Please review it.")
else:
return parsed


class ContainerSession:
"""
Handle the start/stop cycle of a container.
Expand Down
1 change: 1 addition & 0 deletions leverage/conf.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Env variables loading utility.
"""

from pathlib import Path

from yaenv.core import Env
Expand Down
5 changes: 4 additions & 1 deletion leverage/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,9 @@ def __init__(self, client, mounts=None, env_vars=None):
# SSH AGENT
SSH_AUTH_SOCK = os.getenv("SSH_AUTH_SOCK")

# make sure .gitconfig exists before mounting it
self.paths.host_git_config_file.touch(exist_ok=True)

self.environment.update(
{
"COMMON_CONFIG_FILE": self.paths.common_tfvars,
Expand All @@ -479,7 +482,7 @@ def __init__(self, client, mounts=None, env_vars=None):
target=self.paths.guest_aws_credentials_dir,
type="bind",
),
Mount(source=(self.paths.home / ".gitconfig").as_posix(), target="/etc/gitconfig", type="bind"),
Mount(source=self.paths.host_git_config_file.as_posix(), target="/etc/gitconfig", type="bind"),
]
self.mounts.extend(extra_mounts)
# if you have set the tf plugin cache locally
Expand Down
1 change: 1 addition & 0 deletions leverage/leverage.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Binbash Leverage Command-line tool.
"""

import click

from leverage import __version__
Expand Down
1 change: 1 addition & 0 deletions leverage/logger.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Logging utilities.
"""

import logging
from functools import wraps

Expand Down
11 changes: 4 additions & 7 deletions leverage/modules/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@
from pathlib import Path
from configparser import NoSectionError, NoOptionError

import hcl2
import boto3
from configupdater import ConfigUpdater
from botocore.exceptions import ClientError
from configupdater import ConfigUpdater

from leverage import logger
from leverage._utils import key_finder, ExitError, get_or_create_section
from leverage._utils import key_finder, ExitError, get_or_create_section, parse_tf_file


class SkipProfile(Exception):
Expand Down Expand Up @@ -66,8 +65,7 @@ def get_profiles(cli):
# these are files from the layer we are currently on
for name in ("config.tf", "locals.tf"):
try:
with open(cli.paths.cwd / name) as tf_file:
tf_config = hcl2.load(tf_file)
tf_config = parse_tf_file(Path(cli.paths.cwd / name))
except FileNotFoundError:
continue

Expand All @@ -76,8 +74,7 @@ def get_profiles(cli):
raw_profiles.update(set(key_finder(tf_config, "profile", "lookup")))

# the profile value from <layer>/config/backend.tfvars
with open(cli.paths.local_backend_tfvars) as backend_config_file:
backend_config = hcl2.load(backend_config_file)
backend_config = parse_tf_file(cli.paths.local_backend_tfvars)
tf_profile = backend_config["profile"]

return tf_profile, raw_profiles
Expand Down
1 change: 1 addition & 0 deletions leverage/modules/credentials.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Credentials managing module.
"""

import csv
import json
import re
Expand Down
1 change: 1 addition & 0 deletions leverage/modules/project.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Module for managing Leverage projects.
"""

import re
from pathlib import Path
from shutil import copy2
Expand Down
1 change: 1 addition & 0 deletions leverage/modules/run.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Tasks running module.
"""

import re

import click
Expand Down
8 changes: 4 additions & 4 deletions leverage/modules/terraform.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import re
from pathlib import Path
from typing import Sequence

import click
import hcl2
from click.exceptions import Exit

from leverage import logger
from leverage._internals import pass_container, pass_state
from leverage._utils import ExitError
from leverage._utils import ExitError, parse_tf_file
from leverage.container import TerraformContainer
from leverage.container import get_docker_client
from leverage.modules.utils import env_var_option, mount_option, auth_mfa, auth_sso
Expand Down Expand Up @@ -512,8 +512,8 @@ def _validate_layout(tf: TerraformContainer):
logger.error("[red]✘ FAILED[/red]\n")
valid_layout = False

backend_tfvars = tf.paths.account_config_dir / tf.paths.BACKEND_TF_VARS # TODO use paths.backend_tfvars instead?
backend_tfvars = hcl2.loads(backend_tfvars.read_text()) if backend_tfvars.exists() else {}
backend_tfvars = Path(tf.paths.local_backend_tfvars)
backend_tfvars = parse_tf_file(backend_tfvars) if backend_tfvars.exists() else {}

logger.info("Checking [bold]backend.tfvars[/bold]:\n")
names_prefix = f"{tf.project}-{account_name}"
Expand Down
5 changes: 5 additions & 0 deletions leverage/path.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Utilities to obtain relevant files' and directories' locations
"""

import os
import pathlib
from pathlib import Path
Expand Down Expand Up @@ -206,6 +207,10 @@ def host_aws_profiles_file(self):
def host_aws_credentials_file(self):
return self.host_aws_credentials_dir / "credentials"

@property
def host_git_config_file(self):
return self.home / ".gitconfig"

@property
def local_backend_tfvars(self):
return self.account_config_dir / self.BACKEND_TF_VARS
Expand Down
1 change: 1 addition & 0 deletions leverage/tasks.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Task loading, Task object definition and task creation decorator.
"""

import sys
import importlib
from pathlib import Path
Expand Down
2 changes: 2 additions & 0 deletions tests/test_modules/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,8 @@ def test_get_layer_profile(muted_click_context):
"""

data_dict = {
PosixPath("config.tf"): FILE_CONFIG_TF,
PosixPath("locals.tf"): FILE_LOCALS_TF,
"~/config/backend.tfvars": FILE_BACKEND_TFVARS,
"~/.aws/test/config": FILE_AWS_CONFIG,
"~/.aws/test/credentials": FILE_AWS_CREDENTIALS,
Expand Down

0 comments on commit a0cc46b

Please sign in to comment.