Skip to content

Commit

Permalink
[159] Improve apply arguments parsing logic
Browse files Browse the repository at this point in the history
  • Loading branch information
borland667 authored and Osvaldo Demo committed Apr 18, 2024
1 parent d10afc8 commit abc6f65
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 5 deletions.
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)

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

0 comments on commit abc6f65

Please sign in to comment.