This Google Cloud Run function is designed to be used with gCloud-Ghost-Updater to restart a Google Cloud VM when httpPing notices the (Ghost Blog) VM is not available.
- You are using the Google Cloud Function httpPing to monitor your website.
- httpPing will notify your Google Cloud Run trigger URL when your site is up/down and has a key-value pair: "secret": "UNIQUE_PASSWORD"
- NOTE: This is definitely not for use with anything highly sensitive unless you take additional security measures
- Find Service Account: In the IAM section of the console locate the App Engine default service account, usually named
[email protected]
. - Edit: Click the pencil icon next to the service account.
- Add Role: Scroll and hit "Add Another Role."
- Choose Role: In the dropdown, go to "Compute Engine" and pick "Compute Instance Admin (v1)." This role allows the service account to manage Compute Engine instances across the Google Cloud project.
- Add 2nd Role: Click on “Add Another Role”.
- Choose Role: In the dropdown menu, select the “Cloud Functions” category and then choose the “Cloud Functions Invoker” role. This role allows the service account to invoke Cloud Functions.
- Save: Scroll down, click "Save."
- Run
- Create a Google Cloud Run v2 function named
RestartVMService
set Authentication to useHTTPS
andAllow unauthenticated invocations
. - Create a Runtime environment variable named
secret
and set its value to the UNIQUE_PASSWORD that you configured in httpping payload. - Update the
index.js
file with the content in this repository. Make sure to update theYOUR_PROJECT_ID
andEXTERNAL_STATIC_IP
variables with your own values. - Update the
package.js
file with the content in this repository.
To test the function, you can use the following curl command format:
curl -X POST -H "x-custom-secret: UNIQUE_PASSWORD" https://YOUR_ZONE-YOUR_PROJECT_ID-NUMBER.cloudfunctions.net/RestartVMService
For example if you customized it with your details it might look like:
curl -X POST -H "x-custom-secret: UNIQUE_PASSWORD" https://us-west1-ghost-blog-23221.cloudfunctions.net/RestartVMService
When the function is triggered, it performs the following steps:
- Validates the secret.
- Checks the error state.
- Authenticates with Google Cloud.
- Queries all zones in the project.
- Finds the Google Cloud instance that matches the given IP address.
- Selects the instance with the highest number in its name.
- Checks the status of the instance.
- Restarts or starts the instance, depending on its current status.
- Sends a response indicating whether the operation was successful or not.