Skip to content
This repository has been archived by the owner on Feb 25, 2024. It is now read-only.

refactor terraform scripts and apply/destroy cli commands #126

Merged
merged 1 commit into from
Apr 22, 2022
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
11 changes: 7 additions & 4 deletions bentoctl/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import click

from bentoctl import __version__
from bentoctl.cli.helper_scripts import terraform_apply, terraform_destroy
from bentoctl.terraform import terraform_apply, terraform_destroy, is_terraform_applied
from bentoctl.cli.interactive import deployment_config_builder
from bentoctl.cli.operator_management import get_operator_management_subcommands
from bentoctl.cli.utils import BentoctlCommandGroup, handle_bentoctl_exceptions
Expand Down Expand Up @@ -182,10 +182,13 @@ def destroy(deployment_config_file):
Destroy all the resources created and remove the registry.
"""
deployment_config = DeploymentConfig.from_file(deployment_config_file)
if deployment_config.template_type.startswith("terraform"):
if (
deployment_config.template_type.startswith("terraform")
and is_terraform_applied()
):
terraform_destroy()
deployment_config.delete_repository()
console.print(f"Deleted the repository {deployment_config.repository_name}")
deployment_config.delete_repository()
console.print(f"Deleted the repository {deployment_config.repository_name}")


@bentoctl.command()
Expand Down
36 changes: 0 additions & 36 deletions bentoctl/cli/helper_scripts.py

This file was deleted.

63 changes: 63 additions & 0 deletions bentoctl/terraform.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import os
import json
import subprocess

from bentoctl.exceptions import BentoctlException

TERRAFORM_VALUES_FILE = "bentoctl.tfvars"
TERRAFORM_INIT_FOLDER = ".terraform"


def terraform_run(cmd: list, return_output: bool = False):
try:
if not return_output:
subprocess.run(["terraform", *cmd], check=False)
proc = subprocess.Popen(
["terraform", *cmd],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = proc.communicate()
return proc.returncode, stdout.decode("utf-8"), stderr.decode("utf-8")
Comment on lines +13 to +21
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we pipe out the outputs and stderr from terraform? we want the users to know exactly what terraform is doing write?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't user already see the changes in their console with subprocess?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ohh the issue was there were two subprocess calls happening if return_output if false.

except FileNotFoundError:
raise BentoctlException(
"terraform not available. Please make "
"sure terraform is installed and available your path."
)


def terraform_destroy():
if not is_terraform_initialised():
raise BentoctlException('terraform is not initialised')
if not os.path.exists(os.path.join(os.curdir, TERRAFORM_VALUES_FILE)):
raise BentoctlException(
f"{TERRAFORM_VALUES_FILE} not found in current directory."
)
terraform_run(["apply", "-destroy", "-var-file", TERRAFORM_VALUES_FILE, '-auto-approve'])

Comment on lines +36 to +37
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

having -auto-approve here would not give the users a change to see exactly what changes are being made to the infra right? They should probably have a plan phase before destroy

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. It won't let user to see what changed. I am not sure user can interact with subprocess. Also I think auto approve could be an Orion in our cli.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since we don't pipe the stdin the user can interact with it as if we called it from the terminal, so it will be a low friction way to perform all the terraform commands and yeah, we should have the auto-approve command or a more general command like '--yes' or something.


def is_terraform_initialised():
return os.path.exists(os.path.join(os.curdir, TERRAFORM_INIT_FOLDER))


def terraform_apply():
if not is_terraform_initialised():
terraform_run(["init"])

terraform_run(["apply", "-var-file", TERRAFORM_VALUES_FILE, '-auto-approve'])


def terraform_output():
return_code, result, error = terraform_run(["output", "-json"], return_output=True)
if return_code != 0:
raise BentoctlException(error)
return json.loads(result)


def is_terraform_applied() -> bool:
"""
Check if terraform is applied.
"""
# If the terraform is not currently applied, it will return an empty dict.
result = terraform_output()
return True if result else False