How do customize settings.php during installation profile
You may find it easier to use a settings.common.php

Often during team projects, we have local settings.php with db credentials etc.. and a settings.common.php with settings common to the install and deployment environments.

You can add settings.common.php with an include / require line in settings.php

require 'settings.common.php'; // same directory, e.g sites/default/settings.common.php


and then write to it as needed during install.