~smoser/cloud-init/azure_dhcp

« back to all changes in this revision

Viewing changes to cloudinit/atomic_helper.py

  • Committer: Scott Moser
  • Date: 2016-08-05 15:37:33 UTC
  • Revision ID: smoser@ubuntu.com-20160805153733-9j8gn2nwcwvby083
re-add atomic_helper

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/python
 
2
# vi: ts=4 expandtab
 
3
 
 
4
import json
 
5
import os
 
6
import tempfile
 
7
 
 
8
 
 
9
def atomic_write_file(path, content, mode='w'):
 
10
    tf = None
 
11
    try:
 
12
        tf = tempfile.NamedTemporaryFile(dir=os.path.dirname(path),
 
13
                                         delete=False, mode=mode)
 
14
        tf.write(content)
 
15
        tf.close()
 
16
        os.rename(tf.name, path)
 
17
    except Exception as e:
 
18
        if tf is not None:
 
19
            os.unlink(tf.name)
 
20
        raise e
 
21
 
 
22
 
 
23
def atomic_write_json(path, data):
 
24
    return atomic_write_file(path, json.dumps(data, indent=1,
 
25
                                              sort_keys=True) + "\n")