2015-12-31 04:10:59 +00:00
|
|
|
|
import subprocess
|
|
|
|
|
import os
|
2017-03-31 18:32:47 +00:00
|
|
|
|
import sys
|
2015-12-31 04:10:59 +00:00
|
|
|
|
import json
|
|
|
|
|
import logging
|
2016-12-20 10:53:01 +00:00
|
|
|
|
import tempfile
|
2015-12-31 04:10:59 +00:00
|
|
|
|
|
2016-11-18 07:35:14 +00:00
|
|
|
|
from python_terraform.tfstate import Tfstate
|
|
|
|
|
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
|
2020-10-19 21:57:22 +00:00
|
|
|
|
logger = logging.getLogger(__name__)
|
2017-08-28 18:17:33 +00:00
|
|
|
|
|
2020-10-19 21:57:22 +00:00
|
|
|
|
COMMAND_WITH_SUBCOMMANDS = {"workspace"}
|
2015-12-31 04:10:59 +00:00
|
|
|
|
|
|
|
|
|
|
2016-11-19 10:24:33 +00:00
|
|
|
|
class IsFlagged:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
2017-01-03 17:34:37 +00:00
|
|
|
|
class IsNotFlagged:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
class TerraformCommandError(subprocess.CalledProcessError):
|
2020-10-19 21:57:22 +00:00
|
|
|
|
def __init__(self, ret_code, cmd, out, err):
|
|
|
|
|
super(TerraformCommandError, self).__init__(ret_code, cmd)
|
|
|
|
|
self.out = out
|
|
|
|
|
self.err = err
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
|
2019-06-25 18:53:39 +00:00
|
|
|
|
|
2016-12-20 10:53:01 +00:00
|
|
|
|
class Terraform(object):
|
2020-10-19 21:57:22 +00:00
|
|
|
|
"""Wrapper of terraform command line tool.
|
|
|
|
|
|
2016-11-18 07:35:14 +00:00
|
|
|
|
https://www.terraform.io/
|
|
|
|
|
"""
|
|
|
|
|
|
2020-10-19 21:57:22 +00:00
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
working_dir=None,
|
|
|
|
|
targets=None,
|
|
|
|
|
state=None,
|
|
|
|
|
variables=None,
|
|
|
|
|
parallelism=None,
|
|
|
|
|
var_file=None,
|
|
|
|
|
terraform_bin_path=None,
|
|
|
|
|
is_env_vars_included=True,
|
|
|
|
|
):
|
2017-08-02 00:51:12 +00:00
|
|
|
|
"""
|
2017-01-03 17:02:11 +00:00
|
|
|
|
:param working_dir: the folder of the working folder, if not given,
|
|
|
|
|
will be current working folder
|
2016-11-19 10:24:33 +00:00
|
|
|
|
:param targets: list of target
|
2017-01-03 17:02:11 +00:00
|
|
|
|
as default value of apply/destroy/plan command
|
|
|
|
|
:param state: path of state file relative to working folder,
|
|
|
|
|
as a default value of apply/destroy/plan command
|
|
|
|
|
:param variables: default variables for apply/destroy/plan command,
|
|
|
|
|
will be override by variable passing by apply/destroy/plan method
|
|
|
|
|
:param parallelism: default parallelism value for apply/destroy command
|
|
|
|
|
:param var_file: passed as value of -var-file option,
|
|
|
|
|
could be string or list, list stands for multiple -var-file option
|
2016-11-19 10:24:33 +00:00
|
|
|
|
:param terraform_bin_path: binary path of terraform
|
2017-05-09 08:05:48 +00:00
|
|
|
|
:type is_env_vars_included: bool
|
2017-08-02 00:51:12 +00:00
|
|
|
|
:param is_env_vars_included: included env variables when calling terraform cmd
|
2016-11-19 10:24:33 +00:00
|
|
|
|
"""
|
2017-05-09 08:05:48 +00:00
|
|
|
|
self.is_env_vars_included = is_env_vars_included
|
2016-11-18 07:35:14 +00:00
|
|
|
|
self.working_dir = working_dir
|
|
|
|
|
self.state = state
|
2015-12-31 04:10:59 +00:00
|
|
|
|
self.targets = [] if targets is None else targets
|
|
|
|
|
self.variables = dict() if variables is None else variables
|
2016-11-18 07:35:14 +00:00
|
|
|
|
self.parallelism = parallelism
|
2020-10-19 21:57:22 +00:00
|
|
|
|
self.terraform_bin_path = (
|
|
|
|
|
terraform_bin_path if terraform_bin_path else "terraform"
|
|
|
|
|
)
|
2016-11-18 07:35:14 +00:00
|
|
|
|
self.var_file = var_file
|
2016-12-20 16:18:57 +00:00
|
|
|
|
self.temp_var_files = VariableFiles()
|
2016-11-18 07:35:14 +00:00
|
|
|
|
|
|
|
|
|
# store the tfstate data
|
2016-12-20 10:53:01 +00:00
|
|
|
|
self.tfstate = None
|
|
|
|
|
self.read_state_file(self.state)
|
|
|
|
|
|
|
|
|
|
def __getattr__(self, item):
|
|
|
|
|
def wrapper(*args, **kwargs):
|
2017-05-09 07:48:28 +00:00
|
|
|
|
cmd_name = str(item)
|
2020-10-19 21:57:22 +00:00
|
|
|
|
if cmd_name.endswith("_cmd"):
|
2017-05-09 07:48:28 +00:00
|
|
|
|
cmd_name = cmd_name[:-4]
|
2020-10-19 21:57:22 +00:00
|
|
|
|
logger.debug("called with %r and %r", args, kwargs)
|
2017-05-09 07:48:28 +00:00
|
|
|
|
return self.cmd(cmd_name, *args, **kwargs)
|
2016-12-20 10:53:01 +00:00
|
|
|
|
|
|
|
|
|
return wrapper
|
2016-11-18 07:35:14 +00:00
|
|
|
|
|
2020-10-19 21:57:22 +00:00
|
|
|
|
def apply(
|
|
|
|
|
self,
|
|
|
|
|
dir_or_plan=None,
|
|
|
|
|
input=False,
|
|
|
|
|
skip_plan=False,
|
|
|
|
|
no_color=IsFlagged,
|
|
|
|
|
**kwargs,
|
|
|
|
|
):
|
|
|
|
|
"""Refer to https://terraform.io/docs/commands/apply.html
|
|
|
|
|
|
2016-11-24 07:09:16 +00:00
|
|
|
|
no-color is flagged by default
|
2017-01-03 17:34:37 +00:00
|
|
|
|
:param no_color: disable color of stdout
|
|
|
|
|
:param input: disable prompt for a missing variable
|
2016-11-24 07:09:16 +00:00
|
|
|
|
:param dir_or_plan: folder relative to working folder
|
2017-11-24 21:03:56 +00:00
|
|
|
|
:param skip_plan: force apply without plan (default: false)
|
2016-11-19 10:24:33 +00:00
|
|
|
|
:param kwargs: same as kwags in method 'cmd'
|
2016-02-25 09:22:11 +00:00
|
|
|
|
:returns return_code, stdout, stderr
|
2015-12-31 06:48:26 +00:00
|
|
|
|
"""
|
2017-01-03 17:34:37 +00:00
|
|
|
|
default = kwargs
|
2020-10-19 21:57:22 +00:00
|
|
|
|
default["input"] = input
|
|
|
|
|
default["no_color"] = no_color
|
|
|
|
|
default["auto-approve"] = skip_plan is True
|
2017-01-03 17:34:37 +00:00
|
|
|
|
option_dict = self._generate_default_options(default)
|
|
|
|
|
args = self._generate_default_args(dir_or_plan)
|
2020-10-19 21:57:22 +00:00
|
|
|
|
return self.cmd("apply", *args, **option_dict)
|
2016-11-19 10:24:33 +00:00
|
|
|
|
|
2017-01-03 17:34:37 +00:00
|
|
|
|
def _generate_default_args(self, dir_or_plan):
|
|
|
|
|
return [dir_or_plan] if dir_or_plan else []
|
|
|
|
|
|
|
|
|
|
def _generate_default_options(self, input_options):
|
|
|
|
|
option_dict = dict()
|
2020-10-19 21:57:22 +00:00
|
|
|
|
option_dict["state"] = self.state
|
|
|
|
|
option_dict["target"] = self.targets
|
|
|
|
|
option_dict["var"] = self.variables
|
|
|
|
|
option_dict["var_file"] = self.var_file
|
|
|
|
|
option_dict["parallelism"] = self.parallelism
|
|
|
|
|
option_dict["no_color"] = IsFlagged
|
|
|
|
|
option_dict["input"] = False
|
2017-01-03 17:34:37 +00:00
|
|
|
|
option_dict.update(input_options)
|
|
|
|
|
return option_dict
|
2016-11-18 07:35:14 +00:00
|
|
|
|
|
2017-01-03 17:34:37 +00:00
|
|
|
|
def destroy(self, dir_or_plan=None, force=IsFlagged, **kwargs):
|
2020-10-19 21:57:22 +00:00
|
|
|
|
"""Refer to https://www.terraform.io/docs/commands/destroy.html
|
|
|
|
|
|
2016-11-24 07:09:16 +00:00
|
|
|
|
force/no-color option is flagged by default
|
2016-11-19 10:24:33 +00:00
|
|
|
|
:return: ret_code, stdout, stderr
|
|
|
|
|
"""
|
2017-01-03 17:34:37 +00:00
|
|
|
|
default = kwargs
|
2020-10-19 21:57:22 +00:00
|
|
|
|
default["force"] = force
|
2017-01-04 05:21:30 +00:00
|
|
|
|
options = self._generate_default_options(default)
|
|
|
|
|
args = self._generate_default_args(dir_or_plan)
|
2020-10-19 21:57:22 +00:00
|
|
|
|
return self.cmd("destroy", *args, **options)
|
2017-01-04 05:21:30 +00:00
|
|
|
|
|
|
|
|
|
def plan(self, dir_or_plan=None, detailed_exitcode=IsFlagged, **kwargs):
|
2020-10-19 21:57:22 +00:00
|
|
|
|
"""Refer to https://www.terraform.io/docs/commands/plan.html
|
|
|
|
|
|
2017-01-04 05:21:30 +00:00
|
|
|
|
:param detailed_exitcode: Return a detailed exit code when the command exits.
|
|
|
|
|
:param dir_or_plan: relative path to plan/folder
|
|
|
|
|
:param kwargs: options
|
|
|
|
|
:return: ret_code, stdout, stderr
|
|
|
|
|
"""
|
|
|
|
|
options = kwargs
|
2020-10-19 21:57:22 +00:00
|
|
|
|
options["detailed_exitcode"] = detailed_exitcode
|
2017-01-04 05:21:30 +00:00
|
|
|
|
options = self._generate_default_options(options)
|
2017-01-03 17:34:37 +00:00
|
|
|
|
args = self._generate_default_args(dir_or_plan)
|
2020-10-19 21:57:22 +00:00
|
|
|
|
return self.cmd("plan", *args, **options)
|
|
|
|
|
|
|
|
|
|
def init(
|
|
|
|
|
self,
|
|
|
|
|
dir_or_plan=None,
|
|
|
|
|
backend_config=None,
|
|
|
|
|
reconfigure=IsFlagged,
|
|
|
|
|
backend=True,
|
|
|
|
|
**kwargs,
|
|
|
|
|
):
|
|
|
|
|
"""Refer to https://www.terraform.io/docs/commands/init.html
|
2017-08-22 20:12:13 +00:00
|
|
|
|
|
|
|
|
|
By default, this assumes you want to use backend config, and tries to
|
|
|
|
|
init fresh. The flags -reconfigure and -backend=true are default.
|
|
|
|
|
|
2017-08-30 18:00:15 +00:00
|
|
|
|
:param dir_or_plan: relative path to the folder want to init
|
2017-08-22 20:12:13 +00:00
|
|
|
|
:param backend_config: a dictionary of backend config options. eg.
|
|
|
|
|
t = Terraform()
|
2020-10-19 21:57:22 +00:00
|
|
|
|
t.init(backend_config={'access_key': 'myaccesskey',
|
2017-08-22 20:12:13 +00:00
|
|
|
|
'secret_key': 'mysecretkey', 'bucket': 'mybucketname'})
|
|
|
|
|
:param reconfigure: whether or not to force reconfiguration of backend
|
|
|
|
|
:param backend: whether or not to use backend settings for init
|
|
|
|
|
:param kwargs: options
|
|
|
|
|
:return: ret_code, stdout, stderr
|
|
|
|
|
"""
|
|
|
|
|
options = kwargs
|
2020-10-19 21:57:22 +00:00
|
|
|
|
options["backend_config"] = backend_config
|
|
|
|
|
options["reconfigure"] = reconfigure
|
|
|
|
|
options["backend"] = backend
|
2017-08-22 20:12:13 +00:00
|
|
|
|
options = self._generate_default_options(options)
|
|
|
|
|
args = self._generate_default_args(dir_or_plan)
|
2020-10-19 21:57:22 +00:00
|
|
|
|
return self.cmd("init", *args, **options)
|
2017-08-22 20:12:13 +00:00
|
|
|
|
|
2016-11-18 07:35:14 +00:00
|
|
|
|
def generate_cmd_string(self, cmd, *args, **kwargs):
|
2020-10-19 21:57:22 +00:00
|
|
|
|
"""For any generate_cmd_string doesn't written as public method of Terraform
|
2016-11-18 07:35:14 +00:00
|
|
|
|
|
|
|
|
|
examples:
|
|
|
|
|
1. call import command,
|
|
|
|
|
ref to https://www.terraform.io/docs/commands/import.html
|
|
|
|
|
--> generate_cmd_string call:
|
|
|
|
|
terraform import -input=true aws_instance.foo i-abcd1234
|
|
|
|
|
--> python call:
|
|
|
|
|
tf.generate_cmd_string('import', 'aws_instance.foo', 'i-abcd1234', input=True)
|
|
|
|
|
|
|
|
|
|
2. call apply command,
|
|
|
|
|
--> generate_cmd_string call:
|
|
|
|
|
terraform apply -var='a=b' -var='c=d' -no-color the_folder
|
|
|
|
|
--> python call:
|
2016-11-19 10:24:33 +00:00
|
|
|
|
tf.generate_cmd_string('apply', the_folder, no_color=IsFlagged, var={'a':'b', 'c':'d'})
|
2016-11-18 07:35:14 +00:00
|
|
|
|
|
|
|
|
|
:param cmd: command and sub-command of terraform, seperated with space
|
|
|
|
|
refer to https://www.terraform.io/docs/commands/index.html
|
2016-11-19 10:24:33 +00:00
|
|
|
|
:param args: arguments of a command
|
2016-11-18 07:35:14 +00:00
|
|
|
|
:param kwargs: same as kwags in method 'cmd'
|
|
|
|
|
:return: string of valid terraform command
|
2016-02-25 09:22:11 +00:00
|
|
|
|
"""
|
2016-11-18 07:35:14 +00:00
|
|
|
|
cmds = cmd.split()
|
|
|
|
|
cmds = [self.terraform_bin_path] + cmds
|
2019-06-25 18:53:39 +00:00
|
|
|
|
if cmd in COMMAND_WITH_SUBCOMMANDS:
|
|
|
|
|
args = list(args)
|
|
|
|
|
subcommand = args.pop(0)
|
|
|
|
|
cmds.append(subcommand)
|
2016-11-18 07:35:14 +00:00
|
|
|
|
|
2017-08-30 18:00:15 +00:00
|
|
|
|
for option, value in kwargs.items():
|
2020-10-19 21:57:22 +00:00
|
|
|
|
if "_" in option:
|
|
|
|
|
option = option.replace("_", "-")
|
2016-11-18 07:35:14 +00:00
|
|
|
|
|
2017-08-30 18:00:15 +00:00
|
|
|
|
if type(value) is list:
|
|
|
|
|
for sub_v in value:
|
2020-10-19 21:57:22 +00:00
|
|
|
|
cmds += [f"-{option}={sub_v}"]
|
2016-11-18 07:35:14 +00:00
|
|
|
|
continue
|
|
|
|
|
|
2017-08-30 18:00:15 +00:00
|
|
|
|
if type(value) is dict:
|
2020-10-19 21:57:22 +00:00
|
|
|
|
if "backend-config" in option:
|
2017-08-30 18:00:15 +00:00
|
|
|
|
for bk, bv in value.items():
|
2020-10-19 21:57:22 +00:00
|
|
|
|
cmds += [f"-backend-config={bk}={bv}"]
|
2017-08-22 20:12:13 +00:00
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
# since map type sent in string won't work, create temp var file for
|
|
|
|
|
# variables, and clean it up later
|
2020-10-19 21:57:22 +00:00
|
|
|
|
elif option == "var":
|
2019-06-25 18:53:39 +00:00
|
|
|
|
# We do not create empty var-files if there is no var passed.
|
|
|
|
|
# An empty var-file would result in an error: An argument or block definition is required here
|
|
|
|
|
if value:
|
|
|
|
|
filename = self.temp_var_files.create(value)
|
2020-10-19 21:57:22 +00:00
|
|
|
|
cmds += [f"-var-file={filename}"]
|
2019-06-25 18:53:39 +00:00
|
|
|
|
|
2017-08-22 20:12:13 +00:00
|
|
|
|
continue
|
2016-11-18 07:35:14 +00:00
|
|
|
|
|
|
|
|
|
# simple flag,
|
2017-08-30 18:00:15 +00:00
|
|
|
|
if value is IsFlagged:
|
2020-10-19 21:57:22 +00:00
|
|
|
|
cmds += ["-{k}".format(k=option)]
|
2016-11-18 07:35:14 +00:00
|
|
|
|
continue
|
|
|
|
|
|
2017-08-30 18:00:15 +00:00
|
|
|
|
if value is None or value is IsNotFlagged:
|
2016-11-19 10:24:33 +00:00
|
|
|
|
continue
|
|
|
|
|
|
2017-08-30 18:00:15 +00:00
|
|
|
|
if type(value) is bool:
|
2020-10-19 21:57:22 +00:00
|
|
|
|
value = "true" if value else "false"
|
2016-11-18 07:35:14 +00:00
|
|
|
|
|
2020-10-19 21:57:22 +00:00
|
|
|
|
cmds += [f"-{option}={value}"]
|
2016-11-18 07:35:14 +00:00
|
|
|
|
|
|
|
|
|
cmds += args
|
2017-08-08 21:58:33 +00:00
|
|
|
|
return cmds
|
2016-11-18 07:35:14 +00:00
|
|
|
|
|
|
|
|
|
def cmd(self, cmd, *args, **kwargs):
|
2020-10-19 21:57:22 +00:00
|
|
|
|
"""Run a terraform command, if success, will try to read state file
|
|
|
|
|
|
2016-11-18 07:35:14 +00:00
|
|
|
|
:param cmd: command and sub-command of terraform, seperated with space
|
|
|
|
|
refer to https://www.terraform.io/docs/commands/index.html
|
2016-11-19 10:24:33 +00:00
|
|
|
|
:param args: arguments of a command
|
|
|
|
|
:param kwargs: any option flag with key value without prefixed dash character
|
|
|
|
|
if there's a dash in the option name, use under line instead of dash,
|
|
|
|
|
ex. -no-color --> no_color
|
|
|
|
|
if it's a simple flag with no value, value should be IsFlagged
|
|
|
|
|
ex. cmd('taint', allow_missing=IsFlagged)
|
2016-11-18 07:35:14 +00:00
|
|
|
|
if it's a boolean value flag, assign True or false
|
|
|
|
|
if it's a flag could be used multiple times, assign list to it's value
|
|
|
|
|
if it's a "var" variable flag, assign dictionary to it
|
|
|
|
|
if a value is None, will skip this option
|
2017-03-31 18:32:47 +00:00
|
|
|
|
if the option 'capture_output' is passed (with any value other than
|
|
|
|
|
True), terraform output will be printed to stdout/stderr and
|
|
|
|
|
"None" will be returned as out and err.
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
if the option 'raise_on_error' is passed (with any value that evaluates to True),
|
|
|
|
|
and the terraform command returns a nonzerop return code, then
|
|
|
|
|
a TerraformCommandError exception will be raised. The exception object will
|
|
|
|
|
have the following properties:
|
|
|
|
|
returncode: The command's return code
|
|
|
|
|
out: The captured stdout, or None if not captured
|
|
|
|
|
err: The captured stderr, or None if not captured
|
2016-11-18 07:35:14 +00:00
|
|
|
|
:return: ret_code, out, err
|
2015-12-31 04:10:59 +00:00
|
|
|
|
"""
|
2020-10-19 21:57:22 +00:00
|
|
|
|
capture_output = kwargs.pop("capture_output", True)
|
|
|
|
|
raise_on_error = kwargs.pop("raise_on_error", False)
|
|
|
|
|
synchronous = kwargs.pop("synchronous", True)
|
|
|
|
|
|
2017-03-31 18:32:47 +00:00
|
|
|
|
if capture_output is True:
|
|
|
|
|
stderr = subprocess.PIPE
|
|
|
|
|
stdout = subprocess.PIPE
|
2019-11-07 10:00:59 +00:00
|
|
|
|
elif capture_output == "framework":
|
|
|
|
|
stderr = None
|
|
|
|
|
stdout = None
|
2017-03-31 18:32:47 +00:00
|
|
|
|
else:
|
|
|
|
|
stderr = sys.stderr
|
|
|
|
|
stdout = sys.stdout
|
|
|
|
|
|
2017-08-08 21:58:33 +00:00
|
|
|
|
cmds = self.generate_cmd_string(cmd, *args, **kwargs)
|
2020-10-19 21:57:22 +00:00
|
|
|
|
logger.debug("Command: %s", " ".join(cmds))
|
2015-12-31 04:10:59 +00:00
|
|
|
|
|
2016-11-19 10:24:33 +00:00
|
|
|
|
working_folder = self.working_dir if self.working_dir else None
|
|
|
|
|
|
2017-05-09 08:05:48 +00:00
|
|
|
|
environ_vars = {}
|
|
|
|
|
if self.is_env_vars_included:
|
|
|
|
|
environ_vars = os.environ.copy()
|
|
|
|
|
|
2020-10-19 21:57:22 +00:00
|
|
|
|
p = subprocess.Popen(
|
|
|
|
|
cmds, stdout=stdout, stderr=stderr, cwd=working_folder, env=environ_vars
|
|
|
|
|
)
|
2017-08-11 18:00:06 +00:00
|
|
|
|
|
|
|
|
|
if not synchronous:
|
|
|
|
|
return p, None, None
|
|
|
|
|
|
2016-11-18 07:35:14 +00:00
|
|
|
|
out, err = p.communicate()
|
|
|
|
|
ret_code = p.returncode
|
2020-10-19 21:57:22 +00:00
|
|
|
|
logger.debug("output: %s", out)
|
2016-02-25 09:22:11 +00:00
|
|
|
|
|
2016-11-18 07:35:14 +00:00
|
|
|
|
if ret_code == 0:
|
|
|
|
|
self.read_state_file()
|
|
|
|
|
else:
|
2020-10-19 21:57:22 +00:00
|
|
|
|
logger.warning("error: %s", err)
|
2016-12-20 10:53:01 +00:00
|
|
|
|
|
|
|
|
|
self.temp_var_files.clean_up()
|
2017-03-31 18:32:47 +00:00
|
|
|
|
if capture_output is True:
|
2020-10-19 21:57:22 +00:00
|
|
|
|
out = out.decode()
|
|
|
|
|
err = err.decode()
|
2017-03-31 18:32:47 +00:00
|
|
|
|
else:
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
out = None
|
|
|
|
|
err = None
|
|
|
|
|
|
2020-10-19 21:57:22 +00:00
|
|
|
|
if ret_code and raise_on_error:
|
|
|
|
|
raise TerraformCommandError(ret_code, " ".join(cmds), out=out, err=err)
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
|
|
|
|
|
return ret_code, out, err
|
2016-11-18 07:35:14 +00:00
|
|
|
|
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
def output(self, *args, **kwargs):
|
2020-10-19 21:57:22 +00:00
|
|
|
|
"""Refer https://www.terraform.io/docs/commands/output.html
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
|
2020-10-19 21:57:22 +00:00
|
|
|
|
Note that this method does not conform to the (ret_code, out, err) return
|
|
|
|
|
convention. To use the "output" command with the standard convention,
|
|
|
|
|
call "output_cmd" instead of "output".
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
|
|
|
|
|
:param args: Positional arguments. There is one optional positional
|
|
|
|
|
argument NAME; if supplied, the returned output text
|
|
|
|
|
will be the json for a single named output value.
|
2020-10-19 21:57:22 +00:00
|
|
|
|
:param kwargs: Named options, passed to the command. In addition,
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
'full_value': If True, and NAME is provided, then
|
|
|
|
|
the return value will be a dict with
|
|
|
|
|
"value', 'type', and 'sensitive'
|
|
|
|
|
properties.
|
|
|
|
|
:return: None, if an error occured
|
|
|
|
|
Output value as a string, if NAME is provided and full_value
|
|
|
|
|
is False or not provided
|
|
|
|
|
Output value as a dict with 'value', 'sensitive', and 'type' if
|
|
|
|
|
NAME is provided and full_value is True.
|
|
|
|
|
dict of named dicts each with 'value', 'sensitive', and 'type',
|
|
|
|
|
if NAME is not provided
|
2016-11-18 07:35:14 +00:00
|
|
|
|
"""
|
2020-10-19 21:57:22 +00:00
|
|
|
|
full_value = kwargs.pop("full_value", False)
|
|
|
|
|
name_provided = bool(len(args))
|
|
|
|
|
kwargs["json"] = IsFlagged
|
|
|
|
|
if not kwargs.get("capture_output", True) is True:
|
|
|
|
|
raise ValueError("capture_output is required for this method")
|
2017-08-02 00:51:12 +00:00
|
|
|
|
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
ret, out, err = self.output_cmd(*args, **kwargs)
|
2016-11-18 07:35:14 +00:00
|
|
|
|
|
2020-10-19 21:57:22 +00:00
|
|
|
|
if ret:
|
2017-10-16 16:12:34 +00:00
|
|
|
|
return None
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
|
2016-11-18 07:35:14 +00:00
|
|
|
|
out = out.lstrip()
|
2015-12-31 04:10:59 +00:00
|
|
|
|
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
value = json.loads(out)
|
|
|
|
|
|
|
|
|
|
if name_provided and not full_value:
|
2020-10-19 21:57:22 +00:00
|
|
|
|
value = value["value"]
|
Add full support for 'output' command, and enable raise_on_error option
Add a general "raise_on_error" option to all terraform commands. If provided and
set to anything that evaluates to True, then TerraformCommandError (a subclass of
subprocess.CalledProcessError) will be raised if the returncode is not 0. The exception
object will have the following special proerties:
returncode: The returncode from the command, as in subprocess.CalledProcessError.
out: The contents of stdout if available, otherwise None
err: The contents of stderr if available, otherwise None
Terraform.output() no longer requires an argument for the output name; if omitted, it
returns a dict of all outputs, exactly as expected from 'terraform output -json'.
Terraform.output() now accepts an optional "full_value" option. If provided and True, and
an output name was provided, then the return value will be a dict with "value", "type",
and "sensitive" fields, exactly as expected from 'terraform output -json <output-name>'
Added tests for all of this new functionality...
2017-10-13 20:36:25 +00:00
|
|
|
|
|
|
|
|
|
return value
|
2015-12-31 04:10:59 +00:00
|
|
|
|
|
2016-11-18 07:35:14 +00:00
|
|
|
|
def read_state_file(self, file_path=None):
|
2020-10-19 21:57:22 +00:00
|
|
|
|
"""Read .tfstate file
|
|
|
|
|
|
2016-11-18 07:35:14 +00:00
|
|
|
|
:param file_path: relative path to working dir
|
|
|
|
|
:return: states file in dict type
|
|
|
|
|
"""
|
2015-12-31 04:10:59 +00:00
|
|
|
|
|
2020-10-19 21:57:22 +00:00
|
|
|
|
working_dir = self.working_dir or ""
|
2017-08-22 20:12:13 +00:00
|
|
|
|
|
2020-10-19 21:57:22 +00:00
|
|
|
|
file_path = file_path or self.state or ""
|
2015-12-31 04:10:59 +00:00
|
|
|
|
|
2016-11-18 07:35:14 +00:00
|
|
|
|
if not file_path:
|
2020-10-19 21:57:22 +00:00
|
|
|
|
backend_path = os.path.join(file_path, ".terraform", "terraform.tfstate")
|
2017-08-22 20:12:13 +00:00
|
|
|
|
|
|
|
|
|
if os.path.exists(os.path.join(working_dir, backend_path)):
|
|
|
|
|
file_path = backend_path
|
|
|
|
|
else:
|
2020-10-19 21:57:22 +00:00
|
|
|
|
file_path = os.path.join(file_path, "terraform.tfstate")
|
2015-12-31 04:10:59 +00:00
|
|
|
|
|
2017-08-22 20:12:13 +00:00
|
|
|
|
file_path = os.path.join(working_dir, file_path)
|
2015-12-31 04:10:59 +00:00
|
|
|
|
|
2016-11-18 07:35:14 +00:00
|
|
|
|
self.tfstate = Tfstate.load_file(file_path)
|
2016-12-20 10:53:01 +00:00
|
|
|
|
|
2019-06-25 18:53:39 +00:00
|
|
|
|
def set_workspace(self, workspace, *args, **kwargs):
|
2020-10-19 21:57:22 +00:00
|
|
|
|
"""Set workspace
|
|
|
|
|
|
2019-05-03 20:54:28 +00:00
|
|
|
|
:param workspace: the desired workspace.
|
2019-05-07 16:55:13 +00:00
|
|
|
|
:return: status
|
2019-05-03 20:54:28 +00:00
|
|
|
|
"""
|
2020-10-19 21:57:22 +00:00
|
|
|
|
return self.cmd("workspace", "select", workspace, *args, **kwargs)
|
2019-05-03 20:59:48 +00:00
|
|
|
|
|
2019-06-25 18:53:39 +00:00
|
|
|
|
def create_workspace(self, workspace, *args, **kwargs):
|
2020-10-19 21:57:22 +00:00
|
|
|
|
"""Create workspace
|
|
|
|
|
|
2019-05-03 20:59:48 +00:00
|
|
|
|
:param workspace: the desired workspace.
|
2019-05-07 16:55:13 +00:00
|
|
|
|
:return: status
|
2019-05-03 20:59:48 +00:00
|
|
|
|
"""
|
2020-10-19 21:57:22 +00:00
|
|
|
|
return self.cmd("workspace", "new", workspace, *args, **kwargs)
|
2019-05-08 17:55:53 +00:00
|
|
|
|
|
2019-06-25 18:53:39 +00:00
|
|
|
|
def delete_workspace(self, workspace, *args, **kwargs):
|
2020-10-19 21:57:22 +00:00
|
|
|
|
"""Delete workspace
|
|
|
|
|
|
2019-05-08 17:55:53 +00:00
|
|
|
|
:param workspace: the desired workspace.
|
|
|
|
|
:return: status
|
|
|
|
|
"""
|
2020-10-19 21:57:22 +00:00
|
|
|
|
return self.cmd("workspace", "delete", workspace, *args, **kwargs)
|
2019-05-03 20:59:48 +00:00
|
|
|
|
|
2019-06-25 18:53:39 +00:00
|
|
|
|
def show_workspace(self, **kwargs):
|
2020-10-19 21:57:22 +00:00
|
|
|
|
"""Show workspace, this command does not need the [DIR] part
|
|
|
|
|
|
2019-05-07 16:55:13 +00:00
|
|
|
|
:return: workspace
|
2019-05-03 20:59:48 +00:00
|
|
|
|
"""
|
2020-10-19 21:57:22 +00:00
|
|
|
|
return self.cmd("workspace", "show", **kwargs)
|
2019-05-03 20:54:28 +00:00
|
|
|
|
|
2016-12-20 10:53:01 +00:00
|
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
|
|
|
|
self.temp_var_files.clean_up()
|
|
|
|
|
|
|
|
|
|
|
2016-12-20 16:18:57 +00:00
|
|
|
|
class VariableFiles(object):
|
2016-12-20 10:53:01 +00:00
|
|
|
|
def __init__(self):
|
|
|
|
|
self.files = []
|
|
|
|
|
|
|
|
|
|
def create(self, variables):
|
2020-10-19 21:57:22 +00:00
|
|
|
|
with tempfile.NamedTemporaryFile(
|
|
|
|
|
"w+t", suffix=".tfvars.json", delete=False
|
|
|
|
|
) as temp:
|
|
|
|
|
logger.debug("%s is created", temp.name)
|
2016-12-20 10:53:01 +00:00
|
|
|
|
self.files.append(temp)
|
2020-10-19 21:57:22 +00:00
|
|
|
|
logger.debug("variables wrote to tempfile: %s", variables)
|
2016-12-20 10:53:01 +00:00
|
|
|
|
temp.write(json.dumps(variables))
|
|
|
|
|
file_name = temp.name
|
|
|
|
|
|
|
|
|
|
return file_name
|
|
|
|
|
|
|
|
|
|
def clean_up(self):
|
|
|
|
|
for f in self.files:
|
|
|
|
|
os.unlink(f.name)
|
|
|
|
|
|
|
|
|
|
self.files = []
|