Merge branch 'release/0.7.4'
This commit is contained in:
commit
16fd091da2
16 changed files with 517 additions and 188 deletions
4
.gitignore
vendored
4
.gitignore
vendored
|
@ -2,4 +2,6 @@
|
|||
*.tfstate.backup
|
||||
*.pyc
|
||||
*.egg-info
|
||||
.idea
|
||||
.idea
|
||||
.cache
|
||||
/.pypirc
|
||||
|
|
52
.travis.yml
Normal file
52
.travis.yml
Normal file
|
@ -0,0 +1,52 @@
|
|||
language: python
|
||||
python:
|
||||
- "2.7"
|
||||
# - "3.2"
|
||||
# - "3.3"
|
||||
# - "3.4"
|
||||
- "3.5"
|
||||
# - "3.5-dev" # 3.5 development branch
|
||||
# - "3.6-dev" # 3.6 development branch
|
||||
# - "nightly" # currently points to 3.7-dev
|
||||
# command to install dependencies
|
||||
before_install: 'sudo apt-get install unzip'
|
||||
before_script:
|
||||
- 'wget https://releases.hashicorp.com/terraform/0.7.11/terraform_0.7.11_linux_amd64.zip'
|
||||
- 'mkdir tf_bin'
|
||||
- 'unzip terraform_0.7.11_linux_amd64.zip -d tf_bin'
|
||||
|
||||
install:
|
||||
- "curl https://bootstrap.pypa.io/ez_setup.py -o - | python"
|
||||
- "pip install -r test/requirements.txt"
|
||||
- "sudo apt-get -y install pandoc"
|
||||
- "pip install pypandoc"
|
||||
- "pip install ."
|
||||
# command to run tests
|
||||
script:
|
||||
- "export PATH=$PATH:$PWD/tf_bin"
|
||||
- cd test
|
||||
- py.test
|
||||
- cd ..
|
||||
|
||||
deploy:
|
||||
# test pypi
|
||||
- provider: pypi
|
||||
distributions: sdist
|
||||
server: https://testpypi.python.org/pypi
|
||||
user: "beelit94"
|
||||
password:
|
||||
secure: "sWxc+p/gdq3k2WbUGNG2F4TukFNkTkvq6OPaiOvyfgWThYNk6/juRkMd8flmTbh0VGhcjFbpDLeSApb2kFhfiokYJSH1hOOcmXf8xzYH8/+R4DDEiGa5Y/pR9TBvYu4S8eJEfFUFfb1BBpapykj7o43hcaqMExBJIdVJU7aeoEAC1jQeTJh8wWwdJKHy2dNSM+6RVhk3e5+b0LfK7Bk5sU5P+YdEMj79MJU450J4OmZXWzJgvBN5/2QfVa5LrUD00nYuGuiBniz2lVevIHWjUYawUzpPsTa7F0s2WemG9YcV7U8u06xNjY9Ce3CTbxNhc7OIKq+TCkOgR3qZFXVJ8A87G+AT2iQ01VslQ4DJCxnJNTnpqojWnwf6MFL9O8ONioWYO32bhQFKOQ806ASHP4lNMRDKqx8hXtP5In7/r0SARKscv6Bas83rp+FESkKD5vWgkZJG+yx96LlwRLUhSVnVyb/nOJ++zt5RR3BvY2O4p9YAZY3Qt8TQihOdBQKnY3UXsMyNaE25+yvyNWpmyJiePRbTUd+cpLnycnqG9Ll8v6TpFXb6ahFMjlAFfJNQYlREfseClTHSRjZNxfsXGQCsJh6TZAq7jOB5hCk3q41eOUFWARxbyj8j59NBV8fSQrrGJJ9/VZKQeYiQlBB9KpK4PrnH84oeQ8i+VSbVr5w="
|
||||
on:
|
||||
branch: "release/**"
|
||||
tags: false
|
||||
condition: $TRAVIS_PYTHON_VERSION = "3.5"
|
||||
# production pypi
|
||||
- provider: pypi
|
||||
distributions: sdist
|
||||
user: "beelit94"
|
||||
password:
|
||||
secure: "QhCiTLrBvw/Uzt3eiLEmvMP3uHnayVCETqEDA+2+Q9vFavqj0CHA76zqYonBFqnh0a3HFCRIVVt+6ynpZ10kpQ3tAObIw+pY39ZPnpAhOjSpFzzMdpIF9Bhv9A93ng2iSESAZPAOwktHzUwjFx0Zvl0lSYD9rutHgttGgdU2CajiUtwTUhCTjOAVdR2Gm+15H808vzKWnMaKflXxZt+fkt279mQTYAtz6eBWtZwIKry/uAJCSrPSWtbi50O0HsWRMXLXWH5Jn/BVjWSDSM92DssUDq0D+tQyp4M5nQXJ9EyAvEdsKNLx3cvNruznh2ohI2jmcoIjwFiS6+wrEmUiXkP86iyzCSqL/EbcOG0xUh3vbfYtMBp7jENgD405+3SEhPY4PlqUmc+HDtB7FUcHz4y7wGWJRGyQzNnjJ6Tv0Ajdz5mfJubWVIvHjcRqkxTVtUKt50o00xZ62M0ZzQkDTIHQEsZly0XeHAgSvNzWkmjt9BiBrZ9OkoWVkRpSrCBy/EcpDNPCTSfSzOQ0Nq1ePFjkkW1n8QWDW9Pdb+/7/P2y9E2S8CT+nXBkRQeQiO86Qf1Ireg7k9TA5VYisVZ6bEXEc9UV0mAojpSsC7zWhVlbAoltN6ZbjKmqy/wqn2QIcJemcSie0JigzKpdw7l8FPT2lCRyTKlYLpRyKXzSkNI="
|
||||
on:
|
||||
branch: master
|
||||
tags: true
|
||||
condition: $TRAVIS_PYTHON_VERSION = "3.5"
|
3
DESCRIPTION.rst
Normal file
3
DESCRIPTION.rst
Normal file
|
@ -0,0 +1,3 @@
|
|||
Please see README at github_
|
||||
|
||||
.. _github: https://github.com/beelit94/python-terraform/blob/master/README.md
|
7
LICENSE.txt
Normal file
7
LICENSE.txt
Normal file
|
@ -0,0 +1,7 @@
|
|||
Copyright (c) 2016 beelit94@gmail.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
59
README.md
59
README.md
|
@ -3,7 +3,62 @@
|
|||
python-terraform is a python module provide a wrapper of `terraform` command line tool.
|
||||
`terraform` is a tool made by Hashicorp, please refer to https://terraform.io/
|
||||
|
||||
## This project is not stable yet
|
||||
### Status
|
||||
[![Build Status](https://travis-ci.org/beelit94/python-terraform.svg?branch=develop)](https://travis-ci.org/beelit94/python-terraform)
|
||||
|
||||
## Installation
|
||||
pip install git+https://github.com/beelit94/python-terraform.git@develop
|
||||
pip install python-terraform
|
||||
|
||||
## Usage
|
||||
For any terraform command
|
||||
|
||||
def cmd(self, cmd, *args, **kwargs):
|
||||
"""
|
||||
run a terraform command, if success, will try to read state file
|
||||
:param cmd: command and sub-command of terraform, seperated with space
|
||||
refer to https://www.terraform.io/docs/commands/index.html
|
||||
: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)
|
||||
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
|
||||
:return: ret_code, out, err
|
||||
|
||||
For apply/destroy method, the flag options, like, `-no-color` or `-force`
|
||||
have been implemented as boolean argument. simply use `is_no_color=True/False` for
|
||||
apply/destroy method
|
||||
|
||||
|
||||
## Examples
|
||||
### Have a test.tf file under folder "/home/test"
|
||||
#### apply with variables a=b, c=d, refresh=False, no color in the output
|
||||
In shell:
|
||||
|
||||
cd /home/test
|
||||
terraform apply -var='a=b' -var='c=d' -refresh=false -no-color
|
||||
|
||||
In python-terraform:
|
||||
|
||||
from python_terraform import Terraform
|
||||
tf = terraform(working_dir='/home/test')
|
||||
tf.apply(is_no_color=True, refresh=False, var={'a':'b', 'c':'d'})
|
||||
#### taint command, allow-missing and no color
|
||||
In shell:
|
||||
|
||||
cd /home/test
|
||||
terraform taint -allow-missing -no-color
|
||||
|
||||
In python-terraform:
|
||||
|
||||
from python_terraform import Terraform
|
||||
tf = terraform(working_dir='/home/test')
|
||||
tf.cmd('taint', allow_missing=IsFlagged, no_color=IsFlagged)
|
||||
|
||||
|
||||
|
||||
|
2
VERSION
2
VERSION
|
@ -1 +1 @@
|
|||
0.0.4
|
||||
0.7.4
|
|
@ -3,180 +3,234 @@ import os
|
|||
import json
|
||||
import logging
|
||||
|
||||
from python_terraform.tfstate import Tfstate
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class IsFlagged:
|
||||
pass
|
||||
|
||||
|
||||
class IsNotFlagged:
|
||||
pass
|
||||
|
||||
|
||||
class Terraform:
|
||||
def __init__(self, targets=None, state='terraform.tfstate', variables=None):
|
||||
"""
|
||||
Wrapper of terraform command line tool
|
||||
https://www.terraform.io/
|
||||
"""
|
||||
|
||||
def __init__(self, working_dir=None,
|
||||
targets=None,
|
||||
state=None,
|
||||
variables=None,
|
||||
parallelism=None,
|
||||
var_file=None,
|
||||
terraform_bin_path=None):
|
||||
"""
|
||||
:param working_dir: the folder of the working folder, if not given, will be where python
|
||||
:param targets: list of target
|
||||
:param state: path of state file relative to working folder
|
||||
:param variables: variables for apply/destroy/plan command
|
||||
:param parallelism: parallelism for apply/destroy command
|
||||
:param var_file: if specified, variables will not be used
|
||||
:param terraform_bin_path: binary path of terraform
|
||||
"""
|
||||
self.working_dir = working_dir
|
||||
self.state = state
|
||||
self.targets = [] if targets is None else targets
|
||||
self.variables = dict() if variables is None else variables
|
||||
|
||||
self.state_filename = state
|
||||
self.state_data = dict()
|
||||
self.parallelism = 50
|
||||
self.parallelism = parallelism
|
||||
self.terraform_bin_path = terraform_bin_path \
|
||||
if terraform_bin_path else 'terraform'
|
||||
self.var_file = var_file
|
||||
|
||||
def apply(self, targets=None, variables=None, **kargs):
|
||||
# store the tfstate data
|
||||
self.tfstate = dict()
|
||||
|
||||
def apply(self,
|
||||
dir=None,
|
||||
is_no_color=True,
|
||||
is_input=False,
|
||||
**kwargs):
|
||||
"""
|
||||
refer to https://terraform.io/docs/commands/apply.html
|
||||
:param variables: variables in dict type
|
||||
:param targets: targets in list
|
||||
:raise RuntimeError when return code is not zero
|
||||
:param is_no_color: if True, add flag -no-color
|
||||
:param is_input: if True, add option -input=true
|
||||
:param dir: folder relative to working folder
|
||||
:param kwargs: same as kwags in method 'cmd'
|
||||
:returns return_code, stdout, stderr
|
||||
"""
|
||||
variables = self.variables if variables is None else variables
|
||||
targets = self.targets if targets is None else targets
|
||||
|
||||
parameters = []
|
||||
parameters += self._generate_targets(targets)
|
||||
parameters += self._generate_var_string(variables)
|
||||
parameters += self._gen_param_string(kargs)
|
||||
args, option_dict = self._create_cmd_args(is_input,
|
||||
is_no_color,
|
||||
dir,
|
||||
kwargs)
|
||||
|
||||
parameters = \
|
||||
['terraform', 'apply', '-state=%s' % self.state_filename] + parameters
|
||||
return self.cmd('apply', *args, **option_dict)
|
||||
|
||||
cmd = ' '.join(parameters)
|
||||
return self._run_cmd(cmd)
|
||||
def _create_cmd_args(self, is_input, is_no_color, dir, kwargs):
|
||||
option_dict = dict()
|
||||
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
|
||||
if is_no_color:
|
||||
option_dict['no_color'] = IsFlagged
|
||||
option_dict['input'] = is_input
|
||||
option_dict.update(kwargs)
|
||||
args = [dir] if dir else []
|
||||
return args, option_dict
|
||||
|
||||
def _gen_param_string(self, kargs):
|
||||
params = []
|
||||
for key, value in kargs.items():
|
||||
if value:
|
||||
params += ['-%s=%s' % (key, value)]
|
||||
else:
|
||||
params += ['-%s' % key]
|
||||
return params
|
||||
def destroy(self, working_dir=None, is_force=True,
|
||||
is_no_color=True, is_input=False, **kwargs):
|
||||
"""
|
||||
refer to https://www.terraform.io/docs/commands/destroy.html
|
||||
:raise RuntimeError when return code is not zero
|
||||
:return: ret_code, stdout, stderr
|
||||
"""
|
||||
|
||||
def _run_cmd(self, cmd):
|
||||
log.debug('command: ' + cmd)
|
||||
args, option_dict = self._create_cmd_args(is_input,
|
||||
is_no_color,
|
||||
working_dir,
|
||||
kwargs)
|
||||
if is_force:
|
||||
option_dict['force'] = IsFlagged
|
||||
|
||||
p = subprocess.Popen(
|
||||
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
|
||||
return self.cmd('destroy', *args, **option_dict)
|
||||
|
||||
def generate_cmd_string(self, cmd, *args, **kwargs):
|
||||
"""
|
||||
for any generate_cmd_string doesn't written as public method of terraform
|
||||
|
||||
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:
|
||||
tf.generate_cmd_string('apply', the_folder, no_color=IsFlagged, var={'a':'b', 'c':'d'})
|
||||
|
||||
:param cmd: command and sub-command of terraform, seperated with space
|
||||
refer to https://www.terraform.io/docs/commands/index.html
|
||||
:param args: arguments of a command
|
||||
:param kwargs: same as kwags in method 'cmd'
|
||||
:return: string of valid terraform command
|
||||
"""
|
||||
cmds = cmd.split()
|
||||
cmds = [self.terraform_bin_path] + cmds
|
||||
|
||||
for k, v in kwargs.items():
|
||||
if '_' in k:
|
||||
k = k.replace('_', '-')
|
||||
|
||||
if type(v) is list:
|
||||
for sub_v in v:
|
||||
cmds += ['-{k}={v}'.format(k=k, v=sub_v)]
|
||||
continue
|
||||
|
||||
if type(v) is dict:
|
||||
for sub_k, sub_v in v.items():
|
||||
cmds += ["-{k}='{var_k}={var_v}'".format(k=k,
|
||||
var_k=sub_k,
|
||||
var_v=sub_v)]
|
||||
continue
|
||||
|
||||
# simple flag,
|
||||
if v is IsFlagged:
|
||||
cmds += ['-{k}'.format(k=k)]
|
||||
continue
|
||||
|
||||
if v is IsNotFlagged:
|
||||
continue
|
||||
|
||||
if not v:
|
||||
continue
|
||||
|
||||
if type(v) is bool:
|
||||
v = 'true' if v else 'false'
|
||||
|
||||
cmds += ['-{k}={v}'.format(k=k, v=v)]
|
||||
|
||||
cmds += args
|
||||
cmd = ' '.join(cmds)
|
||||
return cmd
|
||||
|
||||
def cmd(self, cmd, *args, **kwargs):
|
||||
"""
|
||||
run a terraform command, if success, will try to read state file
|
||||
:param cmd: command and sub-command of terraform, seperated with space
|
||||
refer to https://www.terraform.io/docs/commands/index.html
|
||||
: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)
|
||||
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
|
||||
:return: ret_code, out, err
|
||||
"""
|
||||
cmd_string = self.generate_cmd_string(cmd, *args, **kwargs)
|
||||
log.debug('command: {c}'.format(c=cmd_string))
|
||||
|
||||
working_folder = self.working_dir if self.working_dir else None
|
||||
|
||||
p = subprocess.Popen(cmd_string, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, shell=True,
|
||||
cwd=working_folder)
|
||||
out, err = p.communicate()
|
||||
ret_code = p.returncode
|
||||
log.debug('output: ' + out)
|
||||
log.debug('output: {o}'.format(o=out))
|
||||
|
||||
if ret_code == 0:
|
||||
log.debug('error: ' + err)
|
||||
self.read_state_file()
|
||||
return ret_code, out, err
|
||||
else:
|
||||
log.warn('error: {e}'.format(e=err))
|
||||
return ret_code, out.decode('utf-8'), err.decode('utf-8')
|
||||
|
||||
def destroy(self, targets=None, variables=None, **kwargs):
|
||||
variables = self.variables if variables is None else variables
|
||||
targets = self.targets if targets is None else targets
|
||||
def output(self, name):
|
||||
"""
|
||||
https://www.terraform.io/docs/commands/output.html
|
||||
:param name: name of output
|
||||
:return: output value
|
||||
"""
|
||||
ret, out, err = self.cmd('output', name, json=IsFlagged)
|
||||
|
||||
parameters = []
|
||||
parameters += self._generate_targets(targets)
|
||||
parameters += self._generate_var_string(variables)
|
||||
log.debug('output raw string: {0}'.format(out))
|
||||
if ret != 0:
|
||||
return None
|
||||
out = out.lstrip()
|
||||
|
||||
parameters = \
|
||||
['terraform', 'destroy', '-force', '-state=%s' % self.state_filename] + \
|
||||
parameters
|
||||
cmd = ' '.join(parameters)
|
||||
return self._run_cmd(cmd)
|
||||
output_dict = json.loads(out)
|
||||
return output_dict['value']
|
||||
|
||||
def refresh(self, targets=None, variables=None):
|
||||
variables = self.variables if variables is None else variables
|
||||
targets = self.targets if targets is None else targets
|
||||
|
||||
parameters = []
|
||||
parameters += self._generate_targets(targets)
|
||||
parameters += self._generate_var_string(variables)
|
||||
parameters = \
|
||||
['terraform', 'refresh', '-state=%s' % self.state_filename] + \
|
||||
parameters
|
||||
cmd = ' '.join(parameters)
|
||||
return self._run_cmd(cmd)
|
||||
|
||||
def read_state_file(self):
|
||||
def read_state_file(self, file_path=None):
|
||||
"""
|
||||
read .tfstate file
|
||||
:param file_path: relative path to working dir
|
||||
:return: states file in dict type
|
||||
"""
|
||||
if os.path.exists(self.state_filename):
|
||||
with open(self.state_filename) as f:
|
||||
json_data = json.load(f)
|
||||
self.state_data = json_data
|
||||
log.debug("state_data=%s" % str(self.state_data))
|
||||
return json_data
|
||||
|
||||
return dict()
|
||||
|
||||
def is_any_aws_instance_alive(self):
|
||||
self.refresh()
|
||||
if not os.path.exists(self.state_filename):
|
||||
log.debug("can't find %s " % self.state_data)
|
||||
return False
|
||||
|
||||
self.read_state_file()
|
||||
try:
|
||||
main_module = self._get_main_module()
|
||||
for resource_key, info in main_module['resources'].items():
|
||||
if 'aws_instance' in resource_key:
|
||||
log.debug("%s is found when read state" % resource_key)
|
||||
return True
|
||||
log.debug("no aws_instance found in resource key")
|
||||
return False
|
||||
except KeyError as err:
|
||||
log.debug(str(err))
|
||||
return False
|
||||
except TypeError as err:
|
||||
log.debug(str(err))
|
||||
return False
|
||||
|
||||
def _get_main_module(self):
|
||||
return self.state_data['modules'][0]
|
||||
|
||||
def get_aws_instances(self):
|
||||
instances = dict()
|
||||
|
||||
try:
|
||||
main_module = self._get_main_module()
|
||||
for resource_key, info in main_module['resources'].items():
|
||||
if 'aws_instance' in resource_key:
|
||||
instances[resource_key] = info
|
||||
except KeyError:
|
||||
return instances
|
||||
except TypeError:
|
||||
return instances
|
||||
|
||||
return instances
|
||||
|
||||
def get_aws_instance(self, resource_name):
|
||||
"""
|
||||
:param resource_name:
|
||||
name of terraform resource, make source count is attached
|
||||
:return: return None if not exist, dict type if exist
|
||||
"""
|
||||
try:
|
||||
return self.get_aws_instances()[resource_name]
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
def get_output_value(self, output_name):
|
||||
"""
|
||||
|
||||
:param output_name:
|
||||
:return:
|
||||
"""
|
||||
try:
|
||||
main_module = self._get_main_module()
|
||||
return main_module['outputs'][output_name]
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _generate_var_string(d):
|
||||
str_t = []
|
||||
for k, v in d.iteritems():
|
||||
str_t += ['-var'] + ["%s=%s" % (k, v)]
|
||||
|
||||
return str_t
|
||||
|
||||
@staticmethod
|
||||
def _generate_targets(targets):
|
||||
str_t = []
|
||||
for t in targets:
|
||||
str_t += ['-target=%s' % t]
|
||||
return str_t
|
||||
if not file_path:
|
||||
file_path = self.state
|
||||
|
||||
if not file_path:
|
||||
file_path = 'terraform.tfstate'
|
||||
|
||||
if self.working_dir:
|
||||
file_path = os.path.join(self.working_dir, file_path)
|
||||
|
||||
self.tfstate = Tfstate.load_file(file_path)
|
||||
|
|
31
python_terraform/tfstate.py
Normal file
31
python_terraform/tfstate.py
Normal file
|
@ -0,0 +1,31 @@
|
|||
import json
|
||||
import os
|
||||
import logging
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Tfstate(object):
|
||||
def __init__(self, data=None):
|
||||
self.tfstate_file = None
|
||||
self.native_data = data
|
||||
if data:
|
||||
self.__dict__ = data
|
||||
|
||||
@staticmethod
|
||||
def load_file(file_path):
|
||||
"""
|
||||
Read the tfstate file and load its contents, parses then as JSON and put the result into the object
|
||||
"""
|
||||
log.debug('read data from {0}'.format(file_path))
|
||||
if os.path.exists(file_path):
|
||||
with open(file_path) as f:
|
||||
json_data = json.load(f)
|
||||
|
||||
tf_state = Tfstate(json_data)
|
||||
tf_state.tfstate_file = file_path
|
||||
return tf_state
|
||||
|
||||
log.warn('{0} is not exist'.format(file_path))
|
||||
|
||||
return Tfstate()
|
2
setup.cfg
Normal file
2
setup.cfg
Normal file
|
@ -0,0 +1,2 @@
|
|||
[wheel]
|
||||
universal = 1
|
21
setup.py
21
setup.py
|
@ -1,11 +1,16 @@
|
|||
"""
|
||||
My Tool does one thing, and one thing well.
|
||||
This is a python module provide a wrapper of terraform command line tool
|
||||
"""
|
||||
from distutils.core import setup
|
||||
from setuptools import setup
|
||||
import os
|
||||
|
||||
dependencies = []
|
||||
module_name = 'python-terraform'
|
||||
short_description = 'This is a python module provide a wrapper ' \
|
||||
'of terraform command line tool'
|
||||
|
||||
with open('DESCRIPTION.rst') as f:
|
||||
long_description = f.read()
|
||||
|
||||
|
||||
def get_version():
|
||||
|
@ -22,15 +27,13 @@ setup(
|
|||
name=module_name,
|
||||
version=get_version(),
|
||||
url='https://github.com/beelit94/python-terraform',
|
||||
license='BSD',
|
||||
license='MIT',
|
||||
author='Freddy Tan',
|
||||
author_email='beelit94@gmail.com',
|
||||
description='This is a python module provide a wrapper of terraform command line tool',
|
||||
long_description=__doc__,
|
||||
description=short_description,
|
||||
long_description=long_description,
|
||||
packages=['python_terraform'],
|
||||
include_package_data=True,
|
||||
package_data={},
|
||||
zip_safe=False,
|
||||
platforms='any',
|
||||
install_requires=dependencies,
|
||||
classifiers=[
|
||||
|
@ -44,11 +47,11 @@ setup(
|
|||
# 'Development Status :: 7 - Inactive',
|
||||
'Environment :: Console',
|
||||
'Intended Audience :: Developers',
|
||||
'License :: OSI Approved :: BSD License',
|
||||
'License :: OSI Approved :: MIT License',
|
||||
'Operating System :: POSIX',
|
||||
'Operating System :: MacOS',
|
||||
'Operating System :: Unix',
|
||||
'Operating System :: Windows',
|
||||
# 'Operating System :: Windows',
|
||||
'Programming Language :: Python',
|
||||
'Programming Language :: Python :: 2',
|
||||
'Programming Language :: Python :: 3',
|
||||
|
|
8
test/apply_tf/test.tf
Normal file
8
test/apply_tf/test.tf
Normal file
|
@ -0,0 +1,8 @@
|
|||
variable "test_var" {}
|
||||
|
||||
provider "archive" {
|
||||
}
|
||||
|
||||
output "test_output" {
|
||||
value = "${var.test_var}"
|
||||
}
|
1
test/requirements.txt
Normal file
1
test/requirements.txt
Normal file
|
@ -0,0 +1 @@
|
|||
pytest
|
24
test/test.tf
24
test/test.tf
|
@ -1,24 +0,0 @@
|
|||
variable "access_key" {}
|
||||
variable "secret_key" {}
|
||||
|
||||
provider "aws" {
|
||||
access_key = "${var.access_key}"
|
||||
secret_key = "${var.secret_key}"
|
||||
region = "us-west-2"
|
||||
}
|
||||
|
||||
resource "aws_instance" "ubuntu-1404" {
|
||||
ami = "ami-9abea4fb"
|
||||
instance_type = "t2.micro"
|
||||
security_groups = ["terraform-salty-splunk"]
|
||||
tags {
|
||||
Name = "python-terraform-test"
|
||||
}
|
||||
// key_name = "${aws_key_pair.key.key_name}"
|
||||
// connection {
|
||||
// type = "ssh"
|
||||
// user = "ubuntu"
|
||||
// key_file = "${var.key_path}"
|
||||
// timeout = "10m"
|
||||
// }
|
||||
}
|
|
@ -1,15 +1,88 @@
|
|||
from python_terraform import Terraform
|
||||
from python_terraform import *
|
||||
import pytest
|
||||
import os
|
||||
import logging
|
||||
import re
|
||||
|
||||
logging.basicConfig(level=logging.WARN)
|
||||
|
||||
|
||||
STRING_CASES = [
|
||||
[
|
||||
lambda x: x.generate_cmd_string('apply', 'the_folder',
|
||||
no_color=IsFlagged,
|
||||
var={'a': 'b', 'c': 'd'}),
|
||||
"terraform apply -var='a=b' -var='c=d' -no-color the_folder"
|
||||
],
|
||||
[
|
||||
lambda x: x.generate_cmd_string('push', 'path',
|
||||
var={'a': 'b'}, vcs=True,
|
||||
token='token',
|
||||
atlas_address='url'),
|
||||
"terraform push -var='a=b' -vcs=true -token=token -atlas-address=url path"
|
||||
],
|
||||
]
|
||||
|
||||
CMD_CASES = [
|
||||
['method', 'expected_output'],
|
||||
[
|
||||
[
|
||||
lambda x: x.cmd('plan', 'apply_tf', no_color=IsFlagged, var={'test_var': 'test'}) ,
|
||||
"doesn't need to do anything"
|
||||
]
|
||||
]
|
||||
]
|
||||
|
||||
|
||||
class TestTerraform:
|
||||
def test_apply_and_destory(self):
|
||||
def teardown_method(self, method):
|
||||
""" teardown any state that was previously setup with a setup_method
|
||||
call.
|
||||
"""
|
||||
|
||||
def purge(dir, pattern):
|
||||
for f in os.listdir(dir):
|
||||
if re.search(pattern, f):
|
||||
if os.path.isfile(f):
|
||||
os.remove(os.path.join(dir, f))
|
||||
|
||||
purge('.', '.tfstate')
|
||||
|
||||
@pytest.mark.parametrize([
|
||||
"method", "expected"
|
||||
], STRING_CASES)
|
||||
def test_generate_cmd_string(self, method, expected):
|
||||
tf = Terraform()
|
||||
ret_code, out, err = tf.apply()
|
||||
result = method(tf)
|
||||
|
||||
print out
|
||||
print err
|
||||
# assert ret_code, 0
|
||||
strs = expected.split()
|
||||
for s in strs:
|
||||
assert s in result
|
||||
|
||||
ret_code, out, err = tf.destroy()
|
||||
@pytest.mark.parametrize(*CMD_CASES)
|
||||
def test_cmd(self, method, expected_output):
|
||||
tf = Terraform()
|
||||
ret, out, err = method(tf)
|
||||
assert expected_output in out
|
||||
assert ret == 0
|
||||
|
||||
assert ret_code, 0
|
||||
def test_state_data(self):
|
||||
tf = Terraform(working_dir='test_tfstate_file', state='tfstate.test')
|
||||
tf.read_state_file()
|
||||
assert tf.tfstate.modules[0]['path'] == ['root']
|
||||
|
||||
def test_apply(self):
|
||||
tf = Terraform(working_dir='apply_tf', variables={'test_var': 'test'})
|
||||
ret, out, err = tf.apply(var={'test_var': 'test2'})
|
||||
assert ret == 0
|
||||
|
||||
def test_get_output(self):
|
||||
tf = Terraform(working_dir='apply_tf', variables={'test_var': 'test'})
|
||||
tf.apply()
|
||||
assert tf.output('test_output') == 'test'
|
||||
|
||||
def test_destroy(self):
|
||||
tf = Terraform(working_dir='apply_tf', variables={'test_var': 'test'})
|
||||
ret, out, err = tf.destroy()
|
||||
assert ret == 0
|
||||
assert 'Destroy complete! Resources: 0 destroyed.' in out
|
||||
|
|
62
test/test_tfstate_file/tfstate.test
Normal file
62
test/test_tfstate_file/tfstate.test
Normal file
|
@ -0,0 +1,62 @@
|
|||
{
|
||||
"version": 3,
|
||||
"terraform_version": "0.7.10",
|
||||
"serial": 0,
|
||||
"lineage": "d03ecdf7-8be0-4593-a952-1d8127875119",
|
||||
"modules": [
|
||||
{
|
||||
"path": [
|
||||
"root"
|
||||
],
|
||||
"outputs": {},
|
||||
"resources": {
|
||||
"aws_instance.ubuntu-1404": {
|
||||
"type": "aws_instance",
|
||||
"depends_on": [],
|
||||
"primary": {
|
||||
"id": "i-84d10edb",
|
||||
"attributes": {
|
||||
"ami": "ami-9abea4fb",
|
||||
"associate_public_ip_address": "true",
|
||||
"availability_zone": "us-west-2b",
|
||||
"disable_api_termination": "false",
|
||||
"ebs_block_device.#": "0",
|
||||
"ebs_optimized": "false",
|
||||
"ephemeral_block_device.#": "0",
|
||||
"iam_instance_profile": "",
|
||||
"id": "i-84d10edb",
|
||||
"instance_state": "running",
|
||||
"instance_type": "t2.micro",
|
||||
"key_name": "",
|
||||
"monitoring": "false",
|
||||
"network_interface_id": "eni-46544f07",
|
||||
"private_dns": "ip-172-31-25-244.us-west-2.compute.internal",
|
||||
"private_ip": "172.31.25.244",
|
||||
"public_dns": "ec2-35-162-30-219.us-west-2.compute.amazonaws.com",
|
||||
"public_ip": "35.162.30.219",
|
||||
"root_block_device.#": "1",
|
||||
"root_block_device.0.delete_on_termination": "true",
|
||||
"root_block_device.0.iops": "100",
|
||||
"root_block_device.0.volume_size": "8",
|
||||
"root_block_device.0.volume_type": "gp2",
|
||||
"security_groups.#": "0",
|
||||
"source_dest_check": "true",
|
||||
"subnet_id": "subnet-d2c0f0a6",
|
||||
"tags.%": "0",
|
||||
"tenancy": "default",
|
||||
"vpc_security_group_ids.#": "1",
|
||||
"vpc_security_group_ids.619359045": "sg-9fc7dcfd"
|
||||
},
|
||||
"meta": {
|
||||
"schema_version": "1"
|
||||
},
|
||||
"tainted": false
|
||||
},
|
||||
"deposed": [],
|
||||
"provider": ""
|
||||
}
|
||||
},
|
||||
"depends_on": []
|
||||
}
|
||||
]
|
||||
}
|
Loading…
Reference in a new issue