CCACHE_DIR: ${HOME}/ccache
     MACPORTS_CACHE: ${HOME}/macports-cache
 
+    MACOS_PACKAGE_LIST: >-
+      ccache
+      gmake
+      icu
+      kerberos5
+      lz4
+      openldap
+      openssl
+      p5.34-io-tty
+      p5.34-ipc-run
+      python312
+      tcl
+      zstd
+
   <<: *macos_task_template
 
   only_if: $CIRRUS_CHANGE_MESSAGE !=~ '.*\nci-os-only:.*' || $CIRRUS_CHANGE_MESSAGE =~ '.*\nci-os-only:[^\n]*(macos|darwin|osx).*'
   macports_cache:
     folder: ${MACPORTS_CACHE}
     fingerprint_script: |
-      # Include the OS major version in the cache key.  If the OS image changes
-      # to a different major version, we need to reinstall.
+      # Reinstall packages if the OS major version, the list of the packages
+      # to install or the MacPorts install script changes.
       sw_vers -productVersion | sed 's/\..*//'
-      # Also start afresh if we change our MacPorts install script.
+      echo $MACOS_PACKAGE_LIST
       md5 src/tools/ci/ci_macports_packages.sh
     reupload_on_changes: true
   setup_additional_packages_script: |
-    sh src/tools/ci/ci_macports_packages.sh \
-      ccache \
-      gmake \
-      icu \
-      kerberos5 \
-      lz4 \
-      openldap \
-      openssl \
-      p5.34-io-tty \
-      p5.34-ipc-run \
-      python312 \
-      tcl \
-      zstd
+    sh src/tools/ci/ci_macports_packages.sh $MACOS_PACKAGE_LIST
     # system python doesn't provide headers
     sudo /opt/local/bin/port select python3 python312
     # Make macports install visible for subsequent steps
 
     sudo port unsetrequested installed
 fi
 
-# if setting all the required packages as requested fails, we need
-# to install at least one of them
-if ! sudo port setrequested $packages > /dev/null 2>&1 ; then
-    echo not all required packages installed, doing so now
+# If setting all the required packages as requested fails, we need
+# to install at least one of them. Need to do so one-by-one as
+# port setrequested only reports failures for the first package.
+echo "checking if all required packages are installed"
+for package in $packages ; do
+  if ! sudo port setrequested $package > /dev/null 2>&1 ; then
     update_cached_image=1
+  fi
+done
+echo "done"
+if [ "$update_cached_image" -eq 1 ]; then
+    echo not all required packages installed, doing so now
     # to keep the image small, we deleted the ports tree from the image...
     sudo port selfupdate
     # XXX likely we'll need some other way to force an upgrade at some