Reputation: 3780
I would like to be able to listen for when a GCE instance is started, stopped, deleted. This is so that I can build a dashboard for users to view the status of machines. How can I do this?
Upvotes: 0
Views: 691
Reputation: 9810
You can use Cloud Function to implement such a workflow. Cloud Functions can't "listen" to GCE events directly but they can be triggered when a message is published to a specific PubSub topic.
Now, GCE VM events are actually logged in Cloud Logging, and logs matching a particular filter can be exported to a PubSub topic.
So in Cloud Logging, you could set an advanced log filter like so:
resource.type="gce_instance"
jsonPayload.event_subtype="compute.instances.stop" OR jsonPayload.event_subtype="compute.instances.start"
This filter will filter stop
and start
events from all VMs in your project. You can see a list of available events here.
Once you've defined the log filter, you can "create sink" and set it to send the filtered logs to a PubSub topic of your choice. More info on how to set up an export sink here.
Now that your event logs are sent to the PubSub topic, you can go to your PubSub topic list, select your topic and click the "Trigger Cloud Function" button. You'll be guided through setting up the Cloud Function that'll be triggered for every new message in that topic. The suggested function code (in nodejs 8 for example):
exports.helloPubSub = (event, context) => {
const pubsubMessage = event.data;
console.log(Buffer.from(pubsubMessage, 'base64').toString());
};
will log the message data where you'll find the event log info. You can then write your Cloud Function to perform whichever process you want, for example updating a Firestore database with the VM instance status.
Upvotes: 3