Problem
When you attempt to import a resource using the Google Cloud provider for Terraform, the operation fails.
When you run the terraform import command:
$ terraform import google_project.project_name test-project-123456
You receive an error message indicating that Terraform could not find default credentials.
Error: Attempted to load application default credentials since neither `credentials` nor `access_token` was set in the provider block. No credentials loaded. To use your gcloud credentials, run 'gcloud auth application-default login'. Original error: google: could not find default credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
Cause
When you use the Terraform CLI with HCP Terraform or Terraform Enterprise, commands such as terraform apply execute within the remote environment. However, the terraform import command always runs on your local machine.
Because it runs locally, terraform import does not have access to the remote workspace variables, including the Google Cloud credentials configured in your HCP Terraform or Terraform Enterprise workspace. To perform an import, you must provide equivalent credentials in your local environment.
Solutions
To resolve this issue, you must authenticate to Google Cloud on your local machine where you are running the terraform import command. You can use one of the following methods.
Solution 1: Use gcloud application-default credentials
The quickest method is to use the gcloud CLI to set your Application Default Credentials (ADC). This command opens a browser window for you to authenticate with your Google account.
Run the following command:
$ gcloud auth application-default login
Solution 2: Configure credentials in the provider block
You can explicitly configure credentials within the google provider block in your Terraform configuration. This method is useful if you need to define a specific service account for Terraform operations.
For detailed instructions, refer to the official documentation on configuring the provider.
Solution 3: Use a service account key file
You can authenticate by pointing to a service account key file using an environment variable. Download the JSON key file for your service account from the Google Cloud Console.
Export the path to this file as the GOOGLE_APPLICATION_CREDENTIALS environment variable.
$ export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/keyfile.json"
For more information, see the documentation on adding credentials via a key file.
Outcome
After you configure your local credentials using one of the solutions, run the terraform import command again. The command should now successfully authenticate with Google Cloud and import the resource into your Terraform state.