title: IAM Service Account Key vs Google Credentials File
body: <p>I'm writing code to generate and download a private key for a Google Cloud service account.</p>
  
  <p>Using the IAM API, I was able to <a href="https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/create" rel="noreferrer">create a service account</a>, and my call to <a href="https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts.keys/create" rel="noreferrer">generate a key</a> seems to be working. I get back a Service Account Key as described on the <a href="https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts.keys#ServiceAccountKey" rel="noreferrer">IAM API create key page</a>, like </p>
  
  <pre><code>{ 
    "privateKeyType": "TYPE_GOOGLE_CREDENTIALS_FILE",
    "privateKeyData": "random-key-stringkajdkjakjfke", ...
  }
  </code></pre>
  
  <p>I downloaded this file as a JSON response and am trying to authenticate with it:</p>
  
  <pre><code>gcloud auth activate-service-account --key-file=service-account-key-file.json
  </code></pre>
  
  <p>Unfortunately, I get an error stating
  <code>The .json key file is not in a valid format.</code></p>
  
  <p>When I go though the Google Cloud Console flow (IAM &amp; Admin -> Service accounts -> ... -> Create Key -> Create) I get a downloaded JSON file that looks like </p>
  
  <pre><code>{
    "type": "service_account",
    "private_key": "----BEGIN-PRIVATE-KEY-----",
    "auth_uri": "https://gaiastaging.corp.google.com/o/oauth2/auth",
  }
  </code></pre>
  
  <p>This file looks completely different than the response from the IAM API. Explains my error! Unfortunately, this format doesn't seem to be described anywhere. It's mentioned briefly in some <a href="https://cloud.google.com/vision/docs/common/auth" rel="noreferrer">docs</a>. Is it a Google Credentials File?</p>
  
  <p>I'd like to take the IAM response file/JSON and convert it to the second credentials file. I've tried writing some code to convert it, but there are some fields like <code>"auth_provider_x509_cert_url"</code> that I don't understand.</p>
  
  <p>Perhaps converting the file is the wrong approach as well? More generally:</p>
  
  <p>How can I generate a file and then use it to authenticate with gcloud?</p>
  
  <p>How should I describe/distinguish between both of the above files? Why is each type of file useful?</p>