title: Get the name or ID of the current Google Compute Instance
body: <p>I'm running a number of Google Compute Engine instances that run Python code, and I want to find the name or the ID of each instance from inside the instances.</p>
  
  <p>One solution I've found is to get the internal IP of the instance using:</p>
  
  <pre><code>import socket
  internal_ip = socket.gethostbyname(socket.gethostname())
  </code></pre>
  
  <p>Then I list all the instances:</p>
  
  <pre><code>from oauth2client.client import GoogleCredentials
  from googleapiclient.discovery import build
  
  credentials = GoogleCredentials.get_application_default()
  self.compute = build('compute', 'v1', credentials=credentials)
  result = self.compute.instances().list(project=project, zone=zone).execute()
  </code></pre>
  
  <p>Then I iterate over all the instances to check if the internal IP matches the IP of an instance:</p>
  
  <pre><code>for instance in result["items"]:
      if instance["networkInterfaces"][0]["networkIP"] == internal_ip:
          internal_id = instance["id"]
  </code></pre>
  
  <p>This works but it's a bit complicated, is there a more direct way to achieve the same thing, e.g. using Google's Python Client Library or the gcloud command line tool?</p>