Interview Prep/Python for DevOps/Exceptions, context managers, files & logging

How do you write a config file atomically?

AdvancedConceptExceptions, context managers, files & logging
Answer

Write to a temp file in the same directory, flush and fsync, then os.replace() it over the target. os.replace is atomic on POSIX when source and destination are on the same filesystem, so readers see either the old file or the new one, never a half-written file.

import os, tempfile
def atomic_write(path, data):
    d = os.path.dirname(os.path.abspath(path))
    with tempfile.NamedTemporaryFile("w", dir=d, delete=False, encoding="utf-8") as tmp:
        tmp.write(data)
        tmp.flush()
        os.fsync(tmp.fileno())
    os.replace(tmp.name, path)

This is how we update nginx upstream files or kubeconfigs that other processes read.

All Python for DevOps questions Roadmap: Python for automation

More on Exceptions, context managers, files & logging