Repository: skypilot-org/skypilot
Issue: GCP credential setup issue

User set up their GCP project with
```
gcloud init
gcloud auth application-default login
```
and `sky check` showed `GCP: enabled`
but the user still met the below error with `sky launch`
```
...
GCP credential file is empty. Please make sure you have run: gcloud init
```
We had to remove the user's `.config/gcloud` directory and started over to make it work. 

Changed files:
sky/clouds/gcp.py, tests/conftest.py, sky/authentication.py, tests/test_optimizer_dryruns.py

diff --git a/sky/authentication.py b/sky/authentication.py
index 2fe30440..8cece97e 100644
--- a/sky/authentication.py
+++ b/sky/authentication.py
@@ -20,7 +20,6 @@ from sky import sky_logging
 from sky.adaptors import gcp
 from sky.utils import common_utils
 from sky.utils import subprocess_utils
-from sky.utils import ux_utils
 from sky.skylet.providers.lambda_cloud import lambda_utils
 
 logger = sky_logging.init_logger(__name__)
@@ -199,26 +198,8 @@ def setup_gcp_authentication(config: Dict[str, Any]) -> Dict[str, Any]:
         logger.info(
             f'OS Login is enabled for GCP project {project_id}. Running '
             'additional authentication steps.')
-        # Read the account information from the credential file, since the user
-        # should be set according the account, when the oslogin is enabled.
-        config_path = os.path.expanduser(clouds.gcp.GCP_CONFIG_PATH)
-        sky_backup_config_path = os.path.expanduser(
-            clouds.gcp.GCP_CONFIG_SKY_BACKUP_PATH)
-        assert os.path.exists(sky_backup_config_path), (
-            'GCP credential backup file '
-            f'{sky_backup_config_path!r} does not exist.')
-
-        with open(sky_backup_config_path, 'r') as infile:
-            for line in infile:
-                if line.startswith('account'):
-                    account = line.split('=')[1].strip()
-                    break
-            else:
-                with ux_utils.print_exception_no_traceback():
-                    raise RuntimeError(
-                        'GCP authentication failed, as the oslogin is enabled '
-                        f'but the file {config_path} does not contain the '
-                        'account information.')
+        account = clouds.gcp.GCP.get_current_user_identity()
+        account = account.split(' ')[0]
         config['auth']['ssh_user'] = account.replace('@', '_').replace('.', '_')
 
         # Add ssh key to GCP with oslogin
diff --git a/sky/clouds/gcp.py b/sky/clouds/gcp.py
index 63738fcd..6d6209c0 100644
--- a/sky/clouds/gcp.py
+++ b/sky/clouds/gcp.py
@@ -24,13 +24,6 @@ DEFAULT_GCP_APPLICATION_CREDENTIAL_PATH = os.path.expanduser(
     '~/.config/gcloud/'
     'application_default_credentials.json')
 
-# TODO(wei-lin): config_default may not be the config in use.
-# See: https://github.com/skypilot-org/skypilot/pull/1539
-GCP_CONFIG_PATH = '~/.config/gcloud/configurations/config_default'
-# Do not place the backup under the gcloud config directory, as ray
-# autoscaler can overwrite that directory on the remote nodes.
-GCP_CONFIG_SKY_BACKUP_PATH = '~/.sky/.sky_gcp_config_default'
-
 # Minimum set of files under ~/.config/gcloud that grant GCP access.
 _CREDENTIAL_FILES = [
     'credentials.db',
@@ -55,7 +48,6 @@ GCLOUD_INSTALLATION_COMMAND = f'pushd /tmp &>/dev/null && \\
     ~/google-cloud-sdk/install.sh -q >> {_GCLOUD_INSTALLATION_LOG} 2>&1 && \\
     echo "source ~/google-cloud-sdk/path.bash.inc > /dev/null 2>&1" >> ~/.bashrc && \\
     source ~/google-cloud-sdk/path.bash.inc >> {_GCLOUD_INSTALLATION_LOG} 2>&1; }} && \\
-    {{ cp {GCP_CONFIG_SKY_BACKUP_PATH} {GCP_CONFIG_PATH} > /dev/null 2>&1 || true; }} && \\
     popd &>/dev/null'
 
 # TODO(zhwu): Move the default AMI size to the catalog instead.
@@ -528,21 +520,6 @@ class GCP(clouds.Cloud):
         return True, None
 
     def get_credential_file_mounts(self) -> Dict[str, str]:
-        # Create a backup of the config_default file, as the original file can
-        # be modified on the remote cluster by ray causing authentication
-        # problems. The backup file will be updated to the remote cluster
-        # whenever the original file is not empty and will be applied
-        # appropriately on the remote cluster when neccessary.
-        if (os.path.exists(os.path.expanduser(GCP_CONFIG_PATH)) and
-                os.path.getsize(os.path.expanduser(GCP_CONFIG_PATH)) > 0):
-            subprocess.run(f'cp {GCP_CONFIG_PATH} {GCP_CONFIG_SKY_BACKUP_PATH}',
-                           shell=True,
-                           check=True)
-        elif not os.path.exists(os.path.expanduser(GCP_CONFIG_SKY_BACKUP_PATH)):
-            raise RuntimeError(
-                'GCP credential file is empty. Please make sure you '
-                'have run: gcloud init')
-
         # Excluding the symlink to the python executable created by the gcp
         # credential, which causes problem for ray up multiple nodes, tracked
         # in #494, #496, #483.
@@ -550,12 +527,11 @@ class GCP(clouds.Cloud):
             f'~/.config/gcloud/{filename}': f'~/.config/gcloud/{filename}'
             for filename in _CREDENTIAL_FILES
         }
-        credentials[GCP_CONFIG_SKY_BACKUP_PATH] = GCP_CONFIG_SKY_BACKUP_PATH
         return credentials
 
     @classmethod
     @functools.lru_cache(maxsize=1)  # Cache since getting identity is slow.
-    def get_current_user_identity(cls) -> Optional[str]:
+    def get_current_user_identity(cls) -> str:
         """Returns the email address + project id of the active user."""
         try:
             account = _run_output('gcloud auth list --filter=status:ACTIVE '
diff --git a/tests/conftest.py b/tests/conftest.py
index 9c20348f..7a1ba776 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -167,7 +167,3 @@ def enable_all_clouds(monkeypatch):
         lambda: enabled_clouds,
     )
     monkeypatch.setattr('sky.check.check', lambda *_args, **_kwargs: None)
-    config_file_backup = tempfile.NamedTemporaryFile(
-        prefix='tmp_backup_config_default', delete=False)
-    monkeypatch.setattr('sky.clouds.gcp.GCP_CONFIG_SKY_BACKUP_PATH',
-                        config_file_backup.name)
diff --git a/tests/test_optimizer_dryruns.py b/tests/test_optimizer_dryruns.py
index b30a7ae5..453bc81d 100644
--- a/tests/test_optimizer_dryruns.py
+++ b/tests/test_optimizer_dryruns.py
@@ -48,11 +48,6 @@ def _make_resources(
     )
     monkeypatch.setattr('sky.check.check', lambda *_args, **_kwargs: None)
 
-    config_file_backup = tempfile.NamedTemporaryFile(
-        prefix='tmp_backup_config_default', delete=False)
-    monkeypatch.setattr('sky.clouds.gcp.GCP_CONFIG_SKY_BACKUP_PATH',
-                        config_file_backup.name)
-
     # Should create Resources here, since it uses the enabled clouds.
     return sky.Resources(*resources_args, **resources_kwargs)