Skip to content

Commit

Permalink
Respect the preset permissions of config files
Browse files Browse the repository at this point in the history
It's sometimes desirable to specify the permissions or ownership of the
generated config file instead of setting the default 644 root:root.

If the file is already present, os-apply-config will just update the
contents and leave everything else alone.

Closes-Bug: #1246266
Change-Id: Idd41ec276dd04f517760c1dbd97c75e376840b41
  • Loading branch information
Tomas Sedovic committed Nov 18, 2013
1 parent 5ac22fc commit 086b6b1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
8 changes: 7 additions & 1 deletion os_apply_config/apply_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,17 @@ def print_key(

def write_file(path, contents):
logger.info("writing %s", path)
if os.path.exists(path):
stat = os.stat(path)
mode, uid, gid = stat.st_mode, stat.st_uid, stat.st_gid
else:
mode, uid, gid = 0o644, -1, -1
d = os.path.dirname(path)
os.path.exists(d) or os.makedirs(d)
with tempfile.NamedTemporaryFile(dir=d, delete=False) as newfile:
newfile.write(contents)
os.chmod(newfile.name, 0o644)
os.chmod(newfile.name, mode)
os.chown(newfile.name, uid, gid)
os.rename(newfile.name, path)

# return a map of filenames->filecontents
Expand Down
20 changes: 20 additions & 0 deletions os_apply_config/tests/test_apply_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,26 @@ def test_install_config_subhash(self):
assert os.path.exists(full_path)
self.assertEqual(open(full_path).read(), contents)

def test_respect_file_permissions(self):
fd, path = tempfile.mkstemp()
with os.fdopen(fd, 'w') as t:
t.write(json.dumps(CONFIG))
t.flush()
tmpdir = tempfile.mkdtemp()
template = "/etc/keystone/keystone.conf"
target_file = os.path.join(tmpdir, template[1:])
os.makedirs(os.path.dirname(target_file))
# File dosen't exist, use the default mode (644)
apply_config.install_config([path], TEMPLATES, tmpdir, False)
self.assertEqual(os.stat(target_file).st_mode, 0o100644)
self.assertEqual(open(target_file).read(), OUTPUT[template])
# Set a different mode:
os.chmod(target_file, 0o600)
apply_config.install_config([path], TEMPLATES, tmpdir, False)
# The permissions should be preserved
self.assertEqual(os.stat(target_file).st_mode, 0o100600)
self.assertEqual(open(target_file).read(), OUTPUT[template])

def test_build_tree(self):
self.assertEqual(apply_config.build_tree(
apply_config.template_paths(TEMPLATES), CONFIG), OUTPUT)
Expand Down

0 comments on commit 086b6b1

Please sign in to comment.