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

[159] Improve apply arguments parsing logic #260

Merged
merged 1 commit into from
Apr 18, 2024
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
8 changes: 7 additions & 1 deletion .github/workflows/tests-integration.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ jobs:
max-parallel: 1
matrix:
python-version: [3.8.14,3.9.15,3.10.8]
toolbox-image-tag: ['1.3.5-0.1.15', '1.5.0-0.1.15', '1.6.0-0.1.15']
steps:
- name: Checkout base branch
uses: actions/checkout@v3
Expand Down Expand Up @@ -153,6 +154,12 @@ jobs:
printf "[INFO] Cloning repo...\n"
git clone https://github.com/binbashar/le-tf-infra-aws.git ../theblairwitchproject

- name: Set Toolbox Image Tag for the cloned ref arch repo
run: |
echo "Updating Terraform Image Tag to ${{ matrix.toolbox-image-tag }}"
sed -E -i 's/^TERRAFORM_IMAGE_TAG=.+$/TERRAFORM_IMAGE_TAG=${{ matrix.toolbox-image-tag }}/' build.env
working-directory: ../theblairwitchproject

- name: Configure Testing Reference Architecture
run: |
echo "[INFO] Configure Reference Architecture\n"
Expand All @@ -175,7 +182,6 @@ jobs:
EOF
echo "[INFO] Disable MFA\n"
sed -i "s/^\(MFA_ENABLED=\)true/\1false/" build.env
sed -E -i 's/^TERRAFORM_IMAGE_TAG=.+$/TERRAFORM_IMAGE_TAG=1.2.7-0.0.5/' build.env;
working-directory: ../theblairwitchproject

- name: Test Testing Reference Architecture
Expand Down
48 changes: 44 additions & 4 deletions leverage/modules/terraform.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import os
import re

import click
import dockerpty
import hcl2
import click
from click.exceptions import Exit

from leverage import logger
from leverage._internals import pass_state
from leverage._internals import pass_container
from leverage._internals import pass_state
from leverage._utils import tar_directory, AwsCredsContainer, LiveContainer, ExitError
from leverage.container import get_docker_client
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

REGION = (
Expand Down Expand Up @@ -351,18 +351,58 @@ def _plan(tf, args):
raise Exit(exit_code)


def handle_apply_arguments_parsing(args):
"""Parse and process the arguments for the 'apply' command."""
# Initialize new_args to handle both '-key=value' and '-key value'
new_args = []
skip_next = False # Flag to skip the next argument if it's part of '-key value'

for i, arg in enumerate(args):
if skip_next:
skip_next = False # Reset flag and skip this iteration
continue

if arg.startswith("-") and not arg.startswith("-var"):
if i + 1 < len(args) and not args[i + 1].startswith("-"):
# Detected '-key value' pair; append them without merging
new_args.append(arg)
new_args.append(args[i + 1])
skip_next = True # Mark to skip the next item as it's already processed
logger.debug(f"Detected '-key value' pair: {arg}, {args[i + 1]}")
else:
# Either '-key=value' or a standalone '-key'; just append
new_args.append(arg)
logger.debug(f"Appending standard -key=value or standalone argument: {arg}")
else:
# Handles '-var' and non '-' starting arguments
new_args.append(arg)
logger.debug(f"Appending argument (non '-' or '-var'): {arg}")

return new_args


@pass_container
def _apply(tf, args):
"""Build or change the infrastructure in this layer."""
# if there is a plan, remove all "-var" from the default args
# Preserve the original `-var` removal logic and modify tf_default_args if necessary
tf_default_args = tf.tf_default_args
for arg in args:
if not arg.startswith("-"):
tf_default_args = [arg for index, arg in enumerate(tf_default_args) if not arg.startswith("-var")]
break
exit_code = tf.start_in_layer("apply", *tf_default_args, *args)

# Process arguments using the new parsing logic
processed_args = handle_apply_arguments_parsing(args)
angelofenoglio marked this conversation as resolved.
Show resolved Hide resolved

logger.debug(f"Original tf_default_args: {tf_default_args}")
logger.debug(f"Processed argument list for execution: {processed_args}")

# Execute the command with the modified arguments list
exit_code = tf.start_in_layer("apply", *tf_default_args, *processed_args)

if exit_code:
logger.error(f"Command execution failed with exit code: {exit_code}")
raise Exit(exit_code)


Expand Down
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import pytest

from leverage.modules.terraform import handle_apply_arguments_parsing


class TestHandleApplyArgumentsParsing:
@pytest.mark.parametrize(
"input_args,expected_output",
[
# Test case: Single '-key=value'
(["-target=kubernetes_manifest.irfq"], ["-target=kubernetes_manifest.irfq"]),
# Test case: '-key value'
(["-target", "kubernetes_manifest.irfq"], ["-target", "kubernetes_manifest.irfq"]),
# Test case: Multiple mixed arguments
(
["-target", "kubernetes_manifest.irfq", "-lock=false"],
["-target", "kubernetes_manifest.irfq", "-lock=false"],
),
# Test case: '-var' arguments should be included as is
(["-var", "name=value"], ["-var", "name=value"]),
# Test case: Non-flag argument
(["some_value"], ["some_value"]),
# Test case: Mixed '-key=value' and '-key value' with '-var'
(
["-var", "name=value", "-target", "kubernetes_manifest.irfq", "-lock=false"],
["-var", "name=value", "-target", "kubernetes_manifest.irfq", "-lock=false"],
),
# Test case: No arguments
([], []),
# Test case: '-key=value' format with '-var'
(["-var", "name=value", "-lock=false"], ["-var", "name=value", "-lock=false"]),
],
)
def test_handle_apply_arguments_parsing(self, input_args, expected_output):
assert handle_apply_arguments_parsing(input_args) == expected_output
Loading