Skip to content

Commit

Permalink
Merge pull request #25 from tamaskozak/terraform-output-json1
Browse files Browse the repository at this point in the history
Terraform output json1
  • Loading branch information
akuzminsky committed Dec 19, 2019
2 parents 5369a3b + 9df0942 commit c64461b
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 7 deletions.
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[bumpversion]
current_version = 0.8.3
current_version = 0.8.4
commit = True
tag = False

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def parse_requirements(req_file):
if __name__ == "__main__":
setup(
name="terraform-ci",
version="0.8.3",
version="0.8.4",
description="Terraform CI runs terraform in Travis-CI",
long_description=dedent(
"""
Expand Down
30 changes: 25 additions & 5 deletions terraform_ci/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@

import boto3

__version__ = "0.8.3"

__version__ = "0.8.4"

DEFAULT_TERRAFORM_VARS = ".env/tf_env.json"
LOG = logging.getLogger(__name__)
Expand Down Expand Up @@ -390,8 +391,22 @@ def setup_logging(logger, debug=False): # pragma: no cover
logger.setLevel(logging.DEBUG)


def terraform_output(path):
"""
Run terraform output and return the json results as a dict
:param path: Path to directory with terraform module.
:type path: str
:return: dict from terraform output
"""
cmd = "terraform output -json"
ret, cout, cerr = execute(cmd.split(), stdout=PIPE, stderr=None, cwd=path)
if ret:
raise CalledProcessError(returncode=ret, cmd=cmd, output=cout, stderr=cerr)
return json.loads(cout)


@contextmanager
def terraform_apply(path, destroy_after=True):
def terraform_apply(path, destroy_after=True, json_output=False):
"""
Run terraform init and apply, then return a generator.
If destroy_after is True, run terraform destroy afterwards.
Expand All @@ -400,8 +415,10 @@ def terraform_apply(path, destroy_after=True):
:type path: str
:param destroy_after: Run terraform destroy after context it returned back.
:type destroy_after: bool
:return: Nothing. The function just yields to use it in the ``with``
block.
:param json_output: Yield terraform output result as a dict (available in the context)
:type json_output: bool
:return: If json_output is true then yield the result from terraform_output otherwise nothing.
Use it in the ``with`` block.
:raise CalledProcessError: if either of terraform commands (except ``terraform destroy``)
exits with non-zero.
"""
Expand All @@ -420,7 +437,10 @@ def terraform_apply(path, destroy_after=True):
raise CalledProcessError(
returncode=ret, cmd=cmd, output=cout, stderr=cerr
)
yield
if json_output:
yield terraform_output(path)
else:
yield

finally:
if destroy_after:
Expand Down

0 comments on commit c64461b

Please sign in to comment.