Skip to content

Commit d23f85a

Browse files
committed
Merge branch 'release/0.9.0'
2 parents 3ae7f87 + 2e9c6d3 commit d23f85a

File tree

7 files changed

+73
-31
lines changed

7 files changed

+73
-31
lines changed

.bumpversion.cfg

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[bumpversion]
2-
current_version = 0.8.6
2+
current_version = 0.9.0
33
commit = True
44
tag = False
55

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,5 @@
66
.cache
77
/.pypirc
88
/.tox/
9+
.dropbox
10+
Icon

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ python:
55
- '3.6'
66
before_install: sudo apt-get install unzip
77
before_script:
8-
- export TFVER=0.9.5
8+
- export TFVER=0.10.0
99
- export TFURL=https://releases.hashicorp.com/terraform/
1010
- TFURL+=$TFVER
1111
- TFURL+="/terraform_"

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Changelog
2+
## [0.9.0]
3+
### Fixed
4+
1. [#12] Output function doesn't accept parameter 'module'
5+
1. [#16] Handle empty space/special characters when passing string to command line options
6+
1. Tested with terraform 0.10.0

python_terraform/__init__.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def __init__(self, working_dir=None,
3535
var_file=None,
3636
terraform_bin_path=None,
3737
is_env_vars_included=True):
38-
"""
38+
"""
3939
:param working_dir: the folder of the working folder, if not given,
4040
will be current working folder
4141
:param targets: list of target
@@ -49,7 +49,7 @@ def __init__(self, working_dir=None,
4949
could be string or list, list stands for multiple -var-file option
5050
:param terraform_bin_path: binary path of terraform
5151
:type is_env_vars_included: bool
52-
:param is_env_vars_included: included env variables when calling terraform cmd
52+
:param is_env_vars_included: included env variables when calling terraform cmd
5353
"""
5454
self.is_env_vars_included = is_env_vars_included
5555
self.working_dir = working_dir
@@ -192,8 +192,7 @@ def generate_cmd_string(self, cmd, *args, **kwargs):
192192
cmds += ['-{k}={v}'.format(k=k, v=v)]
193193

194194
cmds += args
195-
cmd = ' '.join(cmds)
196-
return cmd
195+
return cmds
197196

198197
def cmd(self, cmd, *args, **kwargs):
199198
"""
@@ -224,16 +223,16 @@ def cmd(self, cmd, *args, **kwargs):
224223
stderr = sys.stderr
225224
stdout = sys.stdout
226225

227-
cmd_string = self.generate_cmd_string(cmd, *args, **kwargs)
228-
log.debug('command: {c}'.format(c=cmd_string))
226+
cmds = self.generate_cmd_string(cmd, *args, **kwargs)
227+
log.debug('command: {c}'.format(c=' '.join(cmds)))
229228

230229
working_folder = self.working_dir if self.working_dir else None
231230

232231
environ_vars = {}
233232
if self.is_env_vars_included:
234233
environ_vars = os.environ.copy()
235234

236-
p = subprocess.Popen(cmd_string, stdout=stdout, stderr=stderr, shell=True,
235+
p = subprocess.Popen(cmds, stdout=stdout, stderr=stderr,
237236
cwd=working_folder, env=environ_vars)
238237
out, err = p.communicate()
239238
ret_code = p.returncode
@@ -250,13 +249,15 @@ def cmd(self, cmd, *args, **kwargs):
250249
else:
251250
return ret_code, None, None
252251

253-
def output(self, name):
252+
def output(self, name, *args, **kwargs):
254253
"""
255254
https://www.terraform.io/docs/commands/output.html
256255
:param name: name of output
257256
:return: output value
258257
"""
259-
ret, out, err = self.cmd('output', name, json=IsFlagged)
258+
259+
ret, out, err = self.cmd(
260+
'output', name, json=IsFlagged, *args, **kwargs)
260261

261262
log.debug('output raw string: {0}'.format(out))
262263
if ret != 0:

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
setup(
2222
name=module_name,
23-
version='0.8.6',
23+
version='0.9.0',
2424
url='https://github.com/beelit94/python-terraform',
2525
license='MIT',
2626
author='Freddy Tan',

test/test_terraform.py

Lines changed: 52 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,13 @@
88
import logging
99
import re
1010
import shutil
11+
import fnmatch
1112

1213
logging.basicConfig(level=logging.DEBUG)
1314
root_logger = logging.getLogger()
14-
# ch = logging.StreamHandler(sys.stdout)
15-
# root_logger.addHandler(ch)
1615
current_path = os.path.dirname(os.path.realpath(__file__))
1716

17+
FILE_PATH_WITH_SPACE_AND_SPACIAL_CHARS = "test 'test.out!"
1818
STRING_CASES = [
1919
[
2020
lambda x: x.generate_cmd_string('apply', 'the_folder',
@@ -30,20 +30,30 @@
3030
]
3131

3232
CMD_CASES = [
33-
['method', 'expected_output', 'expected_ret_code', 'expected_logs'],
33+
['method', 'expected_output', 'expected_ret_code', 'expected_logs', 'folder'],
3434
[
3535
[
3636
lambda x: x.cmd('plan', 'var_to_output', no_color=IsFlagged, var={'test_var': 'test'}) ,
3737
"doesn't need to do anything",
3838
0,
39-
''
39+
'',
40+
'var_to_output'
4041
],
4142
# try import aws instance
4243
[
4344
lambda x: x.cmd('import', 'aws_instance.foo', 'i-abcd1234', no_color=IsFlagged),
4445
'',
4546
1,
46-
'command: terraform import -no-color aws_instance.foo i-abcd1234'
47+
'command: terraform import -no-color aws_instance.foo i-abcd1234',
48+
''
49+
],
50+
# test with space and special character in file path
51+
[
52+
lambda x: x.cmd('plan', 'var_to_output', out=FILE_PATH_WITH_SPACE_AND_SPACIAL_CHARS),
53+
'',
54+
0,
55+
'',
56+
'var_to_output'
4757
]
4858
]
4959
]
@@ -71,9 +81,10 @@ def string_logger(request):
7181

7282
def td():
7383
root_logger.removeHandler(handler)
84+
log_stream.close()
7485

7586
request.addfinalizer(td)
76-
return log_stream
87+
return lambda: str(log_stream.getvalue())
7788

7889

7990
class TestTerraform(object):
@@ -83,12 +94,17 @@ def teardown_method(self, method):
8394
"""
8495

8596
def purge(dir, pattern):
86-
for f in os.listdir(dir):
87-
if re.search(pattern, f):
88-
if os.path.isfile(f):
89-
os.remove(os.path.join(dir, f))
90-
91-
purge('.', '.tfstate')
97+
for root, dirnames, filenames in os.walk(dir):
98+
for filename in fnmatch.filter(filenames, pattern):
99+
f = os.path.join(root, filename)
100+
os.remove(f)
101+
for dirname in fnmatch.filter(dirnames, pattern):
102+
d = os.path.join(root, dirname)
103+
shutil.rmtree(d)
104+
105+
purge('.', '*.tfstate')
106+
purge('.', '*.terraform')
107+
purge('.', FILE_PATH_WITH_SPACE_AND_SPACIAL_CHARS)
92108

93109
@pytest.mark.parametrize([
94110
"method", "expected"
@@ -102,10 +118,11 @@ def test_generate_cmd_string(self, method, expected):
102118
assert s in result
103119

104120
@pytest.mark.parametrize(*CMD_CASES)
105-
def test_cmd(self, method, expected_output, expected_ret_code, expected_logs, string_logger):
121+
def test_cmd(self, method, expected_output, expected_ret_code, expected_logs, string_logger, folder):
106122
tf = Terraform(working_dir=current_path)
123+
tf.init(folder)
107124
ret, out, err = method(tf)
108-
logs = str(string_logger.getvalue())
125+
logs = string_logger()
109126
logs = logs.replace('\n', '')
110127
assert expected_output in out
111128
assert expected_ret_code == ret
@@ -123,6 +140,8 @@ def test_cmd(self, method, expected_output, expected_ret_code, expected_logs, st
123140
])
124141
def test_apply(self, folder, variables, var_files, expected_output, options):
125142
tf = Terraform(working_dir=current_path, variables=variables, var_file=var_files)
143+
# after 0.10.0 we always need to init
144+
tf.init(folder)
126145
ret, out, err = tf.apply(folder, **options)
127146
assert ret == 0
128147
assert expected_output in out.replace('\n', '').replace(' ', '')
@@ -160,20 +179,36 @@ def test_pre_load_state_data(self):
160179
)
161180
def test_override_default(self, folder, variables):
162181
tf = Terraform(working_dir=current_path, variables=variables)
182+
tf.init(folder)
163183
ret, out, err = tf.apply(folder, var={'test_var': 'test2'},
164184
no_color=IsNotFlagged)
165185
out = out.replace('\n', '')
166186
assert '\x1b[0m\x1b[1m\x1b[32mApply' in out
167187
out = tf.output('test_output')
168188
assert 'test2' in out
169189

170-
def test_get_output(self):
190+
@pytest.mark.parametrize(
191+
("param"),
192+
[
193+
({}),
194+
({'module': 'test2'}),
195+
]
196+
)
197+
def test_output(self, param, string_logger):
171198
tf = Terraform(working_dir=current_path, variables={'test_var': 'test'})
199+
tf.init('var_to_output')
172200
tf.apply('var_to_output')
173-
assert tf.output('test_output') == 'test'
201+
result = tf.output('test_output', **param)
202+
regex = re.compile("terraform output (-module=test2 -json|-json -module=test2) test_output")
203+
log_str = string_logger()
204+
if param:
205+
assert re.search(regex, log_str), log_str
206+
else:
207+
assert result == 'test'
174208

175209
def test_destroy(self):
176210
tf = Terraform(working_dir=current_path, variables={'test_var': 'test'})
211+
tf.init('var_to_output')
177212
ret, out, err = tf.destroy('var_to_output')
178213
assert ret == 0
179214
assert 'Destroy complete! Resources: 0 destroyed.' in out
@@ -197,6 +232,4 @@ def test_fmt(self, fmt_test_file):
197232
def test_import(self, string_logger):
198233
tf = Terraform(working_dir=current_path)
199234
tf.import_cmd('aws_instance.foo', 'i-abc1234', no_color=IsFlagged)
200-
logs = string_logger.getvalue()
201-
print(logs)
202-
assert 'command: terraform import -no-color aws_instance.foo i-abc1234' in logs
235+
assert 'command: terraform import -no-color aws_instance.foo i-abc1234' in string_logger()

0 commit comments

Comments
 (0)