diff --git a/platforms/common/spack_utils.sh b/platforms/common/spack_utils.sh
index 66cec0b83b684c5569c8b27ba765837204dbac28..e441424149e79c491b1061b9c78d00aa9dac0dc8 100644
--- a/platforms/common/spack_utils.sh
+++ b/platforms/common/spack_utils.sh
@@ -6,7 +6,14 @@ function _install_spack() {
 
   _init_spack "$SPACK_INIT_CMD" "$SPACK_ROOT"
 
+  # Adding a lock file to prevent race conditions.
+  UPSTREAMS_LOCK=${SPACK_ROOT}/etc/spack/upstreams.lock
+  while [ -f "${UPSTREAMS_LOCK}" ]; do
+    sleep 1
+  done
+
   if [ ! -z "${SPACK_UPSTREAMS}" ]; then
+    touch ${UPSTREAMS_LOCK}
     UPSTREAMS_CONFIG=${SPACK_ROOT}/etc/spack/upstreams.yaml
     echo "upstreams:" > $UPSTREAMS_CONFIG
     i=0
@@ -18,6 +25,7 @@ function _install_spack() {
       install_tree: $UP
 EOF
     done
+    rm ${UPSTREAMS_LOCK}
   fi
 
   if [ ! -z "${SPACK_EXTERNALS}" ] ; then