Skip to content

Commit

Permalink
[Resolve #870] Bugfix in _call_sceptre_handler
Browse files Browse the repository at this point in the history
Before this, the _call_sceptre_handler method makes multiple calls to
os.getcwd() in determining paths to add and then later paths to remove.
In the event that the sceptre_handler code then makes a call to
os.chdir, the second call ends up removing the wrong path.

This patch ensures that the paths removed are the same ones that are
added.
  • Loading branch information
alex-harvey-z3q committed Dec 11, 2019
1 parent eb18118 commit 5be4d13
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 6 deletions.
16 changes: 10 additions & 6 deletions sceptre/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,18 +148,20 @@ def _call_sceptre_handler(self):
:raises: IOError
:raises: TemplateSceptreHandlerError
"""

# Get relative path as list between current working directory and where
# the template is
# NB: this is a horrible hack...
relpath = os.path.relpath(self.path, os.getcwd()).split(os.path.sep)
relpaths_to_add = [
os.path.sep.join(relpath[:i+1])
paths_to_add = [
os.path.join(os.getcwd(), os.path.sep.join(relpath[:i+1]))
for i in range(len(relpath[:-1]))
]

# Add any directory between the current working directory and where
# the template is to the python path
for directory in relpaths_to_add:
sys.path.append(os.path.join(os.getcwd(), directory))
for path in paths_to_add:
sys.path.append(path)
self.logger.debug(
"%s - Getting CloudFormation from %s", self.name, self.path
)
Expand All @@ -179,8 +181,10 @@ def _call_sceptre_handler(self):
)
else:
raise e
for directory in relpaths_to_add:
sys.path.remove(os.path.join(os.getcwd(), directory))

for path in paths_to_add:
sys.path.remove(path)

return body

def upload_to_s3(self):
Expand Down
12 changes: 12 additions & 0 deletions tests/fixtures/templates/chdir.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# -*- coding: utf-8 -*-

from troposphere import Template

from os import chdir

def sceptre_handler(sceptre_user_data):
t = Template()

chdir("..")

return t.to_json()
15 changes: 15 additions & 0 deletions tests/test_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,21 @@ def test_body_with_generic_template(self):
expected_output_dict = json.loads(f.read())
assert output_dict == expected_output_dict

def test_body_with_chdir_template(self):
self.template.sceptre_user_data = None
self.template.name = "chdir"
current_dir = os.getcwd()
self.template.path = os.path.join(
os.getcwd(),
"tests/fixtures/templates/chdir.py"
)
try:
json.loads(self.template.body)
except ValueError:
assert False
finally:
os.chdir(current_dir)

def test_body_with_missing_file(self):
self.template.path = "incorrect/template/path.py"
with pytest.raises(IOError):
Expand Down

0 comments on commit 5be4d13

Please sign in to comment.