Need to add a JS file into  using a custom module with custom twig template
You can attach custom tags to any render array from where it bubbles up into the HTML head. In the following sample I'm adding structured data when a certain block is viewed. $value then contains what's being printed between the opening and closing script tag.

/**
 * Implements hook_block_view_BASE_BLOCK_ID_alter().
 */
function MYMODULE_block_view_system_breadcrumb_block_alter(array &amp;$build, BlockPluginInterface $block) {

  // Get JSON-LD.
  if ($json_ld = \Drupal::service('easy_breadcrumb.structured_data_json_ld')
    -&gt;value()) {

    // Prepare script tag.
    $structured_data = [
      '#tag' =&gt; 'script',
      '#attributes' =&gt; ['type' =&gt; 'application/ld+json'],
      '#value' =&gt; $json_ld,
    ];

    // Add script tag.
    $build['#attached']['html_head'][] = [
      $structured_data,
      'easy_breadcrumb_structured_data_json_ld',
    ];
  }
}


I hope you get the idea how this can easily be adjusted to get your custom snippet into the head. You can keep your logic in hook_page_attachments_alter but then let it look more like in the following snippet. Maybe you don't even need any #value at all.

/**
 * Implements hook_page_attachments_alter().
 */
function MYMODULE_page_attachments_alter(array &amp;$attachments) {

  if ($js_file_url = \Drupal::config('MYMODULE.settings')-&gt;get('url')) {

    // Prepare script tag.
    $my_script = [
      '#tag' =&gt; 'script',
      '#attributes' =&gt; ['src' =&gt; $js_file_url],
      '#value' =&gt; 'test',
    ];

    // Add script tag.
    $attachments['#attached']['html_head'][] = [
      $my_script,
      'MYMODULE_my_script',
    ];
  }
}