8 – Updating a Node image field from an external URL

I need to retrieve an image from an external URL and then save the image on Drupal’s file system, and then set the image as the image for a node. In D7, this was a pretty simple task, but it’s causing me issues in D8. In D7, here is what we have:

$file_info = system_retrieve_file($url, 'public://course_images/', TRUE);
if(!empty($file_info) && $file_info->fid) {
    $entity->field_image(0) = array('fid' => $file_info->fid);
}

I am trying the same thing in D8 but just receive this error Value is not valid entity which provides ZERO actual information about exactly what is wrong.

In D8, here is what I currently have:

$file = system_retrieve_file($image_url, 'public://course_images/', TRUE, FileSystemInterface::EXISTS_REPLACE);

if ($file && $file->id) {
  $course_node->set('field_image', (
    'target_id' => $file->id,
    'alt' => 'alt text',
    'title' => 'title'
  ));
}

I’ve also tried using $file->id() and $file->fid with no luck. I just don’t know how to access the file entity id!

I have tried to debug the $file object to figure this out using the logger

Drupal::logger('my_module')->notice('<pre><code>' . print_r($file, TRUE) . '</code></pre>');

but this code is in a cron job and adding that logger just makes the cron job fail with no error other than ‘Cron cannot get lock’ (again, another error with little to no information).

I can see that my file is being saved properly, but how can I access it’s node ID after saving to be able to set as the target_id of the image field?