docs: def write_file(path, content, owner='root', group='root', perms=0o444):
      """Create or overwrite a file with the contents of a byte string."""
      uid = pwd.getpwnam(owner).pw_uid
      gid = grp.getgrnam(group).gr_gid
      # lets see if we can grab the file and compare the context, to avoid doing
      # a write.
      existing_content = None
      existing_uid, existing_gid, existing_perms = None, None, None
      try:
          with open(path, 'rb') as target:
              existing_content = target.read()
          stat = os.stat(path)
          existing_uid, existing_gid, existing_perms = (
              stat.st_uid, stat.st_gid, stat.st_mode
          )
      except Exception:
          pass
      if content != existing_content:
          log("Writing file {} {}:{} {:o}".format(path, owner, group, perms),
              level=DEBUG)
          with open(path, 'wb') as target:
              os.fchown(target.fileno(), uid, gid)
              os.fchmod(target.fileno(), perms)
              if six.PY3 and isinstance(content, six.string_types):
                  content = content.encode('UTF-8')
              target.write(content)
          return
      # the contents were the same, but we might still need to change the
      # ownership or permissions.
      if existing_uid != uid:
          log("Changing uid on already existing content: {} -> {}"
              .format(existing_uid, uid), level=DEBUG)
          os.chown(path, uid, -1)
      if existing_gid != gid:
          log("Changing gid on already existing content: {} -> {}"
              .format(existing_gid, gid), level=DEBUG)
          os.chown(path, -1, gid)
      if existing_perms != perms:
          log("Changing permissions on existing content: {} -> {}"
              .format(existing_perms, perms), level=DEBUG)
          os.chmod(path, perms)